import { connect } from "umi";
import { Icon as LegacyIcon } from "@ant-design/compatible";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { Tabs, Modal } from "antd-v4";
import IndexCenter from "@/routes/indexCenter/indexCenter"; /* 首页 */
import TabComponent from "@/components/Tab/TabComponent";
import CommonListEdit from "@/routes/commonList/commonListEdit"; /* 可编辑公共列表 */
import CommonList from "@/routes/commonList/commonList"; /* 公共列表 */
import CommonListA from "@/routes/commonList/commonListA"; /* 无需注册模块验证的公共列表 */
import CommonListTab from "@/routes/commonList/commonListTab"; /* 多个列表 */
import CommonBill from "@/routes/commonList/commonBill"; /* 通用单据页 */
import CommonNewBill from "@/routes/commonList/commonNewBill"; /* 通用单据页 */
import CommonClassify from "@/routes/commonClassify/commonClassify"; /* 公共分类 */
import CustomerInfo from "@/routes/basicInfoSetting/customerInfo/customerInfo"; /* 客户信息 */
import CommonColumnList from "@/routes/commonColumnList/commonColumnList"; /* 公共自定义标题列表 */
import CommonListTree from "@/routes/commonListTree/commonListTree"; /* 两层通用结构commonListTree,功能如物料需求计划 */
import CommonListLeft from "@/routes/commonList/commonListLeft"; /* 左侧树形 */
import CommonGatte from "@/routes/commonGatte/commonGatte"; /* 甘特图列表 */
import MaterialRequirementsPlanning from "@/routes/materialRequirementsPlanning/materialRequirementsPlanning"; /* 物料需求计划 */
import TestStandInfo from "@/routes/basicInfoSetting/teststandInfo/teststandInfo"; /* 刀模信息 */
import Employee from "@/routes/basicInfoSetting/employee/employee"; /* 职员信息 */
import Materiel from "@/routes/basicInfoSetting/materiel/materiel"; /* 物料信息 */
import PrintInfo from "@/routes/basicInfoSetting/printInfo/printInfo"; /* 印件信息 */
import SystemSetting from "@/routes/basicInfoSetting/systemSetting/systemSetting"; /* 印件信息 */
import SupplyInfo from "@/routes/basicInfoSetting/supplyInfo/supplyInfo"; /* 权限分配 */
import ProcessInfo from "@/routes/basicInfoSetting/processInfo/processInfo"; /* 工序信息 */
import CheckModel from "@/routes/basicInfoSetting/checkModel/checkModel"; /* 审核模板 */
import CheckPhase from "@/routes/basicInfoSetting/checkPhase/checkPhase"; /* 审核阶段 */
import SftLoginInfo from "@/routes/basicInfoSetting/sftLoginInfo/sftLoginInfo"; /* 用户管理 */
import Commonstyle from "@/routes/basicInfoSetting/commonStyle/commonStyle"; /* 常用规格 */
import ProductClassify from "@/routes/basicInfoSetting/productClassify/productClassify"; /* 印件分类信息 */
import CommonCheckBill from "@/routes/common/commonCheckBill"; /* 通用预览单据页 */
import WorkOrderNew from "@/routes/manufacture/workOrder/workOrder"; /* 生产施工单 */
import WorkOrderPack from "@/routes/manufacture/workOrderPack/workOrderPack"; /* 包装施工单 */
import WorkOrderPackTableTree from "@/routes/manufacture/workOrderPackTableTree/workOrderPackTableTree"; /* 包装施工单 */
import WorkOrderResearchTableTree from "@/routes/manufacture/workOrderResearchTableTree/workOrderResearchTableTree"; /* 研发工单 */
import ProcessCardInfo from "@/routes/manufacture/processCard/processCardInfo";
import ProcessCardInfoPack from "@/routes/manufacture/processCardPack/processCardInfoPack";
import ProcessCardPackTableTree from "@/routes/manufacture/processCardPackTableTree/processCardPackTableTree";
import ProcessCardPackTableTreeNew from "@/routes/manufacture/processCardPackTableTreeNew/processCardPackTableTreeNew";
import WorkOrderPackTableTreeNew from "@/routes/manufacture/workOrderPackTableTreeNew/workOrderPackTableTreeNew";
import ProductionPlan from "@/routes/productionPlan/productionPlan"; /* 生产排程 */
import styles from "@/index.less";
import { sendWebSocketMessage } from "@/components/Common/commonFunc";
import { isNotEmptyObject, isNotEmptyArr } from "@/utils/utils"; /* 通用方法 */
import KnifemouldInfo from "@/routes/basicInfoSetting/knifemouldInfo/knifemouldInfo"; /* 刀模信息 */
import CommonChar from "@/routes/commonChar/commonChar"; /* 通用图表页 */
import CommonAuto from "@/routes/commonAuto/commonAuto"; /* 通用自定义界面 */
import EleteamInfo from "@/routes/common/eleteamInfo"; /* 班组信息页 新 */
import SisFormulaInfo from "@/routes/basicInfoSetting/sisFormula/sisFormulaInfo";
import EleMachineInfo from "@/routes/basicInfoSetting/machineInfo/eleMachineInfo"; /* 设备信息 */
import SystemPermissionInfo from "@/routes/basicInfoSetting/systemPermission/systemPermissionInfo"; /* 设备信息 */
import QuotationPackTableTree from "@/routes/quoQuotation/quotationPackTableTree/quotationPackTableTree";
import ImportDataInfo from "@/routes/importData/importData"; /* 设备信息 */
import PaymentTermsInfo from "@/routes/basicInfoSetting/paymentInfo/paymentInfoTerms";
import ProductionReport from "@/routes/basicInfoSetting/productReport/productReport"; /* 产量上报 */
import ProductionMainPlan from "@/routes/productionMainPlan/productionMainPlan"; /*  新生产主计划 */
import ProductionPlanInfo from "@/routes/productionPlan/productionPlanInfo"; /*  新生产排程 */
import ProductionPlanOutside from "@/routes/productionPlan/productionPlanOutside"; /*  发外排程 */
import ProductionSchedule from "@/routes/productionSchedule/productionScheduleInfo"; /*  生产排程甘特图 */
import ProductionScheduleTree from "@/routes/productionScheduleTree/productionScheduleTree"; /*  生产排程tree(金宣发) */
import AuditInformation from "@/routes/basicInfoSetting/auditInformation/auditInformation"; /* 审核信息 */
import SysMsgInfo from "@/routes/basicInfoSetting/mailMsg/sysMsgInfo";
import PrintLabel from "@/routes/basicInfoSetting/printLabel/printLabel";
import MonthEndingClosing from "@/routes/basicInfoSetting/closeAccounts/monthEndingClosing";
import Quotation from "@/routes/quoQuotation/quotation/quotation"; /* 审核信息 */
import QuotationPack from "@/routes/quoQuotation/quotationPack/quotationPack"; /* 报价单(套装) */
import ProductionUnifiedPlanning from "@/routes/productionMainPlan/productionUnifiedPlanning"; /*  主计划统一规划 */
import ProductionPlanChangeMachine from "@/routes/productionPlan/productionPlanChangeMachineInfo"; /*  新生产排程 更换班组机台 */
import CommonBillDeliver from "@/routes/common/commonBillDeliver"; /* 送货单个性化 */
import CommonSubBill from "@/routes/common/commonSubBill"; /* 通用嵌套子表单据 */
import CommonNewTabBill from "@/routes/common/commonNewTabBill"; /* 通用单据页 */
import CommonCostomTabBill from "@/routes/common/commonCostomTabBill";
import CommonNewListBill from "@/routes/common/commonNewListBill"; /* 通用单据页 */
import CommonGroupBill from "@/routes/common/commonGroupBill"; /* 通用单据页 */
import PrintPdf from "../printPdf/printPdf"; /* 单预览 */
import Feedback from '../feedback/feedback';
import * as commonFunc from "@/components/Common/commonFunc";
/* 计算方案s */
const { confirm } = Modal;
const { TabPane } = Tabs;

function Tab({ dispatch, app }) {
  const { panes } = app;
  let paneType = "";
  const tagArr = panes.filter(item => item.newRecordFlag !== undefined);
  const tagLastKey = tagArr !== undefined && tagArr.length > 0 ? tagArr[tagArr.length - 1].key : "";
  const tabpanes = panes.map(pane => {
    const bRecordFlagDisabled = tagArr.length > 0 && pane.key !== tagLastKey;
    const routeList = {
      "/indexPage/commonList": <CommonList />,
      "/indexPage/commonListA": <CommonListA />,
      "/indexPage/commonNewBill": <CommonNewBill />,
      "/indexPage/commonBill": <CommonBill />,
      "/indexPage/commonListEdit": <CommonListEdit />,
      "/indexPage/commonClassify": <CommonClassify />,
      "/indexPage/eleknifemould": <KnifemouldInfo />,
      "/indexPage/elecustomer": <CustomerInfo />,
      "/indexPage/commonListTab": <CommonListTab />,
      "/indexPage/commonColumnList": <CommonColumnList />,
      "/indexPage/commonListTree": <CommonListTree />,
      "/indexPage/commonListLeft": <CommonListLeft />,
      "/indexPage/commonGatte": <CommonGatte />,
      "/indexPage/materialRequirementsPlanning": <MaterialRequirementsPlanning />,
      "/indexPage/eleteststand": <TestStandInfo />,
      "/indexPage/eleemployee": <Employee />,
      "/indexPage/elematerials": <Materiel />,
      "/indexPage/eleproduct": <PrintInfo />,
      "/indexPage/syssystemsettings": <SystemSetting />,
      "/indexPage/elesupply": <SupplyInfo />,
      "/indexPage/eleprocess": <ProcessInfo />,
      "/indexPage/elecheckmodel": <CheckModel />,
      "/indexPage/sischeckphase": <CheckPhase />,
      "/indexPage/sftlogininfo": <SftLoginInfo />,
      "/indexPage/siscommonstyle": <Commonstyle />,
      "/indexPage/sisproductclassify": <ProductClassify />,
      "/indexPage/commonCheckBill": <CommonCheckBill />,
      "/indexPage/workOrderNew": <WorkOrderNew />,
      "/indexPage/workOrderPack": <WorkOrderPack />,
      "/indexPage/workOrderPackTableTree": <WorkOrderPackTableTree />,
      "/indexPage/workOrderResearchTableTree": <WorkOrderResearchTableTree />,
      "/indexPage/processCard": <ProcessCardInfo />,
      "/indexPage/processCardPack": <ProcessCardInfoPack />,
      "/indexPage/processCardPackTableTree": <ProcessCardPackTableTree />,
      "/indexPage/processCardPackTableTreeNew": <ProcessCardPackTableTreeNew />,
      "/indexPage/workOrderPackTableTreeNew": <WorkOrderPackTableTreeNew />,
      "/indexPage/productionPlan": <ProductionPlan />,
      "/indexPage/commonChar": <CommonChar />,
      "/indexPage/commonAuto": <CommonAuto />,
      "/indexPage/eleteamInfo": <EleteamInfo />,
      "/indexPage/sisformulaInfo": <SisFormulaInfo />,
      "/indexPage/elemachineInfo": <EleMachineInfo />,
      "/indexPage/systemPermission": <SystemPermissionInfo />,
      "/indexPage/importData": <ImportDataInfo />,
      "/indexPage/sispaymentTerms": <PaymentTermsInfo />,
      "/indexPage/productionReport": <ProductionReport />,
      "/indexPage/productionMainPlan": <ProductionMainPlan />,
      "/indexPage/productionPlanInfo": <ProductionPlanInfo />,
      "/indexPage/productionPlanOutside": <ProductionPlanOutside />,
      "/indexPage/productionSchedule": <ProductionSchedule />,
      "/indexPage/productionScheduleTree": <ProductionScheduleTree />,
      "/indexPage/auditInformation": <AuditInformation />,
      "/indexPage/mailMsg": <SysMsgInfo />,
      "/indexPage/printlabel": <PrintLabel />,
      "/indexPage/monthEndingClosing": <MonthEndingClosing />,
      "/indexPage/quotation": <Quotation />,
      "/indexPage/quotationPack": <QuotationPack />,
      "/indexPage/quotationPackTableTree": <QuotationPackTableTree />,
      "/indexPage/unifiedPlanning": <ProductionUnifiedPlanning />,
      "/indexPage/productionPlanChangeMachine": <ProductionPlanChangeMachine />,
      "/indexPage/commonBillDeliver": <CommonBillDeliver />,
      "/indexPage/commonSubBill": <CommonSubBill />,
      "/indexPage/commonNewTabBill": <CommonNewTabBill />,
      "/indexPage/commonCostomTabBill": <CommonCostomTabBill />,
      "/indexPage/commonNewListBill": <CommonNewListBill />,
      "/indexPage/commonGroupBill": <CommonGroupBill />,
      "/indexPage/printPdf": <PrintPdf />,
      "/indexPage/feedback": <Feedback />,
    };
    const content = routeList[pane.route] || <IndexCenter />;

    if (pane.paneType) {
      paneType = (
        <span>
          <LegacyIcon type={pane.paneType} />
          {pane.title}
        </span>
      );
    } else {
      paneType = <span>{pane.title}</span>;
    }
    return (
      <TabPane tab={paneType} closable={pane.paneType !== "home"} disabled={bRecordFlagDisabled} key={pane.key} className={styles.tabPane}>
        {content}
      </TabPane>
    );
  });
  const totalProps = {
    tabpanes,
    app,
    onSaveCurrentPane: saveCurrentPane,
    onRemove: removePane,
  };

  const handleSendSocketMessage = (flag, showType, sId, sendTo, msgInfo, param) => {
    const { token } = app;
    const sendws = handleSendWebSocketMsg;
    if (isNotEmptyObject(token)) {
      if (app.webSocket !== null && app.webSocket.readyState === WebSocket.OPEN) {
        sendws(flag, showType, msgInfo, sId, sendTo, param);
      } else {
        dispatch({ type: "app/createWebSocket", payload: { reStart: true, dispatch } });
        setTimeout(() => {
          sendws(flag, showType, msgInfo, sId, sendTo, param);
        }, 30000);
      }
    }
  };

  const handleSendWebSocketMsg = (flag, showType, msgInfo, sId, sendTo, param) => {
    const { webSocket, userinfo, currentPane } = app;
    const { key } = currentPane;
    sendWebSocketMessage(webSocket, key, flag, showType, userinfo.sId, msgInfo, sId, sendTo, param);
  };

  function saveCurrentPane(currentPane) {
    dispatch({ type: "app/saveCurrentPane", payload: { currentPane } });
  }

  const clearWebSocketMsg = i => {
    const { userinfo } = app;
    const { copyTo } = i;
    if (isNotEmptyObject(copyTo)) {
      const { slaveData, srcFormRoute, copyOtherData, masterData, copyToDataSid } = copyTo;
      const sIdArray = [...(copyToDataSid || [])];

      if (!i?.checkedId) {
        if (isNotEmptyObject(srcFormRoute) && srcFormRoute.includes("materialRequirementsPlanning")) {
          /* 物料需求计划用sWorkOrderMaterialId作为唯一键 */
          if (isNotEmptyArr(copyOtherData) && copyOtherData[0]?.name === "detail" && isNotEmptyArr(copyOtherData[0]?.data)) {
            const slaveDetailData = copyOtherData[0].data;
            slaveDetailData.forEach(item => {
              const redisKey = item.sWorkOrderMaterialId;
              sIdArray.push(redisKey);
            });
          } else {
            /* 变更单、采购申请单 */
            slaveData.forEach(item => {
              const redisKey = item.sWorkOrderMaterialId;
              sIdArray.push(redisKey);
            });
          }
        }
      }

      if (isNotEmptyObject(masterData) && isNotEmptyObject(masterData.sSrcSlaveId)) {
        sIdArray.push(masterData.sSrcSlaveId);
      }

      if (Array.isArray(slaveData)) {
        slaveData.forEach(item => {
          const redisKey = item.sSlaveId;
          sIdArray.push(redisKey);
        });
      }

      const sId = [...new Set(sIdArray)].filter(Boolean).toString();
      handleSendSocketMessage("copyfinish", "noAction", sId, userinfo.sId, null, null);
    }
    handleSendSocketMessage("release", "noAction", i?.checkedId || "", userinfo.sId, null, null);
    handleSendSocketMessage("release", "noAction", i?.formId || "", userinfo.sId, null, null);
  };

  function removePane(changePanes, currentPane, removePane) {
    const removeData = Array.isArray(removePane) ? removePane.filter(Boolean) : [];
    if (removePane && removePane.length === 1 && removePane[0] && removePane[0].fromKey) {
      const currentPaneNew = changePanes.find(item => item.key === removePane[0].fromKey);
      if (currentPaneNew) {
        currentPane = currentPaneNew;
      }
    }
    if (removePane && removePane[0]) {
      const isProductionScheduleTree = removePane[0].route.indexOf("systemPermission") > -1 || removePane[0].route.indexOf("production") > -1;
      if (isProductionScheduleTree) {
        removeData.forEach(i => {
          clearWebSocketMsg(i);
        });
        dispatch({ type: "app/removePane", payload: { changePanes, currentPane } });
        return;
      }
    }
    if (app.diffMap && removePane[0] && app.diffMap.get(removePane[0].key)) {
      const contentStr =  commonFunc.showMessage(app.commonConst, 'isLeave') || '内容未保存，是否离开？';/* 内容未保存，是否离开？ */
      const BtnSure = commonFunc.showMessage(app.commonConst, 'BtnSure') || '确认';/* 按钮确认 */
      const BtnCancel = commonFunc.showMessage(app.commonConst, 'BtnCancel') || '取消';/* 按钮取消 */
      confirm({
        icon: <ExclamationCircleOutlined />,
        content: contentStr,
        onOk() {
          removeData.forEach(i => {
            clearWebSocketMsg(i);
          });
          dispatch({ type: "app/removePane", payload: { changePanes, currentPane } });
        },
        onCancel() {
          console.log("取消关闭");
        },
        okText:BtnSure,
        cancelText:BtnCancel
      });
    } else {
      removeData.forEach(i => {
        clearWebSocketMsg(i);
      });
      dispatch({ type: "app/removePane", payload: { changePanes, currentPane } });
    }
  }
  return (
    <div style={{ height: "100%" }}>
      <TabComponent {...totalProps} />
    </div>
  );
}

export default connect(({ app }) => ({ app }))(Tab);
