<template>
  <ResizePageWrapper>
    <template #resizeLeft>
      <BasicTree
        search
        :title="t('模板类别')"
        :clickRowToExpand="true"
        :treeData="data.treeData"
        :selectedKeys="[data.classifyId]"
        :fieldNames="{ key: 'id', title: 'name' }"
        @select="handleSelect"
      />
    </template>

    <template #resizeRight>
      <BasicTable @register="registerTable" isMenuTable>
        <template #toolbar>
          <a-button @click="handleCategory" type="primary" v-auth="'print:classifyMgt'">
            {{ t('分类管理') }}
          </a-button>
          <a-button type="primary" @click="handleCreate" v-auth="'print:add'">{{
            t('新增')
          }}</a-button>
        </template>

        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                auth: 'print:disable',
                label: record.enabledMark === 1 ? '禁用' : '启用',
                onClick: forbidden.bind(null, record),
              },
              {
                label: '编辑',
                auth: 'print:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                auth: 'print:delete',
                color: 'error',
                popConfirm: {
                  title: t('是否确认删除'),
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </BasicTable>
    </template>
    <CategoryModal
      title="表单"
      :dicId="PrintCategory.ID"
      @register="registerCategoryModal"
      @success="getCategoryTree"
    />
    <PrintDesign v-if="data.printDesignVisible" :editData="data.editData" @close="handleClose" />
  </ResizePageWrapper>
</template>
<script lang="ts" setup>
  import { onMounted, reactive, defineAsyncComponent, h } from 'vue';

  import { CategoryModal } from '/@/components/CategoryModal';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  // import { PageWrapper } from '/@/components/Page';
  import { ResizePageWrapper } from '/@/components/Page';
  import { LoadingBox } from '/@/components/ModalPanel/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getDicDetailList } from '/@/api/system/dic';
  import { useModal } from '/@/components/Modal';
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import { Tag } from 'ant-design-vue';
  import { PrintCategory } from '/@/enums/printEnum';
  import {
    deleteDesign,
    disabledDesign,
    enabledDesign,
    getDesignInfo,
    getDesignPrintPage,
  } from '/@/api/system/generator/print';
  import { PrintBasicData } from '/@/model/generator/print';
  import { usePermission } from '/@/hooks/web/usePermission';

  const { t } = useI18n();
  const PrintDesign = defineAsyncComponent({
    loader: () => import('./Design.vue'),
    loadingComponent: LoadingBox,
  });
  const configColumns: BasicColumn[] = [
    {
      title: t('编码'),
      dataIndex: 'code',
      resizable: true,
    },
    {
      title: t('名称'),
      dataIndex: 'name',
      resizable: true,
    },
    // {
    //   title: t('分类'),
    //   dataIndex: 'categoryName',
    //   width: 80,
    //   align: 'left',
    // },
    {
      title: t('流程状态'),
      dataIndex: 'enabledMark',
      width: 120,
      resizable: true,
      customRender: ({ record }) => {
        const status = record.enabledMark;
        const enable = ~~status === 1;
        const color = enable ? 'green' : 'red';
        const text = enable ? t('启用') : t('停用');
        return h(Tag, { color: color }, () => text);
      },
    },
    {
      title: t('备注'),
      dataIndex: 'remark',
      resizable: true,
    },
  ];
  const searchFormSchema: FormSchema[] = [
    {
      field: 'name',
      label: t('模板名称'),
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: t('请输入模板名称'),
      },
    },
    {
      field: 'code',
      label: t('模板编码'),
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: t('请输入模板编码'),
      },
    },
    {
      field: 'enabledMark',
      label: t('模板状态'),
      colProps: { span: 8 },
      component: 'Select',
      componentProps: {
        options: [
          { label: t('启用'), value: 1 },
          { label: t('停用'), value: 0 },
        ],
      },
    },
  ];
  const { notification } = useMessage();
  const { hasPermission } = usePermission();

  const [registerTable, { reload }] = useTable({
    title: t('打印模板列表'),
    api: getDesignPrintPage,
    rowKey: 'id',
    columns: configColumns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      showResetButton: false,
    },
    beforeFetch: (params) => {
      //发送请求默认新增  左边树结构所选机构id
      return { ...params, category: data.classifyId, isAuth: false };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    pagination: {
      pageSize: 18,
    },
    actionColumn: {
      width: 150,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    tableSetting: {
      size: false,
    },
    customRow: (record) => {
      return {
        ondblclick: () => {
          if (hasPermission('print:edit')) {
            handleEdit(record);
          }
        },
      };
    },
  });

  let data: {
    printDesignVisible: boolean;
    treeData: Array<TreeItem>;
    classifyId: string;
    previewVisible: boolean;
    xml: string;
    editData: PrintBasicData;
  } = reactive({
    printDesignVisible: false,
    treeData: [],
    classifyId: '',
    previewVisible: false,
    xml: '',
    editData: {
      code: '',
      name: '',
      icon: '',
      category: undefined,
      parentId: '',
      apiConfig: '',
      sortCode: 0,
      isMenu: 0,
      remark: '',
      content: '',
    },
  });
  const [registerCategoryModal, { openModal: openCategoryModal }] = useModal();
  onMounted(() => {
    getCategoryTree();
  });
  function handleCategory() {
    openCategoryModal(true, { title: t('模板类别分类管理') });
  }
  function handleCreate() {
    data.printDesignVisible = true;
  }
  function handleClose() {
    data.printDesignVisible = false;
    data.editData = {
      code: '',
      name: '',
      icon: '',
      category: undefined,
      parentId: '',
      apiConfig: '',
      sortCode: 0,
      isMenu: 0,
      remark: '',
      content: '',
    };
    reload();
  }
  async function handleEdit(record: Recordable) {
    try {
      let res = await getDesignInfo(record.id);
      if (res) {
        data.editData = res;
        data.printDesignVisible = true;
      }
    } catch (error) {}
  }

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

  function handleSelect(selectIds: Array<string>) {
    data.classifyId = selectIds[0];
    reload();
  }

  async function getCategoryTree() {
    data.treeData = (await getDicDetailList({
      itemId: PrintCategory.ID,
    })) as unknown as TreeItem[];
    data.treeData.unshift({
      key: '',
      id: '',
      name: '全部',
    });
  }

  async function forbidden(record) {
    try {
      if (record.enabledMark == 1) {
        let res = await disabledDesign(record.id);
        if (res) {
          notification.success({
            message: t('禁用流程'),
            description: t('禁用成功！'),
          });
          reload();
        }
      } else {
        let res = await enabledDesign(record.id);
        if (res) {
          notification.success({
            message: t('启动流程'),
            description: t('启动成功！'),
          });
          reload();
        }
      }
    } catch (error) {}
  }
</script>
