<template>
  <ResizePageWrapper :hasLeft="false">
    <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>
            <CustomButtonModal v-else-if="button.buttonType == 'modal'" :info="button" />
            <a-button
              v-else
              :type="button.buttonType === 'danger' ? 'default' : button.buttonType || 'primary'"
              :danger="button.buttonType === 'danger'"
            >
              <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="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>

    <XsckModal @register="registerModal" @success="handleFormSuccess" @cancel="handleFormCancel" />

    <ImportModal
      @register="registerImportModal"
      importUrl="/ckgl/xsck/import"
      @success="handleImportSuccess"
    />
    <ExportModal
      v-if="visibleExport"
      @close="visibleExport = false"
      :columns="columns"
      @success="handleExportSuccess"
    />
  </ResizePageWrapper>
</template>
<script lang="ts" setup>
  import { ref, computed, provide, Ref, 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 {
    getMesWarehouseSaleoutPage,
    deleteMesWarehouseSaleout,
    exportMesWarehouseSaleout,
  } from '/@/api/ckgl/xsck';
  import { ResizePageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
  import CustomButtonModal from '/@/components/Form/src/components/CustomButtonModal.vue';
  import { executeListStyle, getValue } from '/@/hooks/web/useListStyle'; //列表样式配置
  import { useRouter } from 'vue-router';
  import { useModal } from '/@/components/Modal';
  import XsckModal from './components/XsckModal.vue';
  import { ImportModal } from '/@/components/Import';
  import { downloadByData } from '/@/utils/file/download';
  import ExportModal from '/@/views/form/template/components/ExportModal.vue';
  import { searchFormSchema, columns } from './components/config';
  import Icon from '/@/components/Icon/index';
  import { useConcurrentLock } from '/@/hooks/web/useConcurrentLock';
  import { defHttp } from '/@/utils/http/axios';

  const listSpliceNum = ref(3); //操作列最先展示几个

  const pageParamsInfo = ref<any>({});
  const {
    enableLockeData,
    handleOpenFormEnableLockeData,
    handleCloseFormEnableLocke,
    handleHasEnableLocke,
  } = useConcurrentLock();

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

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

  const visibleExport = ref(false);

  //展示在列表内的按钮
  const actionButtons = ref<string[]>(['view', 'edit', 'delete']);
  const buttonConfigs = computed(() => {
    const list = [
      {
        buttonId: '2010591769687232512',
        name: '查看',
        code: 'view',
        icon: 'ant-design:eye-outlined',
        isDefault: true,
        isUse: true,
      },
      {
        buttonId: '2010591769687232513',
        name: '新增',
        code: 'add',
        icon: 'ant-design:plus-outlined',
        isDefault: true,
        isUse: true,
      },
      {
        buttonId: '2010591769687232518',
        name: '推质检',
        code: 'gen',
        icon: 'ant-design:plus-outlined',
        isDefault: true,
        isUse: true,
      },
      {
        buttonId: '2010591769687232514',
        name: '编辑',
        code: 'edit',
        icon: 'ant-design:form-outlined',
        isDefault: true,
        isUse: true,
        isEnableLock: true,
      },
      {
        buttonId: '2010591769687232515',
        name: '快速导入',
        code: 'import',
        icon: 'ant-design:import-outlined',
        isDefault: true,
        isUse: true,
      },
      {
        buttonId: '2010591769687232516',
        name: '快速导出',
        code: 'export',
        icon: 'ant-design:export-outlined',
        isDefault: true,
        isUse: true,
      },
      {
        buttonId: '2010591769687232517',
        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: handleEdit,
    import: handleImport,
    export: handleExport,
    delete: handleDelete,
    gen: handleTuizhijian,
  };

  const { currentRoute } = useRouter();

  const formIdComputedRef = computed(() => currentRoute.value.meta.formId as string);
  provide<Ref<string>>('currentFormId', formIdComputedRef);

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

  const [registerImportModal, { openModal: openImportModal }] = useModal();

  const [registerTable, { reload }] = useTable({
    title: 'Xsck列表',
    api: getMesWarehouseSaleoutPage,
    rowKey: 'id',
    columns: filterColumns,
    pagination: {
      pageSize: 10,
    },
    rowSelection: {
      type: 'checkbox',
    },
    formConfig: {
      labelWidth: 100,
      schemas: searchFormSchema,
      fieldMapToTime: [
        ['djrq', ['djrqStart', 'djrqEnd'], 'YYYY-MM-DD HH:mm:ss ', true],
        ['shrq', ['shrqStart', 'shrqEnd'], 'YYYY-MM-DD HH:mm:ss ', true],
      ],
      showResetButton: false,
    },
    bordered: false,
    beforeFetch: (params) => {
      pageParamsInfo.value = { ...params, FormId: formIdComputedRef.value, PK: 'id' };
      return pageParamsInfo.value;
    },
    afterFetch: (res) => {},
    useSearchForm: true,
    showTableSetting: true,

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

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

  function handleAdd() {
    openModal(true, { isUpdate: false });
  }
  // 推质检方法
  // index.vue
  async function handleTuizhijian() {
    const selectedRowKeys = tableRef.value?.getSelectRowKeys();
    if (!selectedRowKeys || selectedRowKeys.length === 0) {
      notification.warning({
        message: '提示',
        description: '请至少选择一条记录',
      });
      return;
    }
    const dataSource = tableRef.value?.getDataSource() || [];
    const selectedRecords = dataSource.filter((record) => selectedRowKeys.includes(record.id));
    const hasPushed = selectedRecords.some((record) => record.p30 === '1' || record.p30 === 1);
    if (hasPushed) {
      notification.warning({
        message: '提示',
        description: '已推送单据禁止再次推送',
      });
      return;
    }
    try {
      await defHttp.post({
        url: '/ckgl/xsck/gen',
        data: selectedRowKeys,
      });
      notification.success({
        message: '成功',
        description: '已推送至质检',
      });
      // 刷新列表，更新状态
      reload();
    } catch (error) {
      console.error('推质检失败', error);
    }
  }

  async function handleEdit(record: Recordable) {
    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,
      };

      openModal(true, info);
    } catch (error) {}
  }

  function handleDelete(record: Recordable) {
    deleteList([record.id]);
  }

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

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

  function handleSuccess() {
    reload();
  }

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

  function handleFormCancel() {
    handleCloseFormEnableLocke(buttonConfigs.value, 'edit');
  }

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

    openModal(true, info);
  }

  async function handleExport() {
    visibleExport.value = true;
  }

  async function handleExportSuccess(cols) {
    const res = await exportMesWarehouseSaleout({
      isTemplate: false,
      columns: cols.toString(),
      ...pageParamsInfo.value,
    });
    visibleExport.value = false;
    downloadByData(
      res.data,
      'Xsck.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    reload();
  }

  function handleImport() {
    openImportModal(true, {
      title: '快速导入',
      downLoadUrl: '/ckgl/xsck/export',
    });
  }

  function handleImportSuccess() {
    reload();
  }

  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;
        actionsList.push({
          ...button,

          auth: `xsck:${button.code}`,
          label: button?.name,
          color: button.code === 'delete' ? 'error' : undefined,
          onClick: btnEvent[button.code]?.bind(null, record),
        });
      } else {
        if (!['edit', 'delete'].includes(button.code)) {
          actionsList.push({
            auth: `xsck:${button.code}`,
            label: button?.name,
            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>
