<script lang="ts" setup>
/**
 * 排班变更日志详情：基础信息 + 结构化前后快照对照
 * before 是「按日期分组」的原排班（无键日期=原本走默认规则），
 * after 是本次统一应用到全部选中日期的新排班（空对象=恢复默认规则）
 */
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Descriptions, Tag } from 'ant-design-vue';

import { getDoctorScheduleLogDetail } from '../api';
import { scheduleActionColor } from '../config/constants';

const data = ref<Record<string, any>>({});
const loading = ref(false);

/** 涉及日期数组（后端 dates JSON 已解码） */
const dates = computed<string[]>(() =>
  Array.isArray(data.value?.dates) ? data.value.dates : [],
);

/** 变更后快照：{is_rest, slots} 或 空对象（恢复默认） */
const after = computed<Record<string, any>>(() =>
  data.value?.after_snapshot && typeof data.value.after_snapshot === 'object'
    ? data.value.after_snapshot
    : {},
);

/** 变更后是否为「恢复默认规则」（空对象） */
const afterIsClear = computed(() => Object.keys(after.value).length === 0);

/** 变更前快照：{日期: {is_rest, slots}}，转成有序数组渲染 */
const beforeEntries = computed<Array<{ date: string; snap: Record<string, any> }>>(() => {
  const snap = data.value?.before_snapshot;
  if (!snap || typeof snap !== 'object') return [];
  return Object.keys(snap)
    .sort()
    .map((date) => ({ date, snap: snap[date] || {} }));
});

/** 时段行文本：「上午 08:30-12:00 号源20」 */
function slotText(slot: Record<string, any>): string {
  const name = slot?.slot_name || '时段';
  return `${name} ${slot?.start_time || ''}-${slot?.end_time || ''} 号源${slot?.capacity ?? 0}`;
}

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: true,
  draggable: true,
  showConfirmButton: false,
  cancelText: '关闭',
  onCancel() {
    modalApi.close();
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      data.value = {};
      return;
    }
    const payload = modalApi.getData<{ id?: number; values?: Record<string, any> }>();
    const id = Number(payload?.id || payload?.values?.id || 0);
    if (id <= 0) {
      data.value = payload?.values || {};
      return;
    }
    loading.value = true;
    modalApi.setState({ loading: true });
    try {
      const res = await getDoctorScheduleLogDetail(id);
      data.value = res?.data || res || {};
    } catch {
      data.value = payload?.values || {};
    } finally {
      loading.value = false;
      modalApi.setState({ loading: false });
    }
  },
});
</script>

<template>
  <Modal class="w-[92%] md:w-[760px]" title="排班变更详情">
    <Descriptions
      :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }"
      bordered
      size="small"
    >
      <Descriptions.Item label="操作时间">{{ data.created_at }}</Descriptions.Item>
      <Descriptions.Item label="操作人">
        {{ data.operator_name || '-' }}
        <Tag class="ml-1">{{ data.user_type_txt || '-' }}</Tag>
      </Descriptions.Item>
      <Descriptions.Item label="门店">{{ data.store_name || `#${data.store_id || 0}` }}</Descriptions.Item>
      <Descriptions.Item label="医生">{{ data.doctor_name || `#${data.doctor_id || 0}` }}</Descriptions.Item>
      <Descriptions.Item label="变更动作">
        <Tag :color="scheduleActionColor(Number(data.action))">
          {{ data.action_txt || data.action }}
        </Tag>
        <template v-if="data.template_name">「{{ data.template_name }}」</template>
      </Descriptions.Item>
      <Descriptions.Item label="批次号">{{ data.batch_no || '-' }}</Descriptions.Item>
      <Descriptions.Item :span="2" label="涉及日期">
        <div class="date-chips">
          <Tag v-for="d in dates" :key="d">{{ d }}</Tag>
          <span v-if="dates.length === 0">-</span>
        </div>
      </Descriptions.Item>
      <Descriptions.Item v-if="data.remark" :span="2" label="备注">
        {{ data.remark }}
      </Descriptions.Item>
    </Descriptions>

    <!-- 前后对照：左（变更前按日期）右（变更后统一） -->
    <div class="diff">
      <div class="diff__col">
        <div class="diff__head">变更前</div>
        <div v-if="beforeEntries.length === 0" class="diff__empty">
          所选日期原本均走默认排班规则（无单独日排班）
        </div>
        <div v-else class="diff__list">
          <div v-for="item in beforeEntries" :key="item.date" class="diff__row">
            <span class="diff__date">{{ item.date }}</span>
            <template v-if="Number(item.snap.is_rest) === 1">
              <Tag color="red">休诊</Tag>
            </template>
            <template v-else>
              <span
                v-for="(slot, i) in item.snap.slots || []"
                :key="i"
                class="diff__slot"
              >
                {{ slotText(slot) }}
              </span>
            </template>
          </div>
          <div class="diff__note">未列出的日期原本走默认规则</div>
        </div>
      </div>
      <div class="diff__col">
        <div class="diff__head">变更后（应用到全部选中日期）</div>
        <div v-if="afterIsClear" class="diff__empty">恢复默认排班规则</div>
        <template v-else>
          <Tag v-if="Number(after.is_rest) === 1" color="red">休诊</Tag>
          <div v-else class="diff__list">
            <span
              v-for="(slot, i) in after.slots || []"
              :key="i"
              class="diff__slot diff__slot--after"
            >
              {{ slotText(slot) }}
            </span>
          </div>
        </template>
      </div>
    </div>
  </Modal>
</template>

<style scoped>
.date-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  max-height: 120px;
  overflow-y: auto;
}

.diff {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  margin-top: 12px;
}

@media (max-width: 640px) {
  .diff {
    grid-template-columns: 1fr;
  }
}

.diff__col {
  padding: 10px 12px;
  border: 1px solid hsl(var(--border));
  border-radius: 10px;
}

.diff__head {
  margin-bottom: 8px;
  font-size: 13px;
  font-weight: 600;
  color: hsl(var(--foreground));
}

.diff__empty {
  font-size: 12px;
  color: hsl(var(--muted-foreground));
}

.diff__list {
  display: flex;
  flex-direction: column;
  gap: 6px;
  max-height: 260px;
  overflow-y: auto;
}

.diff__row {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
  font-size: 12px;
}

.diff__date {
  min-width: 84px;
  font-weight: 600;
  color: hsl(var(--foreground));
  font-variant-numeric: tabular-nums;
}

.diff__slot {
  padding: 1px 8px;
  font-size: 12px;
  color: hsl(var(--muted-foreground));
  background: hsl(var(--muted) / 0.35);
  border-radius: 6px;
}

.diff__slot--after {
  color: hsl(var(--primary));
  background: hsl(var(--primary) / 0.1);
}

.diff__note {
  font-size: 11px;
  color: hsl(var(--muted-foreground) / 0.7);
}
</style>
