<template>
  <PageWrapper dense fixedHeight contentFullHeight contentClass="flex">
    <BasicTable
      @register="registerTable"
      :row-selection="{ selectedRowKeys: selectedKeys, onChange: onSelectChange }"
    >
      <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="primary">
            <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>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, computed, createVNode, reactive } from 'vue';
  import { DownOutlined, UpOutlined } from '@ant-design/icons-vue';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  import { getLostStaticList, exportLostStaticList } from '/@/api/mes/common/statistic';
  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 { PrintButton } from '/@/enums/printEnum';
  import { InputParamItem } from '/@/components/ApiConfig/src/interface';
  import { searchFormSchema, columns } from './components/config';
  import Icon from '/@/components/Icon/index';
  import { downloadByData } from '/@/utils/file/download';
  const { notification } = useMessage();
  const { t } = useI18n();
  defineEmits(['register']);
  const { filterButtonAuth } = usePermission();

  // const filterColumns = filterColumnAuth(columns, false);
  //展示在列表内的按钮
  const actionButtons = ref<string[]>([]);
  const buttonConfigs = computed(() => {
    const list = [
      {
        isUse: true,
        name: '导出',
        code: 'export',
        icon: 'ant-design:export-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 = {
    export: handleExport,
  };

  const { currentRoute } = useRouter();
  const printMenuId = computed(() => currentRoute.value.meta.menuId as string);
  const formIdComputedRef = computed(() => currentRoute.value.meta.formId as string);

  const selectedKeys = ref<string[]>([]);
  const selectedRowsData = ref<any[]>([]);

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

  const [registerTable, { reload }] = useTable({
    title: '产量统计',
    api: getLostStaticList,
    rowKey: 'id',
    columns: columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [['dataDate', ['startDate', 'endDate'], 'YYYY-MM-DD ', true]],
    },
    beforeFetch: (params) => {
      return { ...params, FormId: formIdComputedRef.value, PK: 'id' };
    },
    useSearchForm: true,
    showTableSetting: false,
    showLine: true,
    striped: false,

    customRow,
  });
  // 模板打印 入参参数
  let printData: {
    visible: boolean;
    id: string;
    code: string;
    requestParamsConfigs: Array<InputParamItem>;
    requestHeaderConfigs: Array<InputParamItem>;
    requestBodyConfigs: Array<InputParamItem>;
  } = reactive({
    visible: false,
    id: '',
    code: '',
    requestParamsConfigs: [],
    requestHeaderConfigs: [],
    requestBodyConfigs: [],
  });
  function buttonClick(code) {
    if (code.includes(PrintButton.CODE)) {
      printData.code = code;
    }
    btnEvent[code]();
  }

  function onSelectChange(selectedRowKeys: [], selectedRows) {
    selectedKeys.value = selectedRowKeys;
    selectedRowsData.value = selectedRows;
  }

  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;
      },
    };
  }

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

  // function handleView(record: Recordable) {
  // }

  async function handleExport() {
    const res = await exportLostStaticList({ isTemplate: false });
    downloadByData(
      res.data,
      '缺陷统计.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
  }

  function getActions(record: Recordable): ActionItem[] {
    const actionsList: ActionItem[] = actionButtonConfig.value?.map((button) => {
      if (!record.workflowData?.processId) {
        return {
          icon: button?.icon,
          tooltip: button?.name,
          color: button.code === 'delete' ? 'error' : undefined,
          onClick: btnEvent[button.code].bind(null, record),
        };
      } else {
        if (button.code === 'view') {
          return {
            icon: button?.icon,
            tooltip: 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;
  }
</style>
