<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerModal"
    :title="getTitle"
    :width="width"
    @ok="handleSubmit"
    :showFooter="true"
  >
    <div class="!pl-8 !pt-4">
      <BasicForm @register="registerForm" layout="vertical" />
      <div v-if="type != DiagnosisEnum.firstDialysis_field">
        <div class="mb-4">
          <a-button type="primary" shape="round" @click="handleAdd">
            <template #icon>
              <PlusOutlined />
            </template>
            添加
          </a-button>
        </div>
        <!-- 过敏原添加 -->
        <div v-if="type == DiagnosisEnum.allergic_field">
          <BasicTable @register="registerTable" @edit-change="callEditChange">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction :actions="createActions(record, column)" />
              </template>
            </template>
          </BasicTable>
        </div>
        <div v-if="type == DiagnosisEnum.operation_field">
          <BasicTable @register="registerTableOperation" @edit-change="callEditChange">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction :actions="createActions(record, column)" />
              </template>
            </template>
          </BasicTable>
        </div>
        <div v-if="type == DiagnosisEnum.contagious_field">
          <BasicTable @register="registerTableContagious" @edit-change="callEditChange">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction :actions="createActions(record, column)" />
              </template>
            </template>
          </BasicTable>
        </div>
        <div
          v-if="
            type == DiagnosisEnum.complications_field ||
            type == DiagnosisEnum.clinic_field ||
            type == DiagnosisEnum.pathological_field ||
            type == DiagnosisEnum.ckd_field
          "
        >
          <BasicTable @register="registerTableMulti" @edit-change="callEditChange">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction :actions="createActions(record, column)" />
              </template>
            </template>
          </BasicTable>
        </div>
        <div v-if="type == DiagnosisEnum.elseRemark_field">
          <BasicTable @register="registerTableOther" @edit-change="callEditChange">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction :actions="createActions(record, column)" />
              </template>
            </template>
          </BasicTable>
        </div>
      </div>
      <!-- {{ type }} -->
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, unref, nextTick, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicTable, useTable, TableAction, BasicColumn, ActionItem } from '/@/components/Table';
  import { PlusOutlined } from '@ant-design/icons-vue';

  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    dataFormSchema,
    columnsAllergic,
    DiagnosisEnum,
    columnsMulti,
    columnsContagious,
    columnsOther,
    columnsOperation,
  } from './data';
  import {
    archivesDiagnosisHistorySingleAddOrEdit,
    archivesDiagnosisHistoryMultiAddOrEdit,
  } from '/@/api/biz/archives/diagnosisHistoryApi';
  import { nanoid } from 'nanoid';
  import { listDictModel, listDictModelBatch } from '@/api/common';
  import dayjs from 'dayjs';

  const emit = defineEmits(['success', 'register']);

  const getTitle = ref('编辑');
  const width = '850px';
  const isSingle = ref(true);
  const type = ref('');
  const typeOptions = ref([]);
  const rowId = ref('');
  const patientBasicId = ref('');
  // 表格数据
  // 过敏史
  const tableDataAllergic = ref([]);
  const tableRecordType = ref('');
  // 传染病史
  const tableDataContagious = ref([]);
  const tableDataOperation = ref([]);

  const tableDataMulti = ref([]);
  const tableDataOther = ref([]);

  const { createMessage } = useMessage();
  const bizDictOptions = reactive<any>({});
  const bizDictData = ref([
    { key: 'allergic', dictCode: 'allergic' },
    { key: 'allergic_food', dictCode: 'allergic_food' },
    { key: 'allergic_touch', dictCode: 'allergic_touch' },
    { key: 'allergic_air', dictCode: 'allergic_air' },
    { key: 'allergic_inject', dictCode: 'allergic_inject' },
    { key: 'contagious', dictCode: 'contagious' },
    { key: 'pb_epidemic', dictCode: 'pb_epidemic' },
    { key: 'complications', dictCode: 'complications' },
    { key: 'complications_breath', dictCode: 'complications_breath' },
    { key: 'complications_blood', dictCode: 'complications_blood' },
    { key: 'complications_incretion', dictCode: 'complications_incretion' },
    { key: 'clinic', dictCode: 'clinic' },
    { key: 'clinic_breath', dictCode: 'clinic_breath' },
    { key: 'clinic_heart', dictCode: 'clinic_heart' },
    { key: 'clinic_blood', dictCode: 'clinic_blood' },
    { key: 'clinic_hbgr', dictCode: 'clinic_hbgr' },
    { key: 'pathological', dictCode: 'pathological' },
    { key: 'pathological_breath', dictCode: 'pathological_breath' },
    { key: 'pathological_heart', dictCode: 'pathological_heart' },
    { key: 'pathological_blood', dictCode: 'pathological_blood' },
    { key: 'pathological_hbgr', dictCode: 'pathological_hbgr' },
    { key: 'ckd', dictCode: 'ckd' },
    { key: 'ckd_breath', dictCode: 'ckd_breath' },
    { key: 'ckd_heart', dictCode: 'ckd_heart' },
    { key: 'ckd_blood', dictCode: 'ckd_blood' },
    { key: 'ckd_hbgr', dictCode: 'ckd_hbgr' },
  ]);
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    console.log('🚀 ~ file: FormModal.vue:52 ~ data:', data);
    const res = await listDictModelBatch(bizDictData.value.map(ele => ele.dictCode));
    for (const i in res) {
      const filter = bizDictData.value.filter(ele => ele.dictCode == i)[0];
      bizDictOptions[filter.key] = res[i];
    }
    tableDataAllergic.value = [];
    type.value = data.type || '';
    typeOptions.value = data.dictOptions;
    rowId.value = data?.id || '';
    patientBasicId.value = data?.patientBasicId || '';
    isSingle.value = data.isSingle;
    getTitle.value = `${data.id ? '编辑' : '新增'} — ${data.title}`;
    // 其他诊断
    if (type.value == DiagnosisEnum.elseRemark_field) {
      tableDataOther.value =
        (data.multiContent.length &&
          data.multiContent.map(ele => {
            return {
              remark: ele.remark,
              id: nanoid(5),
            };
          })) ||
        [];
      console.log('🚀 ~ file: FormModal.vue:179 ~ tableDataOther.value:', tableDataOther.value);
      await nextTick();
      await setTableDataOther(tableDataOther.value);
    }
    // 过敏原
    if (type.value == DiagnosisEnum.allergic_field) {
      tableDataAllergic.value =
        (data.content.length &&
          data.content.map(ele => {
            const nameOptions = bizDictOptions[ele.contentType];
            return {
              type: type.value,
              contentType: ele.contentType,
              typeOptions: typeOptions.value,
              name: ele.multiName,
              nameOptions,
              id: nanoid(5),
            };
          })) ||
        [];
      await nextTick();
      await setTableDataAllergic(tableDataAllergic.value);
    }
    // 手术史
    if (type.value == DiagnosisEnum.operation_field) {
      tableDataOperation.value =
        (data.content.length &&
          data.content.map(ele => {
            return {
              type: type.value,
              singleName: ele.singleName,
              recordTime: dayjs(ele.recordTime).format('YYYY-MM-DD'),
              remark: ele.remark,
              id: nanoid(5),
            };
          })) ||
        [];
      await nextTick();
      await setTableDataOperation(tableDataOperation.value);
    }
    // 传染病史
    if (type.value == DiagnosisEnum.contagious_field) {
      console.log('🚀 ~ file: FormModal.vue:178 ~ data.data:', data);
      tableDataContagious.value =
        (data.content.length &&
          data.content.map(ele => {
            return {
              type: type.value,
              contentType: ele.contentType,
              typeOptions: typeOptions.value,
              startTime: ele.startTime ? dayjs(ele.startTime).format('YYYY-MM-DD') : '',
              endTime: ele.endTime ? dayjs(ele.endTime).format('YYYY-MM-DD') : '',
              status: ele.status,
              remark: ele.remark,
              id: nanoid(5),
            };
          })) ||
        [];
      await nextTick();
      await setTableDataContagious(tableDataContagious.value);
    }
    // 合并症类型、临床诊断类型、病理类型、CKD类型
    if (
      type.value == DiagnosisEnum.complications_field ||
      type.value == DiagnosisEnum.clinic_field ||
      type.value == DiagnosisEnum.pathological_field ||
      type.value == DiagnosisEnum.ckd_field
    ) {
      console.log('🚀 ~ file: FormModal.vue:178 ~ data.data:', data);
      tableDataMulti.value =
        (data.multiContent.length &&
          data.multiContent.map(ele => {
            const nameOptions = bizDictOptions[ele.type];
            return {
              type: type.value,
              contentType: ele.type,
              typeOptions: typeOptions.value,
              name: ele.multiName || [],
              nameOptions,
              id: nanoid(5),
            };
          })) ||
        [];
      await nextTick();
      await setTableDataMulti(tableDataMulti.value);
    }
    let resData = {} as any;
    // resData = {
    //   recordTime: data.isSingle ? data.content?.recordTime : '',
    //   name: data.isSingle ? useUser.getUserInfo?.nickname,
    //   type: type.value,
    // };
    resData = {
      recordTime: data.updateTime
        ? dayjs(data.updateTime).format('YYYY-MM-DD')
        : dayjs().format('YYYY-MM-DD'),
      name: data.updatorName,
      type: type.value,
    };
    // 首次透析方式
    if (type.value == DiagnosisEnum.firstDialysis_field) {
      resData.firstDialysisType = data.content[0]?.contentType;
      resData.firstDialysisDate = dayjs(data.content[0]?.recordTime || Date.now()).format(
        'YYYY-MM-DD',
      );
      resData.recordTime = dayjs(data.updateTime || Date.now()).format('YYYY-MM-DD');
    }
    await setFieldsValue({
      ...resData,
    });
  });
  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: dataFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
    baseColProps: {
      span: 12,
    },
    wrapperCol: {
      span: 22,
    },
  });
  const useTbaleObj = {
    rowKey: 'id',
    showIndexColumn: false,
    bordered: true,
    striped: false,
    pagination: false,
    maxHeight: 200,
    actionColumn: {
      width: 40,
      title: '操作',
      dataIndex: 'action',
    },
  };
  // 过敏史 allergic
  const [
    registerTable,
    { setTableData: setTableDataAllergic, getDataSource: getDataSourceAllergic },
  ] = useTable({
    ...useTbaleObj,
    dataSource: tableDataAllergic.value,
    columns: columnsAllergic,
  });
  // 传染病 contagious
  const [
    registerTableContagious,
    { setTableData: setTableDataContagious, getDataSource: getDataSourceContagious },
  ] = useTable({
    ...useTbaleObj,
    dataSource: tableDataContagious.value,
    columns: columnsContagious,
  });
  const [
    registerTableOperation,
    { setTableData: setTableDataOperation, getDataSource: getDataSourceOperation },
  ] = useTable({
    ...useTbaleObj,
    dataSource: tableDataOperation.value,
    columns: columnsOperation,
  });
  // 治疗前合并症 contagious
  const [
    registerTableMulti,
    { setTableData: setTableDataMulti, getDataSource: getDataSourceMulti },
  ] = useTable({
    ...useTbaleObj,
    dataSource: tableDataMulti.value || [],
    columns: columnsMulti,
  });
  // 其他
  const [
    registerTableOther,
    { setTableData: setTableDataOther, getDataSource: getDataSourceOther },
  ] = useTable({
    ...useTbaleObj,
    dataSource: tableDataOther.value,
    columns: columnsOther,
  });
  // 创建 删除 按钮
  function createActions(record, column: BasicColumn): ActionItem[] {
    return [
      {
        auth: 'archives:diagnosisHistory:edit',
        icon: 'icon-xt-details_delete_default|iconfont',
        tooltip: '删除',
        popConfirm: {
          title: '是否取消删除',
          confirm: handleDel.bind(null, record, column),
        },
      },
    ];
  }
  async function handleAdd() {
    if (type.value == DiagnosisEnum.allergic_field) {
      tableDataAllergic.value.push({
        type: type.value,
        contentType: '',
        typeOptions: typeOptions.value,
        name: [],
        nameOptions: [],
        id: nanoid(5),
      });
      console.log(
        '🚀 ~ file: FormModal.vue:135 ~ handleAdd ~ tableDataAllergic.value:',
        tableDataAllergic.value,
      );
      await nextTick();
      await setTableDataAllergic(tableDataAllergic.value);
    }
    if (type.value == DiagnosisEnum.operation_field) {
      tableDataOperation.value.push({
        type: type.value,
        singleName: '',
        recordTime: dayjs().format('YYYY-MM-DD'),
        remark: '',
        id: nanoid(5),
      });
      console.log(
        '🚀 ~ file: FormModal.vue:135 ~ handleAdd ~ tableDataOperation.value:',
        tableDataOperation.value,
      );
      await nextTick();
      await setTableDataOperation(tableDataOperation.value);
    }
    if (type.value == DiagnosisEnum.contagious_field) {
      tableDataContagious.value.push({
        type: type.value,
        contentType: '',
        startTime: '',
        endTime: '',
        status: 'contagious_status_alive',
        remark: '',
        id: nanoid(5),
      });
      console.log(
        '🚀 ~ file: FormModal.vue:135 ~ handleAdd ~ tableDataAllergic.value:',
        tableDataContagious.value,
      );
      await nextTick();
      await setTableDataContagious(tableDataContagious.value);
    }
    if (
      type.value == DiagnosisEnum.complications_field ||
      type.value == DiagnosisEnum.clinic_field ||
      type.value == DiagnosisEnum.pathological_field ||
      type.value == DiagnosisEnum.ckd_field
    ) {
      tableDataMulti.value.push({
        type: type.value,
        contentType: '',
        typeOptions: typeOptions.value,
        name: [],
        nameOptions: [],
        id: nanoid(5),
      });
      console.log(
        '🚀 ~ file: FormModal.vue:135 ~ handleAdd ~ tableDataAllergic.value:',
        tableDataMulti.value,
      );
      await nextTick();
      await setTableDataMulti(tableDataMulti.value);
    }
    if (type.value == DiagnosisEnum.elseRemark_field) {
      tableDataOther.value.push({
        type: type.value,
        remark: '',
        id: nanoid(5),
      });
      console.log(
        '🚀 ~ file: FormModal.vue:135 ~ handleAdd ~ tableDataAllergic.value:',
        tableDataOther.value,
      );
      await nextTick();
      await setTableDataOther(tableDataOther.value);
    }
  }

  async function handleDel(record) {
    console.log('🚀 ~ file: FormModal.vue:488 ~ handleDel ~ record:', record);
    let data = [];
    let index = null;
    if (type.value == DiagnosisEnum.operation_field) {
      data = getDataSourceOperation();
      index = data.findIndex(item => item.id === record.id);
      tableDataOperation.value.splice(index, 1);
      setTableDataOperation(tableDataOperation.value);
    }
    if (type.value == DiagnosisEnum.allergic_field) {
      data = getDataSourceAllergic();
      index = data.findIndex(item => item.id === record.id);
      tableDataAllergic.value.splice(index, 1);
      setTableDataAllergic(tableDataAllergic.value);
    }
    if (type.value == DiagnosisEnum.contagious_field) {
      data = getDataSourceContagious();
      index = data.findIndex(item => item.id === record.id);
      tableDataContagious.value.splice(index, 1);
      setTableDataContagious(tableDataContagious.value);
    }
    if (type.value == DiagnosisEnum.elseRemark_field) {
      data = getDataSourceOther();
      index = data.findIndex(item => item.id === record.id);
      tableDataOther.value.splice(index, 1);
      setTableDataOther(tableDataOther.value);
    }
    if (!isSingle.value && type.value != DiagnosisEnum.elseRemark_field) {
      data = getDataSourceMulti();
      index = data.findIndex(item => item.id === record.id);
      tableDataMulti.value.splice(index, 1);
      setTableDataMulti(tableDataMulti.value);
    }
  }
  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      const sendData = {
        content: [],
        multiContent: [],
        id: isSingle.value ? '' : rowId.value,
        patientBasicId: patientBasicId.value,
        type: type.value,
      };
      setModalProps({ confirmLoading: true });
      // 首次透析
      if (type.value == DiagnosisEnum.firstDialysis_field) {
        sendData.content = [
          {
            recordTime: values.firstDialysisDate,
            contentType: values.firstDialysisType,
          },
        ];
      }
      // 手术史
      if (type.value == DiagnosisEnum.operation_field) {
        sendData.content = tableDataOperation.value.map(ele => {
          return {
            singleName: ele.singleName,
            recordTime: ele.recordTime,
            remark: ele.remark,
          };
        });
      }
      // 过敏史
      if (type.value == DiagnosisEnum.allergic_field) {
        sendData.content = tableDataAllergic.value.map(ele => {
          return {
            contentType: ele.contentType,
            multiName: ele.name,
          };
        });
      }
      // 传染病史
      if (type.value == DiagnosisEnum.contagious_field) {
        sendData.content = tableDataContagious.value.map(ele => {
          return {
            contentType: ele.contentType,
            status: ele.status,
            startTime: ele.startTime,
            endTime: ele.endTime,
            remark: ele.remark,
          };
        });
      }
      // 合并症类型、临床诊断类型、病理类型、CKD类型 编辑（添加）
      if (
        type.value == DiagnosisEnum.complications_field ||
        type.value == DiagnosisEnum.clinic_field ||
        type.value == DiagnosisEnum.pathological_field ||
        type.value == DiagnosisEnum.ckd_field
      ) {
        sendData.multiContent = tableDataMulti.value.map(ele => {
          return {
            type: ele.contentType,
            multiName: ele.name,
            remark: '',
          };
        });
      }
      // 其他编辑（添加）
      if (type.value == DiagnosisEnum.elseRemark_field) {
        sendData.multiContent = tableDataOther.value.map(ele => {
          return {
            type: '',
            multiName: [],
            remark: ele.remark,
          };
        });
      }
      console.log('🚀 ~ file: FormModal.vue:528 ~ handleSubmit ~ sendData:', sendData);
      unref(isSingle)
        ? await archivesDiagnosisHistorySingleAddOrEdit(sendData)
        : await archivesDiagnosisHistoryMultiAddOrEdit(sendData);
      createMessage.success(`${rowId.value ? '编辑' : '新增'}成功！`);
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  // 回调
  async function callEditChange({ record }) {
    // console.log('🚀 ~ file: FormModal.vue:638 ~ callEditChange ~ record:', record);
    // console.log(
    //   '🚀 ~ file: FormModal.vue:648 ~ callEditChange ~ tableRecordType.value:',
    //   tableRecordType.value,
    // );
    if (
      record.type == DiagnosisEnum.complications_field ||
      record.type == DiagnosisEnum.clinic_field ||
      record.type == DiagnosisEnum.pathological_field ||
      record.type == DiagnosisEnum.ckd_field ||
      record.type == DiagnosisEnum.allergic_field
    ) {
      if (tableRecordType.value != record.contentType || !record.nameOptions.length) {
        tableRecordType.value = record.contentType;
        let res = [];
        res = await listDictModel({ dictCode: record.contentType });
        record.nameOptions = res;
        record.name = [];
      }
      if (record.name.length > 3) {
        // createMessage.error('每次最多选择4个');
        record.nameOptions = record.nameOptions.map(ele => {
          if (!record.name.includes(ele.value)) {
            ele.disabled = true;
          }
          return ele;
        });
      } else {
        record.nameOptions = record.nameOptions.map(ele => {
          ele.disabled = false;
          return ele;
        });
      }
    }
  }
</script>
<style lang="less" scoped>
  ::v-deep(.ant-btn-link) {
    color: rgb(61 65 85 / 100%);
  }

  ::v-deep(.ant-table-body) {
    height: 200px !important;
  }
</style>
