<template>
  <PageWrapper dense fixedHeight contentFullHeight contentClass="flex">
    <BasicTable @register="registerTable" ref="tableRef">
      <template #toolbar>
        <template v-for="button in tableButtonConfig" :key="button.code">
          <a-button
            v-if="button.isDefault"
            type="primary"
            class="ml-4"
            @click="buttonClick(button.code)"
          >
            <template #icon><Icon :icon="button.icon" /></template>
            {{ button.name }}
          </a-button>
          <a-button v-else type="primary">
            <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="getActions(record)" />
        </template>

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

    <PublishModal @register="registerModal" @success="handleSuccess" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, computed, 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 { getXjrPublishPage, deleteXjrPublish } from '/@/api/version/publish';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { executeListStyle } from '/@/hooks/web/useListStyle'; //列表样式配置
  import { useRouter } from 'vue-router';

  import { useModal } from '/@/components/Modal';

  import PublishModal from './components/PublishModal.vue';

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

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

  const { notification } = useMessage();
  const { t } = useI18n();
  defineEmits(['register']);
  const { filterColumnAuth, filterButtonAuth, hasPermission } = usePermission();

  const filterColumns = filterColumnAuth(columns);
  const tableRef = ref();
  const pageParamsInfo = ref<any>({});

  //展示在列表内的按钮
  const actionButtons = ref<string[]>([
    'view',
    'edit',
    'copyData',
    'delete',
    'startwork',
    'flowRecord',
  ]);
  const buttonConfigs = computed(() => {
    const list = [
      {
        name: '刷新',
        code: 'refresh',
        icon: 'ant-design:reload-outlined',
        isDefault: true,
        isUse: true,
      },
      { name: '查看', code: 'view', icon: 'ant-design:eye-outlined', isDefault: true, isUse: true },
      { name: '新增', code: 'add', icon: 'ant-design:plus-outlined', isDefault: true, isUse: true },
      {
        name: '编辑',
        code: 'edit',
        icon: 'ant-design:form-outlined',
        isDefault: true,
        isUse: true,
      },
      {
        name: '复制数据',
        code: 'copyData',
        icon: 'ant-design:copy-outlined',
        isDefault: true,
        isUse: true,
      },
      {
        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 = {
    refresh: handleRefresh,
    view: handleView,
    add: handleAdd,
    edit: handleEdit,
    copyData: handleCopyData,
    delete: handleDelete,
  };

  const { currentRoute } = useRouter();

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

  const [registerModal, { openModal }] = useModal();

  const [registerTable, { reload }] = useTable({
    title: '版本列表',
    api: getXjrPublishPage,
    rowKey: 'id',
    columns: filterColumns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [
        ['publishDate', ['publishDateStart', 'publishDateEnd'], 'YYYY-MM-DD HH:mm:ss ', true],
      ],
      showResetButton: false,
    },
    beforeFetch: (params) => {
      pageParamsInfo.value = { ...params, FormId: formIdComputedRef.value, PK: 'id' };
      return pageParamsInfo.value;
    },
    afterFetch: (_) => {},
    useSearchForm: true,
    showTableSetting: true,

    striped: false,
    actionColumn: {
      width: 210,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    tableSetting: {
      size: false,
    },
    customRow,
  });

  function buttonClick(code) {
    btnEvent[code]();
  }

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

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

  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() {
        deleteXjrPublish(ids).then((_) => {
          handleSuccess();
          notification.success({
            message: 'Tip',
            description: t('删除成功！'),
          });
        });
      },
      onCancel() {},
    });
  }

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

  function handleRefresh() {
    reload();
  }
  function handleSuccess() {
    reload();
  }

  function handleView(record: Recordable) {
    openModal(true, {
      isView: true,
      id: record.id,
    });
  }

  function getActions(record: Recordable): ActionItem[] {
    record.isCanEdit = false;

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

  .show {
    display: flex;
  }

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