<template>
  <BasicDrawer
    v-bind="$attrs"
    destroyOnClose
    @register="registerDrawer"
    :title="getTitle"
    :width="width"
    @ok="handleSubmit"
    :showFooter="true"
    :show-ok-btn="false"
    cancel-text="关闭"
  >
    <div class="!px-4 !pt-4">
      <div class="mb-4" v-auth="'archives:accessComplication:add'">
        <a-button type="primary" shape="round" @click="handleAdd">
          <template #icon>
            <PlusOutlined />
          </template>
          添加
        </a-button>
      </div>
      <div>
        <BasicTable @register="registerTable" @edit-change="onEditChange">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <TableAction :actions="createActions(record, column)" />
            </template>
          </template>
        </BasicTable>
      </div>
    </div>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, reactive, unref, nextTick } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    BasicTable,
    useTable,
    TableAction,
    EditRecordRow,
    ActionItem,
    BasicColumn,
  } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { columnsComplication } from './data';
  import {
    archivesAccessComplicationAdd,
    archivesAccessComplicationEdit,
    archivesAccessComplicationQueryList,
    archivesAccessComplicationRemove,
  } from '/@/api/biz/archives/accessComplicationApi';
  import { listDictModel } from '/@/api/common';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { formatDictLabel, formatDictValue } from '/@/utils';
  import dayjs from 'dayjs';

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

  const getTitle = ref(``);
  const width = '60%';
  const isUpdate = ref(false);
  const vascularAccessId = ref();
  const bizDictOptions = reactive({
    accessType: [],
    vaComp: [],
  });
  // 表格数据
  const tableData = ref();

  const { createMessage } = useMessage();

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async data => {
    setDrawerProps({ confirmLoading: false });
    getTitle.value = `通路并发症 ( ${data.record.name} | ${data.record.gender} | ${data.record.age} )`;
    isUpdate.value = !!data?.isUpdate;
    bizDictOptions.accessType = await listDictModel({ dictCode: 'va_type' });
    bizDictOptions.vaComp = await listDictModel({ dictCode: 'va_comp' });
    vascularAccessId.value = data.accessId;
    await getData();
  });

  const [registerTable, { setTableData, getDataSource }] = useTable({
    dataSource: tableData.value,
    columns: columnsComplication,
    autoCreateKey: true,
    showIndexColumn: false,
    bordered: true,
    striped: false,
    actionColumn: {
      width: 100,
      title: '操作',
      dataIndex: 'action',
    },
  });

  function createActions(record: EditRecordRow, column: BasicColumn): ActionItem[] {
    if (!record.editable) {
      return [
        {
          auth: 'archives:accessComplication:add',
          icon: 'icon-xt-details_edit_default|iconfont',
          tooltip: '编辑',
          onClick: handleEdit.bind(null, record),
        },
        {
          auth: 'archives:accessComplication:remove',
          icon: 'icon-xt-details_delete_default|iconfont',
          tooltip: '删除',
          popConfirm: {
            title: '是否取消删除',
            placement: 'left',
            confirm: handleDel.bind(null, record, column),
          },
        },
      ];
    }
    return [
      {
        label: '保存',
        onClick: handleSave.bind(null, record, column),
      },
      {
        label: '取消',
        popConfirm: {
          title: '是否取消编辑',
          placement: 'left',
          confirm: handleCancel.bind(null, record, column),
        },
      },
    ];
  }
  // 获取数据
  async function getData() {
    tableData.value = await archivesAccessComplicationQueryList(vascularAccessId.value);
    tableData.value = tableData.value.map(ele => {
      ele.name = formatDictValue(bizDictOptions.vaComp, ele.name);
      return ele;
    });
    setTableData(tableData.value);
    await nextTick();
  }

  // 提交按钮事件
  async function handleSubmit() {
    try {
      setDrawerProps({ confirmLoading: true });
      emit('success', {
        isUpdate: unref(isUpdate),
      });
      closeDrawer();
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleAdd() {
    const isAdd = getDataSource().filter(ele => {
      return ele.editable;
    });
    if (isAdd.length) {
      createMessage.error('请编辑完成后添加!');
      return;
    }
    tableData.value.unshift({
      occurredTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      name: '',
      remark: '',
    });
    await nextTick();
    setTableData(tableData.value);
    console.log('getDataSource()', getDataSource());
    const record = getDataSource()[0];
    record.editable = true;
    handleEdit(record);
  }

  async function handleEdit(record) {
    record.onEdit?.(true);
  }
  async function handleDel(record) {
    const data = getDataSource();
    const index = data.findIndex(item => item.key === record.key);
    const res = await archivesAccessComplicationRemove([record?.id]);
    if (res) {
      tableData.value.splice(index, 1);
      setTableData(tableData.value);
    } else {
      createMessage.error('删除失败');
    }
  }
  async function handleSave(record: EditRecordRow) {
    console.log('🚀 ~ file: ViewDrawerComplication.vue:166 ~ handleSave ~ record:', record);
    record.onEdit?.(false, true);
    const data = {
      id: record?.id || '',
      name: record?.name || '',
      occurredTime: record?.occurredTime || '',
      remark: record?.remark || '',
      vascularAccessId: vascularAccessId.value,
    };
    if (record?.id) {
      data.name = formatDictLabel(bizDictOptions.vaComp, record?.name) || record?.name;
    }
    data.id
      ? await archivesAccessComplicationEdit(data)
      : await archivesAccessComplicationAdd(data);
    createMessage.success(data.id ? '编辑成功' : '新增成功！');
    await getData();
  }
  async function handleCancel(record: EditRecordRow) {
    console.log('🚀 ~ file: ViewDrawerComplication.vue:179 ~ handleCancel ~ record:', record);
    if (!record.id) {
      tableData.value.shift();
    }
    await nextTick();
    setTableData(tableData.value);
    record.onEdit?.(false);
  }
  function onEditChange({ column, value, record }) {
    // 本例
    // if (column.dataIndex === 'id') {
    //   record.editValueRefs.name4.value = `${value}`;
    // }
    console.log(column, value, record);
  }
</script>
<style lang="less" scoped>
  ::v-deep(.ant-btn-link) {
    color: rgb(61 65 85 / 100%);
  }
</style>
