<template>
  <ResizePageWrapper dense contentFullHeight fixed-height contentClass="flex">
    <template #resizeLeft>
      <BasicTree
        :title="t('问卷分类')"
        :clickRowToExpand="true"
        :treeData="treeData"
        :selectedKeys="[selectId]"
        :fieldNames="{ key: 'id', title: 'name' }"
        @select="handleSelect"
      />
    </template>
    <template #resizeRight>
      <BasicTable @register="registerTable">
        <template #toolbar>
          <div class="toolbar-defined">
            <a-button
              type="primary"
              danger
              @click="handleDelete"
              v-auth="'questionnaire:batchDelete'"
              >{{ t('批量删除') }}</a-button
            >
            <a-button type="primary" @click="handleCategory" v-auth="'questionnaire:classifyMGT'">{{
              t('分类管理')
            }}</a-button>
            <a-button type="primary" @click="handleCreate" v-auth="'questionnaire:add'">
              <template #icon><PlusOutlined /></template>
              {{ t('新增') }}
            </a-button>
          </div>
        </template>
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                auth: 'questionnaire:previewForm',
                label: '预览表单',
                onClick: previewForm.bind(null, record),
              },
              {
                label: '编辑',
                auth: 'questionnaire:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                auth: 'questionnaire:delete',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </BasicTable>
    </template>
    <DesignModal
      @register="registerDesignModal"
      @success="reload"
      @close="handleClose"
      v-if="isShowModal"
    />
    <CategoryModal title="表单" :dicId="dicId" @register="registerCategoryModal" @success="fetch" />
    <PreviewModal @register="registerPreviewModal" :isDesignPreview="false" />
  </ResizePageWrapper>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import {
    getQuestionnaireList,
    deleteQuestionnaire,
    getQuestionnaireInfo,
  } from '/@/api/questionnaire/design';
  import { ResizePageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import DesignModal from './components/DesignModal.vue';
  import { CategoryModal } from '/@/components/CategoryModal';
  import PreviewModal from './components/PreviewModal.vue';
  import { onMounted, ref, createVNode } from 'vue';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { getDicDetailList } from '/@/api/system/dic';
  import { FormTypeEnum } from '/@/enums/formtypeEnum';
  import { Modal } from 'ant-design-vue';
  import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';

  const { t } = useI18n();
  const treeData = ref<TreeItem[]>([]);
  const selectId = ref('');
  const selectedKeys = ref<string[]>([]);
  const dicId = '1825816954386677762';
  const isShowModal = ref(true);

  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: '',
      component: 'Input',
      componentProps: {
        placeholder: t('请输入关键字'),
      },
    },
  ];

  const columns: BasicColumn[] = [
    {
      dataIndex: 'name',
      title: t('名称'),
    },
    {
      dataIndex: 'categoryName',
      title: t('分类'),
    },
    {
      dataIndex: 'createUserName',
      title: t('创建人'),
    },
    {
      dataIndex: 'createDate',
      title: t('创建时间'),
    },
    {
      dataIndex: 'remark',
      title: t('备注'),
    },
  ];
  const { notification } = useMessage();
  const { hasPermission } = usePermission();

  const [registerDesignModal, { openModal: openDesignModal }] = useModal();
  const [registerCategoryModal, { openModal: openCategoryModal }] = useModal();
  const [registerPreviewModal, { openModal: openPreviewModal }] = useModal();

  const formConfig = {
    rowProps: {
      gutter: 16,
    },
    schemas: searchFormSchema,
    fieldMapToTime: [],
    showResetButton: false,
  };
  const [registerTable, { reload, setSelectedRowKeys }] = useTable({
    api: getQuestionnaireList,
    rowKey: 'id',
    title: '表单列表',
    columns,
    formConfig,
    beforeFetch: (params) => {
      //发送请求默认新增  左边树结构所选id
      return { ...params, category: selectId.value, type: FormTypeEnum.CUSTOM_FORM };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    actionColumn: {
      width: 160,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    rowSelection: {
      onChange: onSelectChange,
    },
    customRow,
    tableSetting: {
      size: false,
    },
  });

  function onSelectChange(rowKeys: string[]) {
    selectedKeys.value = rowKeys;
    setSelectedRowKeys(selectedKeys.value);
  }

  function customRow(record: Recordable) {
    return {
      onClick: () => {
        let selectedRowKeys = [...selectedKeys.value];
        if (selectedRowKeys.indexOf(record.id) >= 0) {
          let index = selectedRowKeys.indexOf(record.id);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.id);
        }
        selectedKeys.value = selectedRowKeys;
        setSelectedRowKeys(selectedRowKeys);
      },
      ondblclick: () => {
        if (hasPermission('form-design:edit')) {
          handleEdit(record);
        }
      },
    };
  }

  function handleCreate() {
    openDesignModal(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openDesignModal(true, {
      id: record.id,
      isUpdate: true,
    });
  }

  function handleClose() {
    isShowModal.value = !isShowModal.value;
    setTimeout(() => {
      isShowModal.value = !isShowModal.value;
    }, 100);
  }

  function handleDelete(record: Recordable = {}) {
    const ids = record.id ? [record.id] : selectedKeys.value;
    if (!ids.length) {
      noticeInfo('删除');
      return;
    }
    Modal.confirm({
      title: t('提示'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('确定要删除所选项吗？'),
      onOk() {
        deleteQuestionnaire(ids).then(() => {
          reload();
          notification.success({
            message: t('提示'),
            description: t('删除成功'),
          });
        });
      },
      onCancel() {},
      okText: t('确认'),
      cancelText: t('取消'),
    });
  }

  function handleSelect(selectIds) {
    selectId.value = selectIds[0];
    reload({ searchInfo: { category: selectIds[0] } });
  }

  function handleCategory() {
    openCategoryModal(true, { title: t('表单分类管理') });
  }

  async function fetch() {
    treeData.value = (await getDicDetailList({
      itemId: dicId,
    })) as unknown as TreeItem[];
    treeData.value.unshift({
      key: '',
      id: '',
      name: '全部',
    });
  }

  async function previewForm(record) {
    const data = await getQuestionnaireInfo(record.id);
    const templateJson = JSON.parse(data.content);
    openPreviewModal(true, { formJson: templateJson.formJson });
  }

  function noticeInfo(info: string) {
    notification.warning({
      message: t('提示'),
      description: t(`请先选择要{notice}的数据项`, { notice: info }),
    }); //提示消息
  }

  onMounted(() => {
    fetch();
  });
</script>
