<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> + {{ t('新增') }} </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              title: t('编辑'),
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              title: t('删除'),
              popConfirm: {
                title: t('是否确认删除'),
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <RuleModal @register="registerRuleModal" @success="handleSuccess" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicTable, useTable, FormSchema, BasicColumn, TableAction } from '/@/components/Table';
  import { addCodeRule, getCodeRuleInfo, editCodeRule } from '/@/api/system/code';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import RuleModal from './RuleModal.vue';
  const { t } = useI18n();
  const codeFormSchema: FormSchema[] = [
    {
      field: 'code',
      label: t('编码编号'),
      component: 'Input',
      required: true,
      colProps: { span: 12 },
    },
    {
      field: 'name',
      label: t('编码名称'),
      component: 'Input',
      required: true,
      colProps: { span: 12 },
    },
    {
      field: 'description',
      label: t('编码说明'),
      component: 'Input',
      colProps: { span: 12 },
    },
    {
      field: 'sortCode',
      label: t('排序码'),
      component: 'InputNumber',
      componentProps: {
        min: 1,
        precision: 0,
        style: { width: '100%' },
      },
      colProps: { span: 12 },
    },
  ];

  const columns: BasicColumn[] = [
    {
      title: t('前缀'),
      dataIndex: 'itemTypeName',
      width: 120,
    },
    {
      title: t('格式'),
      dataIndex: 'formatStr',
      width: 120,
    },
    {
      title: t('步长'),
      dataIndex: 'stepValue',
      width: 120,
    },
    {
      title: t('初始值'),
      dataIndex: 'initValue',
      width: 120,
    },
    {
      title: t('说明'),
      dataIndex: 'description',
      width: 120,
    },
  ];

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

  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: codeFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });

    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      const record = await getCodeRuleInfo(data.record.id);
      setFieldsValue({
        ...record,
      });
      setTableData(JSON.parse({ ...record }.formatJson));
    } else {
      setTableData([]);
    }
  });
  const [registerRuleModal, { openModal }] = useModal();

  const [registerTable, { getDataSource, setTableData, updateTableDataRecord }] = useTable({
    title: t('规则设计'),
    columns,
    bordered: true,
    pagination: false,
    canResize: false,
    actionColumn: {
      width: 80,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  const getTitle = computed(() => (!unref(isUpdate) ? t('新增单据编码') : t('编辑单据编码')));

  async function handleSubmit() {
    try {
      const values = await validate();
      values.formatJson = JSON.stringify(getDataSource());
      setModalProps({ confirmLoading: true });
      if (values.formatJson === '[]') {
        notification.warning({
          message: t('提示'),
          description: t('编码规则不能为空'),
        });
        return;
      }
      // TODO custom api
      if (!unref(isUpdate)) {
        //false 新增
        await addCodeRule(values);
        notification.success({
          message: t('提示'),
          description: t('新增成功'),
        }); //提示消息
      } else {
        values.id = rowId.value;
        await editCodeRule(values);
        notification.success({
          message: t('提示'),
          description: t('修改成功！'),
        }); //提示消息
      }

      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  function handleDelete(record: Recordable) {
    const dataSource = getDataSource();
    setTableData(dataSource.filter((x) => x.key !== record.key));
  }

  function handleCreate() {
    openModal(true, {
      isUpdate: false,
    });
  }
  function handleSuccess({ isUpdate, record }) {
    if (isUpdate) {
      updateTableDataRecord(record.key, record);
    } else {
      const dataSource = getDataSource();
      dataSource.push(record);
      setTableData(dataSource);
    }
  }
</script>
