<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 v-if="column.dataIndex === 'state'">
          <template v-if="record.state == 1">
            <div style="color: #5e95ff">待维修</div>
          </template>
          <template v-if="record.state == 2">
            <div style="color: #fdae37">维修中</div>
          </template>
          <template v-if="record.state == 3">
            <div style="color: #12b700">已维修</div>
          </template>
          <template v-if="record.state == 4">
            <div style="color: #ff0000">已报损</div>
          </template>
        </template>
      </template>
    </BasicTable>

    <PrintPreview
      v-if="printData.visible"
      :id="printData.id"
      :request-params-configs="printData.requestParamsConfigs"
      :request-body-configs="printData.requestBodyConfigs"
      :request-header-configs="printData.requestHeaderConfigs"
      @close="printData.visible = false"
    />
    <DevRepairModal @register="registerModal" @success="handleSuccess" />

    <!-- 自己写的查看和编辑弹窗 -->
    <a-modal
      :maskClosable="false"
      :title="titleModa"
      v-model:visible="visibleModa"
      :confirm-loading="confirmLoading"
      :width="1000"
      :footer="null"
    >
      <propsModal :rowData="rowData" @cancel="handelCancel" @success="handelSuccess"></propsModal>
    </a-modal>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, computed, createVNode, reactive } from 'vue';

  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  import {
    getMesDevRepairPage,
    deleteMesDevRepair,
    exportMesDevRepair,
  } from '/@/api/mes/devrepair';
  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 { getPrintConfigInfo } from '/@/api/system/generator/print';
  import PrintPreview from '/@/views/generator/print/Preview.vue';
  import { getMesDevRepair, updateMesDevRepair } from '/@/api/mes/devrepair';
  import { PrintButton } from '/@/enums/printEnum';
  import { InputParamItem } from '/@/components/ApiConfig/src/interface';

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

  import DevRepairModal from './components/DevRepairModal.vue';
  import propsModal from './components/propsModal.vue';

  import { downloadByData } from '/@/utils/file/download';

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

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

  const filterColumns = filterColumnAuth(columns, false);
  //展示在列表内的按钮
  const actionButtons = ref<string[]>(['view', 'edit', 'delete', 'startwork', 'repair', 'losses']);
  const buttonConfigs = computed(() => {
    const list = [
      { 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: 'repair',
        icon: 'ant-design:setting-twotone',
        isDefault: true,
      },
      {
        isUse: true,
        name: '报损',
        code: 'losses',
        icon: 'ant-design:alert-outlined',
        isDefault: true,
      },
      {
        isUse: true,
        name: '删除',
        code: 'delete',
        icon: 'ant-design:delete-outlined',
        isDefault: true,
      },
      {
        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 = {
    view: handleView,
    add: handleAdd,
    edit: handleEdit,
    delete: handleDelete,
    export: handleExport,
    repair: handleRepair,
    losses: handleLosses,
  };

  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 titleModa = ref<string>('');
  const visibleModa = ref<boolean>(false);
  const confirmLoading = ref<boolean>(false);

  const rowData = ref({});

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

  // 模板打印 入参参数
  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: [],
  });

  const [registerTable, { reload }] = useTable({
    title: '设备维修',
    api: getMesDevRepairPage,
    rowKey: 'id',
    columns: filterColumns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [],
    },
    beforeFetch: (params) => {
      return { ...params, FormId: formIdComputedRef.value, PK: 'id' };
    },
    useSearchForm: true,
    showTableSetting: false,
    showLine: true,
    striped: false,
    actionColumn: {
      align: 'left',
      width: 280,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    customRow,
  });

  function buttonClick(code) {
    if (code.includes(PrintButton.CODE)) {
      printData.code = code;
    }
    btnEvent[code]();
  }

  function handleAdd() {
    openModal(true, {
      isUpdate: false,
    });
  }
  function handleEdit(record: Recordable) {
    openModal(true, {
      id: record.id,
      isUpdate: true,
    });
  }
  function handleRepair(record: Recordable) {
    rowData.value = {
      id: record.id,
      isUpdate: true,
      flag: '维修',
    };

    titleModa.value = '维修单维修';
    visibleModa.value = true;
  }
  function handleLosses(record: Recordable) {
    rowData.value = {
      id: record.id,
      isUpdate: true,
      flag: '报损',
    };

    titleModa.value = '维修单报损';
    visibleModa.value = true;
  }

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

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

  // 模板打印
  async function handleTemplateprint() {
    if (!selectedKeys.value.length) {
      notification.warning({
        message: t('提示'),
        description: t('请选择数据'),
      });
      return;
    }
    if (selectedKeys.value.length > 1) {
      notification.warning({
        message: t('提示'),
        description: t('只能选择一条数据进行操作'),
      });
      return;
    }
    let id = selectedKeys.value[0];
    try {
      const record = await getMesDevRepair(id);
      let res = await getPrintConfigInfo(printData.code, printMenuId.value);
      if (res.enabledMark == null) {
        notification.warning({
          message: t('提示'),
          description: t('当前功能未绑定打印模板，请绑定后再进行模板打印。'),
        });
        return;
      }
      if (res.enabledMark == 0) {
        notification.warning({
          message: t('提示'),
          description: t('找不到打印模板，请联系管理员。'),
        });
        return;
      }
      printData.id = res.schemaId;
      if (res.apiConfig) {
        let json = JSON.parse(res.apiConfig);
        if (json.requestParamsConfigs && json.requestParamsConfigs.length > 0) {
          printData.requestParamsConfigs = json.requestParamsConfigs.map((ele) => {
            if (ele.config && record[ele.config] != undefined) {
              ele.value = record[ele.config];
            }
            return ele;
          });
        }
        if (json.requestHeaderConfigs && json.requestHeaderConfigs.length > 0) {
          printData.requestHeaderConfigs = json.requestHeaderConfigs.map((ele) => {
            if (ele.config && record[ele.config] != undefined) {
              ele.value = record[ele.config];
            }
            return ele;
          });
        }
        if (json.requestBodyConfigs && json.requestBodyConfigs.length > 0) {
          printData.requestBodyConfigs = json.requestBodyConfigs.map((ele) => {
            if (ele.config && record[ele.config] != undefined) {
              ele.value = record[ele.config];
            }
            return ele;
          });
        }
        printData.visible = true;
      } else {
        notification.warning({
          message: t('提示'),
          description: t('当前功能未绑定打印模板，请绑定后再进行模板打印。'),
        });
      }
    } catch (error) {}
  }

  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) {
    rowData.value = {
      id: record.id,
      isUpdate: false,
    };

    titleModa.value = '查看维修单';
    visibleModa.value = true;
  }

  async function handleExport() {
    const res = await exportMesDevRepair({ 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 {};
        }
      }
    });
    // console.log('actionsList', actionsList);
    return actionsList.filter((e) => {
      if (e.tooltip == '编辑') {
        if (record.state == '1') return true;
        else return false;
      } else if (e.tooltip == '删除') {
        if (record.state == '1') return true;
        else return false;
      } else if (e.tooltip == '维修') {
        if (record.state == '1' || record.state == '2') return true;
        else return false;
      } else if (e.tooltip == '报损') {
        if (record.state == '1' || record.state == '2') return true;
        else return false;
      } else return true;
    });
  }

  const handelCancel = () => {
    visibleModa.value = false;
  };

  async function handelSuccess(obj) {
    if (!obj) {
      visibleModa.value = false;
      reload();
      return;
    }
    const data = await updateMesDevRepair(obj);
    if (data) {
      reload();
      notification.success({
        message: 'Tip',
        description: t('修改成功！'),
      });
      visibleModa.value = false;
    }
  }
</script>
<style lang="less" scoped>
  :deep(.ant-table-selection-col) {
    width: 50px;
  }
</style>
