<template>
  <PageWrapper dense fixedHeight contentFullHeight>
    <BasicTable @register="registerTable" isMenuTable>
      <template #toolbar>
        <template v-for="button in tableButtonConfig" :key="button.code">
          <a-button
            v-if="button.isDefault"
            type="primary"
            @click="buttonClick(button.code)"
            class="ml-4"
          >
            <template #icon><Icon :icon="button.icon" /></template>
            {{ button.name }}
          </a-button>
          <a-button v-else type="primary" class="ml-4">
            <template #icon><Icon :icon="button.icon" /></template>
            {{ button.name }}
          </a-button>
        </template>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <TableAction :actions="getActions(record)" />
        </template>
      </template>
    </BasicTable>

    <NewsModal @register="registerModal" @success="handleSuccess" />
    <ModalPanel
      :visible="viewOpen"
      :width="800"
      :title="viewData.briefHead"
      @submit="handleViewClose"
      @close="handleViewClose"
    >
      <ViewModal v-if="viewOpen" :viewData="viewData" />
    </ModalPanel>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, computed, createVNode } from 'vue';
  import { ModalPanel } from '/@/components/ModalPanel/index';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  import { getList, deleteOa, changeStatus } from '/@/api/system/oa';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { useRouter } from 'vue-router';

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

  import NewsModal from './components/NewsModal.vue';
  import ViewModal from './components/View.vue';
  import { searchFormSchema, columns } from './components/newsConfig';
  import Icon from '/@/components/Icon/index';
  import { OaType } from '../../../enums/oa';

  const { notification } = useMessage();
  const { t } = useI18n();
  defineEmits(['register']);
  const { filterColumnAuth, filterButtonAuth, hasPermission } = usePermission();
  const viewOpen = ref(false);
  const viewData: Recordable = ref({});
  const filterColumns = filterColumnAuth(columns);

  //展示在列表内的按钮
  const actionButtons = ref<string[]>([
    'view',
    'edit',
    'status',
    'copyData',
    'delete',
    'startwork',
  ]);
  const buttonConfigs = computed(() => {
    const list = [
      {
        isUse: true,
        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: 'status',
        icon: 'ant-design:heat-map-outlined',
        isDefault: false,
      },
      {
        isUse: true,
        name: '删除',
        code: 'delete',
        icon: 'ant-design:delete-outlined',
        isDefault: 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,
    delete: handleDelete,
    status: handlePublic,
  };

  const { currentRoute } = useRouter();

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

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

  const [registerTable, { reload }] = useTable({
    title: '新闻列表',
    api: getList,
    rowKey: 'id',
    columns: filterColumns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      showResetButton: false,
    },
    beforeFetch: (params) => {
      return { ...params, FormId: formIdComputedRef.value, type: OaType.NEWS, PK: 'id' };
    },

    useSearchForm: true,
    showTableSetting: true,

    striped: false,
    actionColumn: {
      width: 180,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    tableSetting: {
      size: false,
    },
    customRow: (record) => {
      return {
        ondblclick: () => {
          if (hasPermission('oaNews:edit')) {
            handleEdit(record);
          }
        },
      };
    },
  });

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

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

  function handleEdit(record: Recordable) {
    openModal(true, {
      id: record.id,
      isUpdate: true,
    });
  }
  async function handlePublic(record: Recordable) {
    try {
      await changeStatus(record.id);
      notification.success({
        message: 'Tip',
        description: t('成功！'),
      }); //提示消息
      handleSuccess();
    } catch (error) {
      notification.error({
        message: 'Tip',
        description: t('失败！'),
      }); //提示消息
    }
  }
  function handleDelete(record: Recordable) {
    deleteList([record.id]);
  }

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

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

  function handleView(record: Recordable) {
    viewData.value = record;
    viewOpen.value = true;
  }
  function handleViewClose() {
    viewOpen.value = false;
  }
  function getActions(record: Recordable): ActionItem[] {
    const actionsList: ActionItem[] = actionButtonConfig.value?.map((button) => {
      if (button.code === 'status') {
        return {
          label: record.enabledMark === 0 ? '发布' : '下架',
          onClick: btnEvent[button.code].bind(null, record),
        };
      } else {
        return {
          label: button?.name,
          color: button.code === 'delete' ? 'error' : undefined,
          onClick: 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>
