<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>
          <ImportFlow
            ><a-button v-auth="'design:importFlow'" type="primary">{{
              t('导入流程')
            }}</a-button></ImportFlow
          >
          <a-button v-auth="'design:classifyMgt'" type="primary" @click="handleCategory">{{
            t('分类管理')
          }}</a-button>
          <a-button type="primary" v-auth="'design:add'" @click="handleCreate">{{
            t('新增')
          }}</a-button>
        </template>

        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                auth: 'design:disable',
                label: record.enabledMark === 1 ? '禁用' : '启用',
                onClick: forbidden.bind(null, record),
                ifShow: record.enabledMark !== 2,
              },
              {
                auth: 'design:preview',
                label: '预览',
                onClick: preview.bind(null, record),
                ifShow: record.enabledMark !== 2,
              },
              {
                auth: 'design:history',
                label: '历史',
                onClick: queryHistory.bind(null, record),
                ifShow: record.enabledMark !== 2,
              },
              {
                auth: 'design:exportFlow',
                label: '导出',
                onClick: handleDownByData.bind(null, record),
              },
              {
                label: '编辑',
                auth: 'design:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                auth: 'design:delete',
                color: 'error',
                popConfirm: {
                  title: t('是否确认删除'),
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </BasicTable>
    </template>

    <CategoryModal
      title="流程"
      :dicId="FlowCategory.ID"
      @register="registerCategoryModal"
      @success="getCategoryTree"
    />
    <Preview v-if="data.previewVisible" :xml="data.xml" @close="data.previewVisible = false" />
    <WorkflowDesignModal
      v-if="data.visibleBpmnDesign"
      :editData="data.editData"
      @close="handleClose"
    />
    <History :schemaId="schemaId" v-if="data.visibleHistory" @close="historyClose" />
  </ResizePageWrapper>
</template>
<script lang="ts" setup>
  import { onMounted, reactive, defineAsyncComponent, h, ref } 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 {
    deleteDesign,
    getDesignPage,
    exportDesign,
    enabledDesign,
    disabledDesign,
    getPreviewProcess,
  } from '/@/api/workflow/design';
  import { getBpmnJsonAndXmlById } from './bpmn/config/info';
  import { FlowCategory } from '/@/enums/workflowEnum';

  import { useModal } from '/@/components/Modal';
  import { downloadByData } from '/@/utils/file/download';
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import History from './History.vue';
  import ImportFlow from './ImportFlow.vue';
  import { usePermission } from '/@/hooks/web/usePermission';

  import { Tag } from 'ant-design-vue';
  const { t } = useI18n();

  const Preview = defineAsyncComponent(() => import('./Preview.vue'));
  const WorkflowDesignModal = defineAsyncComponent({
    loader: () => import('./bpmn/index.vue'),
    loadingComponent: LoadingBox,
  });
  const configColumns: BasicColumn[] = [
    {
      title: t('编码'),
      dataIndex: 'code',
      resizable: true,
    },
    {
      title: t('名称'),
      dataIndex: 'name',
      resizable: true,
    },
    {
      title: t('分类'),
      dataIndex: 'categoryName',
      width: 80,
      resizable: true,
    },
    {
      title: t('流程状态'),
      dataIndex: 'enabledMark',
      width: 120,
      resizable: true,
      customRender: ({ record }) => {
        const status = record.enabledMark;
        let color = 'red';
        let text = t('停用');
        switch (status) {
          case 1:
            color = 'success';
            text = t('启用');
            break;
          case 2:
            color = 'yellow';
            text = t('草稿');
            break;
        }
        return h(Tag, { color: color }, () => text);
      },
    },
    {
      title: t('备注'),
      dataIndex: 'remark',
      width: 120,
      resizable: true,
    },
  ];
  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: t('关键字'),
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: t('请输入关键字'),
      },
    },
  ];
  const { notification } = useMessage();
  const { hasPermission } = usePermission();

  const [registerTable, { reload }] = useTable({
    title: t('流程模板列表'),
    api: getDesignPage,
    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: 280,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    tableSetting: {
      size: false,
    },
    customRow: (record) => {
      return {
        ondblclick: () => {
          if (hasPermission('design:edit')) {
            handleEdit(record);
          }
        },
      };
    },
  });

  let data: {
    visibleBpmnDesign: boolean;
    visibleHistory: boolean;
    treeData: Array<TreeItem>;
    classifyId: string;
    previewVisible: boolean;
    xml: string;
    editData: {
      id: string;
      json: { processConfig: any; childNodeConfig: Array<any> };
      xml: string;
      isCanDraft?: boolean;
    };
  } = reactive({
    visibleBpmnDesign: false,
    visibleHistory: false,
    treeData: [],
    classifyId: '',
    previewVisible: false,
    xml: '',
    editData: { id: '', json: { processConfig: null, childNodeConfig: [] }, xml: '' },
  });
  const [registerCategoryModal, { openModal: openCategoryModal }] = useModal();

  const schemaId = ref('');

  onMounted(() => {
    getCategoryTree();
  });
  function handleCategory() {
    openCategoryModal(true, { title: t('流程分类管理') });
  }

  function handleCreate() {
    data.visibleBpmnDesign = true;
    data.editData.isCanDraft = true;
  }
  function handleClose() {
    data.visibleBpmnDesign = false;
    data.editData.id = '';
    data.editData.xml = '';
    data.editData.json = { processConfig: null, childNodeConfig: [] };
    reload();
  }
  async function handleEdit(record: Recordable) {
    console.log('record', record);
    let res = await getBpmnJsonAndXmlById(record.id);
    data.editData.id = record.id;
    data.editData.xml = res.xml;
    data.editData.json = res.json;
    data.editData.isCanDraft = record.enabledMark === 2;
    data.visibleBpmnDesign = true;
  }

  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() {
    let res = (await getDicDetailList({
      itemId: FlowCategory.ID,
    })) as unknown as TreeItem[];
    data.treeData = res.map((ele) => {
      ele.icon = 'ant-design:tags-outlined';
      return ele;
    });
    data.treeData.unshift({
      key: '',
      id: '',
      name: '全部',
      icon: 'ant-design:tags-outlined',
    });
  }

  function queryHistory(record) {
    schemaId.value = record.id;
    data.visibleHistory = true;
  }

  function historyClose() {
    data.visibleHistory = false;
    reload();
  }

  async function handleDownByData(record) {
    try {
      let res: any = await exportDesign(record.id);
      downloadByData(res, record.name + '.json');
    } catch (error) {}
  }

  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) {}
  }

  async function preview(record) {
    try {
      let res = await getPreviewProcess(record.id);
      if (res) {
        data.xml = res;
        data.previewVisible = true;
      }
    } catch (error) {}
  }
</script>
