<template>
  <BasicDrawer
    v-bind="$attrs"
    destroyOnClose
    @register="registerDrawer"
    :title="getTitle"
    :width="width"
    @ok="handleSubmit"
    :showFooter="true"
  >
    <BasicForm
      @register="registerForm"
      layout="vertical"
      class="!px-6 !pt-4"
      @field-value-change="callFormFieldChange"
    >
      <template #suppliesTemplate>
        <div>
          <a-button type="primary" shape="round" @click="handleAdd">
            <template #icon>
              <PlusOutlined />
            </template>
            添加
          </a-button>
          <div class="w-full mt-2">
            <BasicTable @register="registerTable">
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'action'">
                  <TableAction
                    :actions="[
                      {
                        auth: 'archives:diagnosisHistory:edit',
                        icon: 'icon-xt-details_delete_default|iconfont',
                        tooltip: '删除',
                        popConfirm: {
                          title: '是否取消删除',
                          placement: 'left',
                          confirm: handleDel.bind(null, record, column),
                        },
                      },
                    ]"
                  />
                </template>
              </template>
            </BasicTable>
          </div>
        </div>
      </template>
    </BasicForm>
    <FormDrawerHistory @register="registerDrawerHistory" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, reactive, unref, nextTick } from 'vue';
  import { BasicDrawer, useDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { columnsDrawer, dataFormSchema } from './data';
  import { listDictModel } from '/@/api/common';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { nanoid } from 'nanoid';
  import {
    archivesFormulaTemplateAdd,
    archivesFormulaTemplateDetail,
    archivesFormulaTemplateEdit,
  } from '@/api/biz/archives/formulaTemplateApi';
  import FormDrawerHistory from './FormDrawerHistory.vue';
  import dayjs from 'dayjs';
  const emit = defineEmits(['success', 'register']);

  const getTitle = ref('透析处方');
  const width = '70%';
  const isUpdate = ref(false);
  const rowId = ref();
  const patientBasicId = ref();
  const bizDictOptions = reactive({
    accessType: [],
  });
  // 表格数据
  const tableData = ref([]);

  const { createMessage } = useMessage();
  const [registerDrawerHistory, { openDrawer }] = useDrawer();

  const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
    schemas: dataFormSchema,
    showActionButtonGroup: false,
    baseColProps: {
      span: 6,
    },
  });
  const [registerTable, { setTableData, getDataSource }] = useTable({
    rowKey: 'id',
    showIndexColumn: false,
    bordered: true,
    striped: false,
    pagination: false,
    maxHeight: 200,
    actionColumn: {
      width: 80,
      title: '操作',
      dataIndex: 'action',
    },
    dataSource: tableData.value,
    columns: columnsDrawer,
  });
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async data => {
    console.log('🚀 ~ file: FormDrawer.vue:49 ~ data:', data);
    await resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = data.isUpdate;
    getTitle.value = `${isUpdate.value ? '编辑透析处方模板' : '新建透析处方模板'} ( ${
      data.record.name
    } | ${data.record.gender} | ${data.record.age} )`;
    bizDictOptions.accessType = await listDictModel({ dictCode: 'va_type' });
    patientBasicId.value = data.record.patientBasicId;
    rowId.value = data.record?.id;
    console.log('unref(isUpdate)', unref(isUpdate));
    if (unref(isUpdate)) {
      const resData = await archivesFormulaTemplateDetail(rowId.value);
      if (resData.suppliesTemplate) {
        tableData.value = resData.suppliesTemplate.map(ele => {
          return {
            name: ele.name,
            typeName: ele.typeName,
            count: ele.count,
          };
        });
        await nextTick();
        await setTableData(tableData.value);
      }
      await setFieldsValue({
        ...resData,
      });
      if (resData.dialysisType) {
        updateSchema({
          // label: '透析模式',
          field: 'dialysisType',
          // required: true,
          // component: 'ApiSelect',
          componentProps: {
            disabled: true,
            // api: listDictModel,
            // params: {
            //   dictCode: 'dt',
            // },
          },
        });
      }
    } else {
      await setFieldsValue({
        enactedTime: dayjs().format('YYYY-MM-DD'),
      });
    }
  });

  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      values.patientBasicId = patientBasicId.value;
      !unref(isUpdate)
        ? await archivesFormulaTemplateAdd({ ...values })
        : await archivesFormulaTemplateEdit({ ...values, id: rowId.value });
      !unref(isUpdate) ? createMessage.success('新增成功！') : createMessage.success('编辑成功！');
      closeDrawer();
      emit('success', {
        isUpdate: unref(isUpdate),
        values: { ...values, id: rowId.value },
      });
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleAdd() {
    console.log('添加');
    tableData.value.push({
      typeId: '',
      name: '',
      nanoid: nanoid(5),
    });
    console.log(
      '🚀 ~ file: FormModal.vue:135 ~ handleAdd ~ tableDataAllergic.value:',
      tableData.value,
    );
    await nextTick();
    await setTableData(tableData.value);
  }
  function handleDel(record) {
    console.log('删除');
    const data = getDataSource();
    const index = data.findIndex(item => item.id === record.id);
    tableData.value.splice(index, 1);
    setTableData(tableData.value);
  }
  function callFormFieldChange(key) {
    console.log('🚀 ~ file: FormDrawer.vue:169 ~ callFormFieldChange ~ key:', key);
    if (key == 'vitals') {
      console.log('打开体征历史数据');
      openDrawer(true, {
        record: {
          patientBasicId: patientBasicId.value,
        },
      });
    }
  }
</script>
<style lang="less" scoped>
  ::v-deep(.ant-table-body) {
    height: 200px !important;
  }

  ::v-deep(label[for='form_item_suppliesTemplate']) {
    display: none;
  }

  ::v-deep(.ant-btn-link) {
    color: rgb(61 65 85 / 100%);
  }
</style>
