<template>
  <PageWrapper dense fixedHeight contentFullHeight contentClass="flex">
    <BasicTable
      v-show="!visibleModaDetail"
      @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 === 'priority'">
          <div
            style="
              color: #ffffff;
              background: #ffaf5e;
              border-radius: 20px 20px 20px 20px;
              opacity: 1;
              width: fit-content;
              padding: 0 10px;
            "
            :style="{
              background:
                record.priority == '非常紧急'
                  ? '#FF5353'
                  : record.priority == '紧急'
                  ? '#FFAF5E'
                  : '#999999',
            }"
            >{{ record.priority }}</div
          >
        </template>
      </template>
    </BasicTable>

    <LookProcess
      v-if="visibleLookProcessRef"
      :taskId="taskIdRef"
      :processId="processIdRef"
      @close="visibleLookProcessRef = false"
      :visible="visibleLookProcessRef"
    />
    <LaunchProcess
      v-if="visibleLaunchProcessRef"
      :schemaId="schemaIdRef"
      :form-data="formDataRef"
      :form-id="formIdComputedRef"
      @close="handleCloseLaunch"
    />
    <ApprovalProcess
      v-if="visibleApproveProcessRef"
      :taskId="taskIdRef"
      :processId="processIdRef"
      :schemaId="schemaIdRef"
      @close="handleCloseApproval"
      :visible="visibleApproveProcessRef"
    />
    <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"
    />
    <ProOrderWorkModal @register="registerModal" @success="handleSuccess" />
    <a-modal
      :maskClosable="false"
      title="工单指派"
      v-model:visible="visibleModa2"
      :confirm-loading="confirmLoading"
      :width="1000"
      :footer="null"
    >
      <pointPropsModal
        :rowData="rowData2"
        @cancel="handleCancel"
        @success="handleSuccess"
      ></pointPropsModal>
    </a-modal>
    <a-modal
      :maskClosable="false"
      title="工序指派"
      v-model:visible="visibleModa1"
      :confirm-loading="confirmLoading"
      width="90%"
      :body-style="{
        height: '700px',
        overflow: 'hidden',
        overflowY: 'scroll',
      }"
      :style="{
        left: '5%',
        top: '120px',
      }"
      :footer="null"
    >
      <steppointPropsModal
        :rowData="rowData1"
        @cancel="handleCancel"
        @success="handleSuccess"
      ></steppointPropsModal>
    </a-modal>
    <!-- <a-modal
      :maskClosable="false"
      title="工单详情"
      v-model:visible="visibleModaDetail"
      :confirm-loading="confirmLoading"
      width="90%"
      :body-style="{
        height: '700px',
        overflow: 'hidden',
        overflowY: 'scroll',
      }"
      :style="{
        left: '5%',
        top: '120px',
      }"
      :footer="null"
    >
      <detailPropsModal
        :rowData="rowDataDetail"
        @cancel="visibleModaDetail = false"
        @success="visibleModaDetail = false"
      ></detailPropsModal>
    </a-modal> -->
    <div v-if="visibleModaDetail">
                 
      <detailPropsModal
        :rowData="rowDataDetail"
        @cancel="visibleModaDetail = false"
        @success="visibleModaDetail = false"
      ></detailPropsModal>
          </div
    >
  </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 {
    getMesProOrderworkPage,
    deleteMesProOrderwork,
    updateMesProOrderworkState,
  } from '/@/api/mes/proorderwork';
  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 { getMesProOrderwork } from '/@/api/mes/proorderwork';
  import { PrintButton } from '/@/enums/printEnum';
  import { InputParamItem } from '/@/components/ApiConfig/src/interface';

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

  import LookProcess from '/@/views/workflow/task/components/LookProcess.vue';
  import LaunchProcess from '/@/views/workflow/task/components/LaunchProcess.vue';
  import ApprovalProcess from '/@/views/workflow/task/components/ApprovalProcess.vue';
  import { getFormExecuteWorkflow } from '/@/api/form/execute';

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

  import pointPropsModal from '../proorderwork/components/pointPropsModal.vue';
  import steppointPropsModal from '../proorderwork/components/steppointPropsModal.vue';
  import detailPropsModal from '../proorderwork/components/detailPropsModal.vue';

  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', 'point', 'steppoint', 'stop', 'start', 'delete']);
  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: 'startwork',
      //   icon: 'ant-design:form-outlined',
      //   isDefault: true,
      // },
      {
        isUse: true,
        name: '批量指派',
        code: 'batchpoint',
        icon: 'ant-design:like-outlined',
        isDefault: true,
      },
      {
        isUse: true,
        name: '工单指派',
        code: 'point',
        icon: 'ant-design:like-outlined',
        isDefault: true,
      },
      {
        isUse: true,
        name: '工序派单',
        code: 'steppoint',
        icon: 'ant-design:dislike-outlined',
        isDefault: true,
      },
      {
        isUse: true,
        name: '暂停',
        code: 'stop',
        icon: 'ant-design:stop-outlined',
        isDefault: true,
      },
      {
        isUse: true,
        name: '恢复',
        code: 'start',
        icon: 'ant-design:rollback-outlined',
        isDefault: true,
      },
      {
        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 = {
    point: handleBatchpoint,
    view: handleView,
    batchpoint: handleBatchpoint,
    steppoint: handleSteppoint,
    delete: handleDelete,
    stop: handleStop,
    start: handleStart,
  };

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

  const visibleLookProcessRef = ref(false);
  const processIdRef = ref('');

  const visibleLaunchProcessRef = ref(false);
  const schemaIdRef = ref('');
  const formDataRef = ref();

  const visibleApproveProcessRef = ref(false);
  const taskIdRef = ref('');

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

  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: getMesProOrderworkPage,
    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: 220,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    customRow,
  });

  function buttonClick(code) {
    if (code.includes(PrintButton.CODE)) {
      printData.code = code;
    }
    btnEvent[code]();
  }
  function handleStart(record: Recordable) {
    Modal.confirm({
      title: '提示信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否确认恢复？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        updateMesProOrderworkState(record.id, record.preState).then((_) => {
          reload();
          notification.success({
            message: 'Tip',
            description: t('恢复成功！'),
          });
        });
      },
      onCancel() {},
    });
  }
  function handleStop(record: Recordable) {
    Modal.confirm({
      title: '提示信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否确认暂停？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        updateMesProOrderworkState(record.id, '7').then((_) => {
          reload();
          notification.success({
            message: 'Tip',
            description: t('暂停成功！'),
          });
        });
      },
      onCancel() {},
    });
  }

  function handleDelete(record: Recordable) {
    Modal.confirm({
      title: '提示信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否确认关单？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        updateMesProOrderworkState(record.id, '9').then((_) => {
          reload();
          notification.success({
            message: 'Tip',
            description: t('关单成功！'),
          });
        });
      },
      onCancel() {},
    });
  }

  const confirmLoading = ref<boolean>(false);
  const visibleModa2 = ref<boolean>(false);
  const rowData2 = ref({});
  const visibleModa1 = ref<boolean>(false);
  const rowData1 = ref({});

  const rowDataDetail = ref({});
  const visibleModaDetail = ref<boolean>(false);
  function handleSteppoint(record: Recordable) {
    rowData1.value.id = '';
    console.log('record===', record);
    rowData1.value = {
      id: record.id,
      isUpdate: true,
    };
    visibleModa1.value = true;
  }
  function handleBatchpoint(record: Recordable) {
    rowData2.value.workIds = '';
    let flag = true;
    console.log('record===', record);
    if (record) {
      rowData2.value = {
        workIds: record.id,
        isUpdate: true,
      };
    } else {
      //多选
      selectedRowsData.value.forEach((ele) => {
        if (!flag) return;
        if (ele.state && ele.state != '0') {
          notification.warning({
            message: 'Tip',
            description: t('工单[' + ele.workNo + ']非待下发状态，不可以指派'),
          });
          flag = false;
          return;
        }
      });
      rowData2.value = {
        workIds: selectedKeys.value?.join(','),
        isUpdate: true,
      };
    }
    if (flag) {
      visibleModa2.value = true;
    }
  }
  async function handleCancel() {
    visibleModa1.value = false;
    visibleModa2.value = false;
  }

  // function handleBatchdelete() {
  //   if (!selectedKeys.value.length) {
  //     notification.warning({
  //       message: 'Tip',
  //       description: t('请选择需要删除的数据'),
  //     });
  //     return;
  //   }
  //   //与工作流相关的数据不能进行批量删除
  //   const cantDelete = selectedRowsData.value.filter((x) => {
  //     return (
  //       (x.workflowData?.enabled && x.workflowData?.status) ||
  //       (!x.workflowData?.enabled && !!x.workflowData?.processId)
  //     );
  //   });
  //   if (cantDelete.length) {
  //     notification.warning({
  //       message: 'Tip',
  //       description: t('含有不能删除的数据'),
  //     });
  //     return;
  //   }
  //   deleteList(selectedKeys.value);
  // }
  // function deleteList(ids) {
  //   Modal.confirm({
  //     title: '提示信息',
  //     icon: createVNode(ExclamationCircleOutlined),
  //     content: '是否确认删除？',
  //     okText: '确认',
  //     cancelText: '取消',
  //     onOk() {
  //       deleteMesProOrderwork(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 getMesProOrderwork(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 handleRefresh() {
    reload();
  }
  function handleSuccess() {
    handleCancel();
    reload();
  }

  function handleView(record: Recordable) {
    rowDataDetail.value.id = '';
    console.log('record===', record);
    rowDataDetail.value = {
      id: record.id,
      isUpdate: false,
    };
    visibleModaDetail.value = true;
  }

  function getActions(record: Recordable): ActionItem[] {
    let actionsList: ActionItem[] = [];
    let editAndDelBtn: ActionItem[] = [];
    actionButtonConfig.value?.map((button) => {
      if (button.code === 'view') {
        actionsList.push({
          icon: button?.icon,
          tooltip: button?.name,
          onClick: handleView.bind(null, record),
        });
      }
      if (['start', 'stop', 'delete', 'batchpoint', 'steppoint', 'point'].includes(button.code)) {
        editAndDelBtn.push({
          icon: button?.icon,
          tooltip: button?.name,
          color:
            button.code === 'start' || button.code === 'stop' || button.code === 'delete'
              ? 'error'
              : undefined,
          onClick: btnEvent[button.code].bind(null, record),
        });
      }
    });
    if (record.workflowData.enabled) {
      //与工作流有关联的表单
      if (record.workflowData.status) {
        //如果是本人需要审批的数据 就会有taskIds  所以需要修改绑定事件
        const act: ActionItem = {};
        if (record.workflowData.taskIds) {
          act.tooltip = '查看流程(待审批)';
          act.icon = 'daishenpi|svg';
          act.onClick = handleApproveProcess.bind(null, record);
        } else {
          act.tooltip =
            '查看流程' + (record.workflowData.status === 'ACTIVE' ? '(审批中)' : '(已完成)');
          act.icon =
            record.workflowData.status === 'ACTIVE' ? 'jinshenpi|svg' : 'shenpiwancheng|svg';
          act.onClick = handleStartwork.bind(null, record);
        }
        actionsList.unshift(act);
      } else {
        actionsList.unshift({
          icon: 'faqishenpi|svg',
          tooltip: '发起审批',
          onClick: handleLaunchProcess.bind(null, record),
        });
        actionsList = actionsList.concat(editAndDelBtn);
      }
    } else {
      if (!record.workflowData.processId) {
        //与工作流没有关联的表单并且在当前页面新增的数据 如选择编辑、删除按钮则加上
        actionsList = actionsList.concat(editAndDelBtn);
      }
    }
    return actionsList.filter((e) => {
      if (e.tooltip == '暂停') {
        if (
          !record.state ||
          (record.state != '8' &&
            record.state != '已完成' &&
            record.state != '9' &&
            record.state != '已关闭' &&
            record.state != '7' &&
            record.state != '已暂停')
        )
          return true;
        else return false;
      } else if (e.tooltip == '恢复') {
        if (record.state == '7' || record.state == '已暂停') return true;
        else return false;
      } else if (e.tooltip == '关单') {
        if (
          !record.state ||
          (record.state != '8' &&
            record.state != '已完成' &&
            record.state != '9' &&
            record.state != '已关闭' &&
            record.state != '7' &&
            record.state != '已暂停')
        )
          return true;
        else return false;
      } else if (e.tooltip == '工单指派') {
        if (
          (!record.state || record.state == '0' || record.state == '待下发') &&
          record.sendType != '2'
        )
          return true;
        else return false;
      } else if (e.tooltip == '工序派单') {
        if (!record.state || record.state == '0' || record.state == '待下发') return true;
        else return false;
      } else return true;
    });
  }

  function handleStartwork(record: Recordable) {
    if (record.workflowData) {
      visibleLookProcessRef.value = true;
      processIdRef.value = record.workflowData.processId;
    }
  }
  async function handleLaunchProcess(record: Recordable) {
    if (record.workflowData) {
      const result = await getFormExecuteWorkflow({
        formId: formIdComputedRef.value,
        id: record['id'],
      });

      visibleLaunchProcessRef.value = true;
      schemaIdRef.value = record.workflowData.schemaId;
      formDataRef.value = result;
    }
  }
  function handleApproveProcess(record: Recordable) {
    visibleApproveProcessRef.value = true;
    schemaIdRef.value = record.workflowData.schemaId;
    processIdRef.value = record.workflowData.processId;
    taskIdRef.value = record.workflowData.taskIds[0];
  }
  function handleCloseLaunch() {
    visibleLaunchProcessRef.value = false;
    reload();
  }
  function handleCloseApproval() {
    visibleApproveProcessRef.value = false;
    reload();
  }
</script>
<style lang="less" scoped>
  :deep(.ant-table-selection-col) {
    width: 50px;
  }
</style>
