<template>
  <ResizePageWrapper :hasLeft="true" :formLeftWidth="300">
    <template #resizeLeft>
      <BasicTree
        title="页面分类"
        toolbar
        search
        switcher
        :clickRowToExpand="true"
        :treeData="treeData"
        :fieldNames="{ key: 'value', title: 'name' }"
        @select="handleSelect"
      >
        <template #title="item"> &nbsp;&nbsp;{{ item.name }} </template>
      </BasicTree>
    </template>

    <template #resizeRight>
      <BasicTable @register="registerTable" isMenuTable ref="tableRef">
        <template #toolbar>
          <template v-for="button in tableButtonConfig" :key="button.code">
            <a-button v-if="button.isDefault" type="primary" @click="buttonClick(button.code)">
              <template #icon><Icon :icon="button.icon" /></template>
              {{ button.name }}
            </a-button>
            <a-button
              v-else
              :type="button.buttonType === 'danger' ? 'default' : button.buttonType || 'primary'"
              :danger="button.buttonType === 'danger'"
              @click="buttonClick(button.code)"
            >
              <template #icon><Icon :icon="button.icon" /></template>
              {{ button.name }}
            </a-button>
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.componentType === 'switch'">
            <a-switch
              v-model:checked="record[column.dataIndex]"
              :unCheckedValue="0"
              :checkedValue="1"
              :disabled="true"
            />
          </template>

          <template v-if="column.dataIndex === 'action'">
            <TableAction
              :actions="getLessActions(record)"
              :dropDownActions="getMoreActions(record)"
            />
          </template>

          <template v-else-if="column.dataIndex && column?.listStyle">
            <span :style="executeListStyle(getValue(record, column, 'style'), column?.listStyle)">{{
              getValue(record, column, 'value')
            }}</span>
          </template>
        </template>
      </BasicTable>
    </template>

    <PageDesignModal
      @register="registerModal"
      @success="handleFormSuccess"
      @close="handleFormCancel"
    />
    <CategoryModal
      title="页面设计"
      :dicId="dicId"
      @register="registerCategoryModal"
      @success="fetch"
    />
    <HistoryModal
      @register="registerHistoryModal"
      @edit-history="
        (data) => {
          handleEdit(data, true);
        }
      "
      :key="refreshKey"
    />
    <PublishModal @register="registerPublishModal" @success="reload" />
  </ResizePageWrapper>
</template>
<script lang="ts" setup>
  import { ref, computed, onMounted, createVNode } from 'vue';

  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  import { getPageDesignPage, deletePageDesign } from '/@/api/system/pagedesign';
  import { ResizePageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { executeListStyle, getValue } from '/@/hooks/web/useListStyle'; //列表样式配置
  import { useRouter } from 'vue-router';
  import { CategoryModal } from '/@/components/CategoryModal';
  import { useModal } from '/@/components/Modal';
  import HistoryModal from './components/HistoryModal.vue';
  import PublishModal from './components/PublishModal.vue';
  import PageDesignModal from './components/PageDesignModal.vue';

  import { searchFormSchema, columns } from './components/config';

  import Icon from '/@/components/Icon/index';

  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { getDicDetailList } from '/@/api/system/dic';
  const dicId = '1911711937169440769';
  const listSpliceNum = ref(5); //操作列最先展示几个

  import { useConcurrentLock } from '/@/hooks/web/useConcurrentLock';
  const [registerHistoryModal, { openModal: openHistoryModal }] = useModal();
  const pageParamsInfo = ref<any>({});
  const { handleOpenFormEnableLockeData, handleCloseFormEnableLocke, handleHasEnableLocke } =
    useConcurrentLock();
  const refreshKey = ref(0);
  const { notification } = useMessage();
  const { t } = useI18n();
  defineEmits(['register']);
  const { filterColumnAuth, filterButtonAuth, hasPermission } = usePermission();

  const filterColumns = filterColumnAuth(columns);
  const tableRef = ref();

  //展示在列表内的按钮
  const actionButtons = ref<string[]>(['history', 'publish', 'copy', 'edit', 'delete']);
  const buttonConfigs = computed(() => {
    const list = [
      {
        name: '历史记录',
        code: 'history',
        icon: 'ant-design:copy-outlined',
        isDefault: true,
        isUse: true,
      },
      {
        name: '发布',
        code: 'publish',
        icon: 'ant-design:copy-outlined',
        isDefault: true,
        isUse: true,
      },
      {
        name: '复制',
        code: 'copy',
        icon: 'ant-design:copy-outlined',
        isDefault: true,
        isUse: true,
      },
      {
        buttonId: '1911692536307171329',
        name: '新增',
        code: 'add',
        icon: 'ant-design:plus-outlined',
        isDefault: true,
        isUse: true,
      },
      {
        buttonId: '1911692536307171330',
        name: '编辑',
        code: 'edit',
        icon: 'ant-design:form-outlined',
        isDefault: true,
        isUse: true,
        isEnableLock: true,
      },
      {
        isUse: true,
        name: '分类管理',
        code: 'category',
        icon: '',
        isDefault: false,
        setting: [{ operateType: 2, operateConfig: { apiConfig: { path: '' } } }],
        showType: 'top',
        buttonType: 'primary',
      },
      {
        buttonId: '1911692536307171331',
        name: '删除',
        code: 'delete',
        icon: 'ant-design:delete-outlined',
        isDefault: true,
        isUse: true,
      },
    ];
    return filterButtonAuth(list);
  });

  const tableButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => !actionButtons.value.includes(x.code));
  });

  const actionButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => actionButtons.value.includes(x.code));
  });

  const btnEvent = {
    view: handleView,
    add: handleAdd,
    edit: (data) => {
      handleEdit(data);
    },
    category: handleCategory,
    delete: handleDelete,
    copy: handleCopyData,
    history: handleHistory,
    publish: handlePublish,
  };

  const { currentRoute } = useRouter();

  const formIdComputedRef = computed(() => currentRoute.value.meta.formId as string);

  const selectId = ref('');
  const treeData = ref<TreeItem[]>([]);

  const [registerModal, { openModal }] = useModal();
  const [registerCategoryModal, { openModal: openCategoryModal }] = useModal();
  const [registerPublishModal, { openModal: openPublishModal }] = useModal();
  const [registerTable, { reload }] = useTable({
    title: 'PageDesign列表',
    api: getPageDesignPage,
    rowKey: 'id',
    columns: filterColumns,
    formConfig: {
      labelWidth: 100,
      schemas: searchFormSchema,
      fieldMapToTime: [],
      showResetButton: false,
    },
    beforeFetch: (params) => {
      pageParamsInfo.value = { ...params, FormId: formIdComputedRef.value, PK: 'id' };
      return pageParamsInfo.value;
    },
    afterFetch: () => {},
    useSearchForm: true,
    showTableSetting: true,

    striped: false,
    actionColumn: {
      width: 295,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    tableSetting: {
      size: false,
    },
    customRow,
    isAdvancedQuery: false,
    querySelectOption: JSON.stringify(searchFormSchema),
    objectId: formIdComputedRef.value, ////系统表单formId,自定义表单releaseId的id值
  });

  onMounted(() => {
    fetch();
  });
  async function handleHistory(record) {
    openHistoryModal(true, { title: t('历史记录'), formId: record.id });
  }
  function handlePublish(record) {
    openPublishModal(true, { title: t('发布页面——' + record.name), id: record.id });
  }
  function buttonClick(code) {
    btnEvent[code]();
  }

  function handleAdd() {
    openModal(true, { isUpdate: false, undoAble: true });
  }

  async function handleEdit(record: Recordable, isHistory = false) {
    let field = 'id';
    try {
      let hasIn = handleHasEnableLocke(buttonConfigs.value, 'edit');
      if (hasIn) {
        let res = await handleOpenFormEnableLockeData(record[field], formIdComputedRef.value);
        if (res !== null) {
          return;
        }
      }

      let info = {
        id: record[field],
        isUpdate: true,
        isHistory: isHistory,
        menuId: record.menuId,
      };

      openModal(true, info);
    } catch (error) {}
  }
  function handleCopyData(record: Recordable) {
    openModal(true, {
      id: record.id,
      isCopy: true,
    });
  }
  function handleDelete(record: Recordable) {
    deleteList([record.id]);
  }

  function deleteList(ids) {
    Modal.confirm({
      title: '提示信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否确认删除？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        deletePageDesign(ids).then((_) => {
          handleSuccess();
          notification.success({
            message: 'Tip',
            description: t('删除成功！'),
          });
        });
      },
      onCancel() {},
    });
  }

  function handleCategory() {
    openCategoryModal(true, { title: t('页面设计分类管理') });
  }

  function customRow(record: Recordable) {
    return {
      ondblclick: () => {
        if (record.isCanEdit && hasPermission('pagedesign:edit')) {
          handleEdit(record, false);
        }
      },
    };
  }

  function handleSuccess() {
    reload();
  }

  function handleFormSuccess() {
    handleSuccess();
    handleCloseFormEnableLocke(buttonConfigs.value, 'edit');
    refreshKey.value++;
  }
  function handleFormCancel() {
    handleCloseFormEnableLocke(buttonConfigs.value, 'edit');
  }

  function handleView(record: Recordable) {
    let info = {
      isView: true,
      id: record.id,
    };

    openModal(true, info);
  }

  function handleSelect(selectIds) {
    selectId.value = selectIds[0];
    reload({ searchInfo: { category: selectIds[0] } });
  }
  async function fetch() {
    treeData.value = (await getDicDetailList({
      itemId: '1911711937169440769',
    })) as unknown as TreeItem[];
  }

  function getLessActions(record: Recordable) {
    let list = getActions(record);
    return list.slice(0, listSpliceNum.value);
  }
  function getMoreActions(record: Recordable) {
    let list = getActions(record);
    return list.slice(listSpliceNum.value);
  }
  function getActions(record: Recordable): ActionItem[] {
    record.isCanEdit = false;

    let actionsList: ActionItem[] = [];
    actionButtonConfig.value?.map((button) => {
      if (!record?.workflowData?.processId) {
        record.isCanEdit = true;
        if (record.isDraft === 1) {
          actionsList.push({
            auth: `pagedesign:${button.code}`,
            label: button?.code == 'publish' && record.menuId ? '已发布' : button?.name,
            color: button.code === 'delete' ? 'error' : undefined,
            onClick:
              button?.code == 'publish' && record.menuId
                ? null
                : btnEvent[button.code]?.bind(null, record),
          });
        } else {
          if (['edit', 'delete'].includes(button.code)) {
            actionsList.push({
              auth: `pagedesign:${button.code}`,
              label: button?.code == 'publish' && record.menuId ? '已发布' : button?.name,
              color: button.code === 'delete' ? 'error' : undefined,
              onClick:
                button?.code == 'publish' && record.menuId
                  ? null
                  : btnEvent[button.code]?.bind(null, record),
            });
          }
        }
      } else {
        if (!['edit', 'delete'].includes(button.code)) {
          actionsList.push({
            auth: `pagedesign:${button.code}`,
            label: button?.code == 'publish' && record.menuId ? '已发布' : button?.name,
            onClick:
              button?.code == 'publish' && record.menuId
                ? null
                : btnEvent[button.code]?.bind(null, record),
          });
        }
      }
    });
    return actionsList;
  }
</script>
<style lang="less" scoped>
  :deep(.ant-table-selection-col) {
    width: 50px;
  }

  .show {
    display: flex;
  }

  .hide {
    display: none !important;
  }
</style>
