<template>
  <ResizePageWrapper>
    <template #resizeLeft>
      <BasicTree
        search
        :title="t('规则分类')"
        :clickRowToExpand="true"
        :treeData="state.treeData"
        :selectedKeys="[state.classifyId]"
        :fieldNames="{ key: 'id', title: 'name' }"
        @select="handleSelect"
      />
    </template>
    <template #resizeRight>
      <BasicTable @register="registerTable" isMenuTable>
        <template #toolbar>
          <a-button type="primary" v-auth="'ruleProcess:add'" @click="handleCreate">
            {{ t('新增') }}
          </a-button>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex == 'action'">
            <TableAction
              :actions="[
                {
                  label: '编辑',
                  auth: 'ruleProcess:edit',
                  onClick: handleEdit.bind(null, record),
                },
                {
                  label: '删除',
                  auth: 'ruleProcess:delete',
                  color: 'error',
                  ifShow: record.code !== 'chinese',
                  popConfirm: {
                    title: t('是否确认删除？'),
                    confirm: handleDelete.bind(null, record),
                  },
                },
              ]"
            />
          </template>
        </template>
      </BasicTable>
    </template>
    <RuleProcessDesign
      v-if="state.show"
      :editData="state.editData"
      @close="closeRuleProcessDesign"
      @save="saveRuleProcessDesign"
      :treeData="state.treeData"
    />
  </ResizePageWrapper>
</template>
<script lang="ts">
  import { defineComponent, reactive } from 'vue';
  import { ResizePageWrapper } from '/@/components/Page';
  import { BasicTable, useTable, TableAction, BasicColumn, FormSchema } from '/@/components/Table';
  import RuleProcessDesign from './components/design/index.vue';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { usePermission } from '/@/hooks/web/usePermission';

  import {
    getRuleProcessPage,
    deleteRuleProcess,
    addRuleProcess,
    updateRuleProcess,
  } from '/@/api/ruleProcess/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getDicDetailList } from '/@/api/system/dic';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { defaultProcessInfo, RuleProcessCategory } from './components/design/config';
  import { RuleProcessListModel } from '/@/api/ruleProcess/model';
  import { cloneDeep } from 'lodash-es';
  const { t } = useI18n();
  export const columns: BasicColumn[] = [
    {
      title: t('规则名称'),
      dataIndex: 'name',
      align: 'center',
      resizable: true,
    },
    {
      title: t('规则编码'),
      dataIndex: 'code',
      align: 'center',
      resizable: true,
    },
    {
      title: t('规则分类'),
      dataIndex: 'itemName',
      align: 'center',
      resizable: true,
    },
    {
      title: t('备注'),
      dataIndex: 'remark',
      align: 'center',
      resizable: true,
    },
    {
      title: t('创建时间'),
      dataIndex: 'createDate',
      align: 'center',
      resizable: true,
    },
  ];

  export const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: '',
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: t('请输入规则名称或应用名称'),
      },
    },
  ];

  export default defineComponent({
    name: 'RuleProcess',
    components: {
      BasicTable,
      RuleProcessDesign,
      TableAction,
      ResizePageWrapper,
      BasicTree,
    },
    setup() {
      const state = reactive({
        show: false,
        editData: cloneDeep(defaultProcessInfo) as RuleProcessListModel,
        treeData: [] as Array<TreeItem>,
        classifyId: '',
      });
      const { notification } = useMessage();
      const { hasPermission } = usePermission();
      getCategoryTree();
      const [registerTable, { reload }] = useTable({
        title: t('规则流程设计列表'),
        api: getRuleProcessPage,
        columns,
        formConfig: {
          rowProps: {
            gutter: 16,
          },
          schemas: searchFormSchema,
          showResetButton: false,
        },
        useSearchForm: true,
        showTableSetting: true,
        striped: false,
        pagination: {
          hideOnSinglePage: true,
        },
        actionColumn: {
          width: 88,
          title: t('操作'),
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
        tableSetting: {
          size: false,
        },
        customRow: (record) => {
          return {
            ondblclick: () => {
              if (hasPermission('ruleProcess:edit')) {
                handleEdit(record);
              }
            },
          };
        },
        beforeFetch: (params) => {
          //发送请求默认新增  左边树结构所选机构id
          return { ...params, itemId: state.classifyId };
        },
      });
      function handleSelect(selectIds: Array<string>) {
        state.classifyId = selectIds[0];
        reload();
      }

      async function getCategoryTree() {
        let res = (await getDicDetailList({
          itemId: RuleProcessCategory.ID,
        })) as unknown as TreeItem[];
        state.treeData = res.map((ele) => {
          ele.icon = 'ant-design:tags-outlined';
          return ele;
        });
        state.treeData.unshift({
          key: '',
          id: '',
          name: '全部',
          icon: 'ant-design:tags-outlined',
        });
      }
      function handleCreate() {
        state.editData = cloneDeep(defaultProcessInfo);
        state.show = true;
      }

      function handleEdit(record: RuleProcessListModel) {
        state.editData = record;
        state.show = true;
      }

      function handleDelete(record: Recordable) {
        deleteRuleProcess([record.id]).then((_) => {
          reload();
          notification.success({
            message: t('提示'),
            description: t('删除成功'),
          }); //提示消息
        });
      }

      function handleSuccess() {
        reload();
      }

      function closeRuleProcessDesign() {
        state.show = false;
      }
      async function saveRuleProcessDesign(saveData) {
        try {
          let res = false;
          let str = '';
          if (state.editData.id) {
            str = '编辑';
            res = await updateRuleProcess({ ...saveData, id: state.editData.id });
          } else {
            str = '新增';
            res = await addRuleProcess(saveData);
          }
          if (res) {
            closeRuleProcessDesign();
            reload();
            notification.success({
              message: t(str + '提示'),
              description: t('成功'),
            }); //提示消息
          }
        } catch (error) {}
      }
      return {
        state,
        registerTable,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        t,
        closeRuleProcessDesign,
        handleSelect,
        saveRuleProcessDesign,
      };
    },
  });
</script>
