<script lang="ts" setup>
import { computed, ref, watch } from 'vue';

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

import { Button, Input, message, Radio, RadioGroup, Textarea } from 'ant-design-vue';

import { auditStoreInput, getStoreInputDetail } from '../api';
import DoctorInputCardGrid from './DoctorInputCardGrid.vue';
import { getLinkedDoctors, isDoctorPending } from '../utils/doctorInputDisplay';

const auditStatus = ref<number>(1);
const auditRemark = ref<string>('');
const erpId = ref<string>('');
const mesId = ref<string>('');
const currentRow = ref<any>(null);
const gridApi = ref<any>(null);
const loading = ref(false);
const detailLoading = ref(false);
const allDoctors = ref<any[]>([]);
const selectedDoctorIds = ref<number[]>([]);

const pendingDoctorIds = computed(() =>
  allDoctors.value
    .filter((d) => isDoctorPending(d))
    .map((d) => Number(d.id))
    .filter((id) => id > 0),
);

const loadLinkedDoctors = async (storeInputId: number) => {
  detailLoading.value = true;
  allDoctors.value = [];
  selectedDoctorIds.value = [];
  try {
    const res = await getStoreInputDetail(storeInputId);
    allDoctors.value = getLinkedDoctors(res);
    selectedDoctorIds.value = allDoctors.value
      .filter((d) => isDoctorPending(d))
      .map((d) => Number(d.id))
      .filter((id) => id > 0);
  } catch (error) {
    console.error('加载关联医生失败:', error);
    message.error('加载关联医生失败');
  } finally {
    detailLoading.value = false;
  }
};

const selectAllPending = () => {
  selectedDoctorIds.value = [...pendingDoctorIds.value];
};

const clearSelection = () => {
  selectedDoctorIds.value = [];
};

const handleAudit = async () => {
  if (!currentRow.value) {
    message.error('数据错误');
    return;
  }

  if (auditStatus.value === 1 && !erpId.value.trim()) {
    message.error('审核通过时请填写 ERP ID');
    return;
  }

  loading.value = true;
  modalApi.setState({ confirmLoading: true });
  try {
    const payload: Parameters<typeof auditStoreInput>[0] = {
      id: currentRow.value.id,
      status: auditStatus.value,
      audit_remark: auditRemark.value,
      erp_id: auditStatus.value === 1 ? erpId.value.trim() : undefined,
      mes_id:
        auditStatus.value === 1 && mesId.value.trim()
          ? mesId.value.trim()
          : undefined,
    };
    if (auditStatus.value === 1 && selectedDoctorIds.value.length > 0) {
      payload.doctor_input_ids = [...selectedDoctorIds.value];
    }
    await auditStoreInput(payload);
    const doctorCount =
      auditStatus.value === 1 ? selectedDoctorIds.value.length : 0;
    message.success(
      doctorCount > 0
        ? `审核成功，已一并通过 ${doctorCount} 位医生预填`
        : '审核成功',
    );
    gridApi.value?.reload();
    modalApi.close();
    auditStatus.value = 1;
    auditRemark.value = '';
    erpId.value = '';
    mesId.value = '';
    allDoctors.value = [];
    selectedDoctorIds.value = [];
  } catch (error) {
    console.error('审核失败:', error);
    message.error('审核失败，请稍后重试');
  } finally {
    loading.value = false;
    modalApi.setState({ confirmLoading: false });
  }
};

const [ModalComponent, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: handleAudit,
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values, gridApi: api } = modalApi.getData<Record<string, any>>();
      currentRow.value = values;
      gridApi.value = api;
      auditStatus.value = 1;
      auditRemark.value = '';
      erpId.value = values?.erp_id != null ? String(values.erp_id) : '';
      mesId.value = values?.mes_id != null ? String(values.mes_id) : '';
      if (values?.id) {
        await loadLinkedDoctors(Number(values.id));
      } else {
        message.warning('门店数据异常，无法加载关联医生');
      }
    } else {
      allDoctors.value = [];
      selectedDoctorIds.value = [];
    }
  },
});

watch(auditStatus, (v) => {
  if (v !== 1) {
    selectedDoctorIds.value = [];
  } else if (currentRow.value?.id && pendingDoctorIds.value.length) {
    selectedDoctorIds.value = [...pendingDoctorIds.value];
  }
});
</script>

<template>
  <ModalComponent
    title="审核录入信息"
    class="w-[720px]"
    :confirm-loading="loading"
  >
    <div class="space-y-4 p-4">
      <div>
        <div class="mb-2 font-semibold">审核结果：</div>
        <RadioGroup v-model:value="auditStatus">
          <Radio :value="1">审核通过</Radio>
          <Radio :value="2">审核拒绝</Radio>
        </RadioGroup>
      </div>
      <div v-if="auditStatus === 1">
        <div class="mb-2 font-semibold">ERP ID：</div>
        <Input v-model:value="erpId" placeholder="审核通过时必填" />
      </div>
      <div v-if="auditStatus === 1">
        <div class="mb-2 font-semibold">MES ID：</div>
        <Input v-model:value="mesId" placeholder="可选，煎药中心编码" />
      </div>
      <div v-if="auditStatus === 1">
        <div class="mb-2 flex flex-wrap items-center justify-between gap-2">
          <div>
            <div class="font-semibold">一并审核关联医生（可选）</div>
            <div class="text-xs text-gray-500">点击卡片选中/取消，悬停查看详情</div>
          </div>
          <div v-if="pendingDoctorIds.length > 0" class="flex gap-2">
            <Button size="small" type="link" @click="selectAllPending">全选</Button>
            <Button size="small" type="link" @click="clearSelection">取消全选</Button>
          </div>
        </div>
        <div v-if="detailLoading" class="text-sm text-gray-400">加载中...</div>
        <div v-else-if="allDoctors.length === 0" class="text-sm text-gray-400">
          暂无关联医生预填
        </div>
        <DoctorInputCardGrid
          v-else
          v-model:selected-ids="selectedDoctorIds"
          :doctors="allDoctors"
          selectable
          only-pending-selectable
        />
      </div>
      <div>
        <div class="mb-2 font-semibold">审核备注：</div>
        <Textarea
          v-model:value="auditRemark"
          :rows="4"
          placeholder="请输入审核备注（可选）"
        />
      </div>
    </div>
  </ModalComponent>
</template>
