<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 === '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>

    <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"
    />
    <ProOrderPlanModal @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="handleCancel" @success="handleSuccess"></propsModal>
    </a-modal>
    <!-- 生产工单 -->
    <a-modal
      :maskClosable="false"
      :title="titleModa"
      v-model:visible="visibleModa2"
      :confirm-loading="confirmLoading"
      :width="1000"
      :footer="null"
    >
      <propsModal2
        :rowData="rowData2"
        @cancel="handleCancel"
        @success="handleSuccess"
      ></propsModal2>
    </a-modal>
    <a-modal
      :maskClosable="false"
      title="作废"
      v-model:visible="visibleModaCancel"
      :confirm-loading="confirmLoading"
      :width="500"
      :footer="null"
    >
      <div style="height: 300px; padding-top: 20px; padding-right: 20px">
        <div>
          <a-form ref="formRef" :model="cancelData" :labelCol="{ span: 6 }">
            <a-col :span="24">
              <a-form-item label="作废理由" name="cancelRemark" required>
                <a-textarea
                  maxlength="200"
                  :disabled="cancelState && cancelState.length > 0"
                  v-model:value="cancelData.cancelRemark"
                  :auto-size="{ minRows: 2, maxRows: 5 }"
                />
              </a-form-item>
            </a-col>
          </a-form>
        </div>
        <div
          style="
            padding: 10px 16px;
            text-align: right;
            background: white;
            border-top: 1px solid rgb(240, 240, 240);
            border-radius: 0px 0px 2px 2px;
            position: absolute;
            bottom: 1px;
            width: 98%;
          "
          v-if="!cancelState"
        >
          <a-button @click="handleCancelRecordClose">取消</a-button>
          <a-button @click="handleCancelRecordSubmit" type="primary" style="margin-left: 12px"
            >确认</a-button
          >
        </div>
      </div>
    </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 {
    getMesProOrderplanPage,
    deleteMesProOrderplan,
    cancelMesProOrderPlan,
  } from '/@/api/mes/proorderplan';
  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 { getMesProOrderplan } from '/@/api/mes/proorderplan';
  import { PrintButton } from '/@/enums/printEnum';
  import { InputParamItem } from '/@/components/ApiConfig/src/interface';

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

  import ProOrderPlanModal from './components/ProOrderPlanModal.vue';
  import propsModal from '../proorderplan/components/propsModal.vue';
  import propsModal2 from '../proorderwork/components/propsModal.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', 'edit', 'delete', 'startwork', 'addWork']);
  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: 'delete',
        icon: 'ant-design:delete-outlined',
        isDefault: true,
      },
      {
        isUse: true,
        name: '作废',
        code: 'batchdelete',
        icon: 'ant-design:delete-outlined',
        isDefault: true,
      },
      {
        isUse: true,
        name: '生成工单',
        code: 'addWork',
        icon: 'ant-design:plus-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: handleAddPlan,
    edit: handleEdit,
    delete: handleCancelRecord,
    batchdelete: handleCancelRecord,
    addWork: handleAddPlan,
  };

  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();

  // 模板打印 入参参数
  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: getMesProOrderplanPage,
    rowKey: 'id',
    columns: filterColumns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [
        ['onlineDate', ['onlineDateStart', 'onlineDateEnd'], 'YYYY-MM-DD ', true],
        ['createDate', ['createDateStart', 'createDateEnd'], 'YYYY-MM-DD ', true],
      ],
    },
    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 handleAdd() {
    openModal(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    // openModal(true, {
    //   id: record.id,
    //   isUpdate: true,
    // });
    rowData.value = {
      id: record.id,
      orderId: record.orderId,
      orderNo: record.orderNo,
      isUpdate: true,
    };

    titleModa.value = '编辑生产计划';
    visibleModa.value = true;
  }
  const titleModa = ref<string>('');
  const visibleModa = ref<boolean>(false);
  const confirmLoading = ref<boolean>(false);
  const rowData = ref({});
  const visibleModa2 = ref<boolean>(false);
  const rowData2 = ref({});

  function handleView(record: Recordable) {
    rowData2.value.planIds = '';
    console.log('record===', record);
    rowData2.value = {
      planIds: record.id,
      isUpdate: false,
    };
    titleModa.value = '查看工单';
    visibleModa2.value = true;
  }
  function handleAddPlan(record: Recordable) {
    rowData2.value.planIds = '';
    let flag = true;
    console.log('record===', record);
    if (record) {
      rowData2.value = {
        planIds: record.id,
        isUpdate: true,
      };
    } else {
      //多选，需判断同车间，同产线：
      let carId = '';
      let lineId = '';
      if (selectedKeys.value?.length == 0) {
        notification.warning({
          message: 'Tip',
          description: t('请选择生产计划'),
        });
        return;
      }
      selectedRowsData.value.forEach((ele) => {
        if (!flag) return;
        if (carId.length == 0) carId = ele.carId;
        if (lineId.length == 0) lineId = ele.lineId;
        if (carId != ele.carId || lineId != ele.lineId) {
          notification.warning({
            message: 'Tip',
            description: t('请选择同一车间同一产线的生产计划'),
          });
          flag = false;
          return;
        }
      });
      rowData2.value = {
        planIds: selectedKeys.value?.join(','),
        isUpdate: true,
      };
    }
    if (flag) {
      titleModa.value = '生成工单';
      visibleModa2.value = true;
    }
  }
  async function handleCancel() {
    visibleModa.value = false;
    visibleModa2.value = false;
  }
  const cancelData = ref<any>({
    cancelRemark: '',
    state: '',
    id: '',
  });
  const visibleModaCancel = ref<boolean>(false);

  function handleCancelRecord(record: Recordable) {
    cancelData.value.cancelRemark = '';
    cancelData.value.id = '';
    cancelData.value.state = '';

    console.log('record', record);
    if (record) {
      selectedKeys.value = [];
      cancelData.value.id = record.id;
      if (record.state == '3' || record.state == '已作废') {
        cancelData.value.cancelRemark = record.cancelRemark;
        cancelData.value.state = record.state;
      }
    } else {
      if (!selectedKeys.value.length) {
        notification.warning({
          message: 'Tip',
          description: t('请选择需要作废的数据'),
        });
        return;
      }
    }
    visibleModaCancel.value = true;
  }
  function handleCancelRecordClose() {
    visibleModaCancel.value = false;
  }
  function handleCancelRecordSubmit() {
    // Modal.confirm({
    //   title: '提示信息',
    //   icon: createVNode(ExclamationCircleOutlined),
    //   content: '是否确认作废？',
    //   okText: '确认',
    //   cancelText: '取消',
    //   onOk() {
    if (!selectedKeys.value.length) {
      selectedKeys.value.push(cancelData.value.id);
      console.log('selectedKeys.value', selectedKeys.value);
    }
    if (!cancelData.value.cancelRemark || cancelData.value.cancelRemark.length == 0) {
      notification.error({
        message: 'Tip',
        description: t('请填写作废理由'),
      });
      return;
    }
    cancelMesProOrderPlan(selectedKeys.value, cancelData.value.cancelRemark).then((_) => {
      handleCancelRecordClose();
      reload();
      notification.success({
        message: 'Tip',
        description: t('作废成功！'),
      });
    });
    //   },
    //   onCancel() {},
    // });
  }
  function handleDelete(record: Recordable) {
    deleteList([record.id]);
  }

  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() {
        deleteMesProOrderplan(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 getMesProOrderplan(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() {
    handleCancel();
    visibleModa.value = false;
    reload();
  }

  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.filter((e) => {
      if (e.tooltip == '编辑' || e.tooltip == '生成工单') {
        if (!record.state || record.state == '1' || record.state == '待生成工单') return true;
        else return false;
      } else if (e.tooltip == '作废') {
        if (!record.state || (record.state != '3' && record.state != '已作废')) return true;
        else return false;
      } else if (e.tooltip == '查看工单') {
        if (record.state && record.state != '1' && record.state != '待生成工单') return true;
        else return false;
      } else return true;
    });
  }
</script>
<style lang="less" scoped>
  :deep(.ant-table-selection-col) {
    width: 50px;
  }
</style>
