<template>
  <div ref="modal" :class="prefixCls">
    <BasicModal
      v-bind="$attrs"
      width="820px"
      :getContainer="modal"
      @register="registerModal"
      @ok="handleSubmit"
    >
      <BasicForm @register="registerForm"/>
      <BasicTable v-show="state.tableVisible" @register="gencodeCustomFieldRegisterTable">
        <template #toolbar>
          <a-button
            v-show="state.tag != 'view'"
            type="primary"
            @click="handleAdd()"
          >新增</a-button>
        </template>
        <template #bodyCell="{ index, column, record }">
          <template v-if="column.key === 'action'">
            <TableAction
              :actions="[
                {
                  label: '查看',
                  icon: 'fa-regular:eye',
                  onClick: handleViewEdit.bind(null, record)
                },
                {
                  label: '编辑',
                  icon: 'fa6-regular:pen-to-square',
                  onClick: handleEdit.bind(null, record, index)
                },
                {
                  label: '删除',
                  icon: 'ant-design:delete-outlined',
                  color: 'error',
                  onClick: handleDel.bind(null, record, index)
                }]"
            />
          </template>
        </template>
      </BasicTable>
      <GencodeCustomFieldModal @register="gencodeCustomFieldRegisterModal" @success="handleGencodeCustomField"/>
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, computed, ref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, gencodeCustomFieldColumns } from './genCustomObj.data';
  import { saveAndGencodeCustomField, getGencodeCustomObj, selectListByValue } from '/@/api/platform/system/controller/gencodeCustomObj';
  import { BasicModal, ModalProps, useModal, useModalInner } from '/@/components/Modal';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import GencodeCustomFieldModal from './GencodeCustomFieldModal.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { isNil } from 'lodash-es';
  import { isEmpty } from '/@/utils/is';
  import {useDesign} from '/@/hooks/web/useDesign';

  /** 通用变量统一声明区域 */
  interface WindowState {
    tag: string;
    dataSource: Recordable[];
    tableVisible: boolean;
  }
  const state = reactive<WindowState>({
    tag: '',
    dataSource: [],
    tableVisible: false
  });
  const modal = ref();
  const { prefixCls } = useDesign('gen-custom-obj');
  const { createConfirm, createMessage } = useMessage();
  /** https://v3.cn.vuejs.org/api/options-data.html#emits */
  const emit = defineEmits(['success', 'register']);
  const [gencodeCustomFieldRegisterModal, { openModal: gencodeCustomFieldOpenModal }] = useModal();
  const getDataSource = computed(() => state.dataSource.filter(item => item._action != 'del'));
  const [registerForm, { resetFields, setFieldsValue, validate, clearValidate, setProps, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 }
  });
  const [gencodeCustomFieldRegisterTable] = useTable({
    dataSource: getDataSource,
    rowKey: 'id',
    columns: gencodeCustomFieldColumns,
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    pagination: false,
    clickToRowSelect: false,
    showIndexColumn: false,
    maxHeight: 380,
    actionColumn: {
      width: 220,
      title: '操作',
      dataIndex: 'action',
      fixed: false,
      ifShow: () => state.tag != 'view'
    },
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data: BoxPayload = { _tag: '' }) => {
    // 处理清除脏数据
    await resetFields();
    await clearValidate();
    // 处理设置数据
    state.tag = data._tag;
    state.dataSource = [];
    state.tableVisible = false;
    const id = data.record?.id;
    const classValue = data.record?.value;
    const props: Partial<ModalProps> = { confirmLoading: false, showOkBtn: true };
    await setProps({ disabled: false });
    await updateSchema([{
      field: 'value',
      componentProps: {
        disabled: state.tag != 'add'
      },
      rules: [
        {
          required: true,
          message: '请输入完整类名'
        },
        {
          validator: async (rule, value) => {
            if (!isEmpty(value)) {
              const result = await selectListByValue(value);
              const list = result.filter(item => item.value != classValue);
              if(list?.length > 0) return Promise.reject('该完整类名已存在');
            }
            return Promise.resolve();
          },
          validateTrigger: 'blur'
        }]
    },
    {
      field: 'type',
      componentProps: {
        onChange: (e: ChangeEvent) => e.target?.value && (state.tableVisible = e.target.value == '0')
      }
    }]);
    // 采用tag标签区分操作
    switch (state.tag) {
      case 'add':
        props.title = '新建java类型';
        break;
      case 'view':
        props.title = '查看java类型';
        props.showOkBtn = false;
        await setProps({ disabled: true });
        const getGencodeCustomObjView = await getGencodeCustomObj(id);
        state.dataSource = getGencodeCustomObjView?.gencodeCustomFieldList || [];
        state.tableVisible = getGencodeCustomObjView.type == '0';
        await setFieldsValue(getGencodeCustomObjView);
        break;
      case 'edit':
        props.title = '编辑java类型';
        const getGencodeCustomObjEdit = await getGencodeCustomObj(id);
        state.dataSource = getGencodeCustomObjEdit?.gencodeCustomFieldList || [];
        state.tableVisible = getGencodeCustomObjEdit.type == '0';
        await setFieldsValue(getGencodeCustomObjEdit);
        break;
    }
    // 尾部:设置处理后的最终配置数据
    setModalProps(props);
  });

  function handleAdd() {
    gencodeCustomFieldOpenModal(true,{ _tag: 'add' });
  }

  function handleEdit(record: Recordable, index: number) {
    gencodeCustomFieldOpenModal(true, { _tag: 'edit', record, index });
  }

  function handleViewEdit(record: Recordable) {
    gencodeCustomFieldOpenModal(true, { _tag: 'view', record });
  }

  async function handleDel(record: Recordable, index: number) {
    createConfirm({
      iconType: 'warning',
      title: '警告',
      content: `是否确认删除java属性为${record.name}的数据?`,
      onOk: async () => {
        if (record.id) {
          record._action = 'del';
        } else state.dataSource.splice(index, 1);
      }
    });
  }

  function handleGencodeCustomField(record: Recordable, index?: number) {
    if (!isNil(index) && index !== -1) {
      state.dataSource.splice(index, 1, record);
    } else state.dataSource.push(record);
  }

  async function handleSubmit() {
    try {
      // 提取验证数据
      const formData = await validate();
      formData.gencodeCustomFieldList = state.dataSource;
      // 处理提交之前逻辑
      setModalProps({ confirmLoading: true });
      await saveAndGencodeCustomField(formData);
      // 处理提交完成之后逻辑
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
<style scoped lang="less">
  @prefix-cls: ~'@{namespace}-gen-custom-obj';

  .@{prefix-cls} {
    :deep(.ant-modal) {
      top: 40px;
    }
  }
</style>
