/* eslint-disable */
import React, { useRef, useState, useEffect } from "react";
import { Tabs, Button, message } from "antd-v4";
import { CompressOutlined, ExpandOutlined } from "@ant-design/icons";
import * as commonUtils from "@/utils/utils";
import * as commonFunc from "@/components/Common/commonFunc";
import * as commonBusiness from "@/components/Common/commonBusiness";
import * as commonServices from "@/services/services";
import CommonBase from "@/components/Common/CommonBase";
import AntdDraggableModal from "@/components/Common/AntdDraggableModal";
import CommonViewTable from "@/components/Common/CommonViewTable";
import StaticEditTable from "@/components/Common/CommonTable";
import jsPreviewPdf from "@js-preview/pdf";
import commonConfig from "@/utils/config";

import styles from "./index.less";

const MakeUpPDFEvent = props => {
  const addState = {};

  const { formData = [], selectData = [], masterData, makeUpPDFRecord = {} } = props;
  const [activeKey, setActiveKey] = useState("100");
  useEffect(
    () => {
      if (!formData.length) return;

      const getInitData = async () => {
        const [masterConfig, slaveConfig] = formData;
        const slaveColumn = commonFunc.getHeaderConfig(slaveConfig);

        const { sId, sMakeUpId = sId } = makeUpPDFRecord;
        let resultData = {};
        let masterDefaultData = {};
        if (sMakeUpId) {
          resultData = await props.handleGetDataOne({ name: "master", configData: masterConfig, condition: { sId: sMakeUpId }, isWait: true });
          const sParentId = resultData?.masterData?.sId;
          resultData = {
            ...resultData,
            ...(await props.handleGetDataSet({
              name: "slave",
              configData: slaveConfig,
              condition: { sSqlCondition: { sParentId } },
              clearSelectData: true,
              isWait: true,
            })),
          };
        } else {
          const defaultData = commonFunc.getDefaultData(masterConfig);
          const { sPageMaterialsId, sPageMaterialsName, sPageMaterialsNo } = selectData[0];
          masterDefaultData = {
            ...defaultData,
            dTimes: selectData.length * 20,
            sPageMaterialsId,
            sPageMaterialsName,
            sPageMaterialsNo,
          };
        }

        props.onSaveState({
          masterConfig,
          masterData: { handleType: "add", ...commonFunc.getDefaultData(masterConfig), ...masterDefaultData },
          // masterData: { sId: commonUtils.createSid(), handleType: "add", ...commonFunc.getDefaultData(masterConfig) },
          slaveConfig,
          slaveColumn,
          slaveData: selectData,
          ...resultData,
        });
      };

      getInitData();
    },
    [formData.length]
  );
  const handleResult = async (url, body) => {
    const { app } = props;
    let { masterData } = props;
    const dataReturn = (await commonServices.postValueService(app.token, body, url)).data;
    if (dataReturn.code === 1) {
      /*   成功   */
      const [masterNewData] = dataReturn.dataset.rows[0].dataSet;
      masterData = { ...masterData, ...masterNewData };
      if (commonUtils.isNotEmptyObject(masterData)) {
        props.onSaveState({
          masterData,
        });
      }
    } else {
      /*   失败   */
      message.error(dataReturn.msg);
      return false;
    }
  };
  /* 生成拼版任务 */
  addState.onSend = () => {
    props.onSaveState({ bRefreshTable: true });
    setActiveKey("200");
    setMakeUpProcessList([]);
    const { app, masterData, slaveData } = props;
    const { userinfo } = app;
    const url = `${commonConfig.server_host}makeup/makeupcreate`;
    const body = {
      ...userinfo,
      sUserId: userinfo.sId,
      sMakePerson: userinfo.sUserName,
      masterData: [masterData],
      slaveData,
    };
    handleResult(url, body);
    // commonServices.postValueService(app.token, body, url);
  };
  /* 暂停 */
  addState.onStop = () => {
    setActiveKey("200");
    const { app, masterData, slaveData } = props;
    const { userinfo } = app;
    const url = `${commonConfig.server_host}makeup/makeupstop`;
    const body = {
      ...userinfo,
      sUserId: userinfo.sId,
      sMakePerson: userinfo.sUserName,
      sBillNo: commonUtils.isNotEmptyObject(masterData) ? masterData.sBillNo : "",
      sId: commonUtils.isNotEmptyObject(masterData) ? masterData.sId : "",
      sOrderSlaveId: slaveData[0].sOrderSlaveId,
    };
    handleResult(url, body);
  };
  /* 生产工单 */
  addState.onCreateWorkOrder = () => {
    setActiveKey("200");
    const { app, masterData, slaveData } = props;
    const { userinfo } = app;
    let sId = masterData?.sId;
    if (commonUtils.isEmptyObject(sId)) {
      message.warn("拼版还未完成，请等待...");
      return;
    }
    const url = `${commonConfig.server_host}makeup/makeuptowork`;
    const body = {
      ...userinfo,
      sUserId: userinfo.sId,
      sMakePerson: userinfo.sUserName,
      sBillNo: commonUtils.isNotEmptyObject(masterData) ? masterData.sBillNo : "",
      sId,
      sOrderSlaveId: slaveData[0].sOrderSlaveId,
    };
    handleResult(url, body);
  };
  const [makeUpProcessList, setMakeUpProcessList] = useState([]);
  const [makeUpData, setMakeUpData] = useState({});
  const [slaveDataNew, setSlaveDataNew] = useState([]);
  // 获取ws消息
  useEffect(() => {
    window.tempWsAction = ({ data } = {}) => {
      const { msg, action } = commonUtils.convertStrToObj(data);
      console.log("=====data", data);
      if (action === "showMakeUpProcess") {
        setMakeUpProcessList(pre => [...pre, msg]);
      } else if (action === "showMakeUpView") {
        setMakeUpData(pre => ({ ...pre, sViewPdf: msg }));
      } else if (action === "sendMakeUpData") {
        setMakeUpData(pre => ({ ...pre, ...msg }));
      } else if (action === "sendMakeUpSlaveData") {
        setSlaveDataNew(msg);
      }
    };

    return () => {
      window.tempWsAction = null;
    };
  }, []);

  useEffect(
    () => {
      props.onSaveState({
        masterData: { ...masterData, ...makeUpData },
      });
    },
    [makeUpData]
  );

  useEffect(
    () => {
      if (!slaveDataNew.length) return;
      const slaveData = props.slaveData.map(item => {
        const extraData = slaveDataNew.find(i => i.sOrderSlaveId === item.sOrderSlaveId) || {};
        return {
          ...item,
          ...extraData,
        };
      });
      props.onSaveState({ slaveData });
    },
    [slaveDataNew]
  );

  return {
    ...props,
    ...addState,
    activeKey,
    setActiveKey,
    makeUpProcessList,
  };
};
const MakeUpPDF = baseProps => {
  const { pdfMakeUpVisible } = baseProps;
  if (!pdfMakeUpVisible) return "";

  const props = MakeUpPDFEvent(baseProps);
  const { onCancel, onOk, title, app, masterConfig, masterData = {}, bFullScreen } = props;
  if (!masterConfig) return "";

  const ableConfigs = masterConfig.gdsconfigformslave.filter(item => item.sName && item.bVisible && !item.sControlName);

  const viewProps = {
    ...props,
    viewConfigs: ableConfigs,
    tableConfig: masterConfig,
    iColValueView: 24,
    viewRow: masterData,
    tableName: "master",
    onDataChange: props.onChange,
    onViewClick: (...args) => {
      props.onViewClick(...args);
      props.onCancel();
    },
  };

  const tabsConfig = masterConfig.gdsconfigformslave.filter(item => item.sName && item.bVisible && item.sControlName);
  const tabOrderInfomation = commonFunc.showLocalMessage(props, "tabOrderInfomation", "订单信息");
  const tabPlatemakingProgress = commonFunc.showLocalMessage(props, "tabPlatemakingProgress", "拼版进度");

  return (
    <AntdDraggableModal
      width="100%"
      height="calc(100vh - 50px)"
      title={title}
      visible={pdfMakeUpVisible}
      onCancel={onCancel.bind(this, props.bRefreshTable)}
      onOk={onOk}
      bodyStyle={{
        height: "calc(100vh - 105px)",
        overflowY: "auto",
        display: "flex",
        flexDirection: "column",
      }}
      style={{
        top: 50,
      }}
      footer={[]}
    >
      <div className={`searchMainForm ${styles.viewTable} ${bFullScreen ? styles.viewTableHide : ""}`}>
        <CommonViewTable {...viewProps} />
      </div>
      <Tabs
        type="card"
        className={`noXlyTabs ${styles.tabs} ${bFullScreen ? styles.tabsHide : ""}`}
        activeKey={props.activeKey}
        onChange={props.setActiveKey}
        tabBarExtraContent={{
          right: (
            <div className={styles.btns}>
              <Button type="primary" size="large" className={styles.btnSend} onClick={props.onSend}>
                {masterConfig.gdsconfigformslave.find(item => item.sControlName === "BtnSend")?.showName || "发送"}
              </Button>
              <Button type="primary" size="large" className={styles.btnPause} onClick={props.onStop}>
                {masterConfig.gdsconfigformslave.find(item => item.sControlName === "BtnPause")?.showName || "暂停"}
              </Button>
              <Button type="primary" size="large" className={styles.btnPause} onClick={props.onCreateWorkOrder}>
                {masterConfig.gdsconfigformslave.find(item => item.sControlName === "BtnCreateWorkOrder")?.showName || "生成工单"}
              </Button>
            </div>
          ),
        }}
        items={[
          { label: tabOrderInfomation, key: "100", children: <SlaveComponent {...props} /> },
          { label: tabPlatemakingProgress, key: "200", children: <ProcessComponent {...props} /> },
          ...tabsConfig.map((config, index) => {
            const { showName, sName } = config;
            const fileUrl = masterData[sName];
            const pdfUrl = `${commonConfig.file_host}file/downloadView?savePathStr=${encodeURIComponent(fileUrl)}&sModelsId=100&token=${app.token}`;
            const pdfProps = {
              ...props,
              pdfUrl,
            };

            return {
              label: showName,
              key: index,
              children: (() => {
                if (!fileUrl) {
                  return <div>暂无内容</div>;
                } else if (fileUrl.toLowerCase().endsWith(".pdf")) {
                  return <PDFPreviewerComponent {...pdfProps} />;
                } else if (fileUrl.toLowerCase().endsWith(".svg")) {
                  return <img src={pdfUrl} alt="" style={{ width: "100%", height: "100%" }} />;
                }
              })(),
            };
          }),
        ]}
      />
    </AntdDraggableModal>
  );
};

const PDFPreviewerComponent = props => {
  const { pdfUrl, bFullScreen } = props;

  const handleSwitchFullScreen = () => {
    props.onSaveState({ bFullScreen: !bFullScreen });
  };

  return (
    <div style={{ width: "100%", height: "100%", position: "relative" }}>
      <Button
        className={styles.fullScreen}
        type="primary"
        size="large"
        icon={bFullScreen ? <CompressOutlined /> : <ExpandOutlined />}
        onClick={handleSwitchFullScreen}
      />
      <iframe src={pdfUrl} style={{ width: "100%", height: "100%" }} frameBorder="0" />
    </div>
  );
};

const SlaveComponent = props => {
  const { masterData = {}, slaveData = [] } = props;
  const tableRef = useRef(null);
  const [tableHeight, setTableHeight] = useState("100px");

  useEffect(() => {
    const { height } = tableRef.current.parentNode.getBoundingClientRect();
    setTableHeight(`${height - 40}px`);
  }, []);

  const slaveDataOne = slaveData[0] || {};
  const { sPageMaterialsId, sPageMaterialsName, sPageMaterialsNo } = masterData;
  // 监听主表纸张变化
  useEffect(
    () => {
      if (sPageMaterialsId && sPageMaterialsId !== slaveDataOne.sPageMaterialsId) {
        props.onSaveState({
          slaveData: slaveData.map(item => ({
            ...item,
            sPageMaterialsId,
            sPageMaterialsName,
            sPageMaterialsNo,
            handleType: item.handleType || "update",
          })),
        });
      }
    },
    [sPageMaterialsId]
  );

  const slaveTableProps = {
    ...commonBusiness.getTableTypes("slave", props),
    tableProps: {
      rowSelection: null,
    },
    fixedHeight: tableHeight,
  };

  return (
    <div className="xly-bill-list" style={{ height: "100%", width: "100%", padding: 0 }} ref={tableRef}>
      <StaticEditTable {...slaveTableProps} />
    </div>
  );
};

const ProcessComponent = props => {
  const { app, makeUpProcessList = [], masterData = {} } = props;
  const { sViewPdf } = masterData;
  const imgUrl = sViewPdf
    ? `${commonConfig.file_host}file/downloadView?savePathStr=${encodeURIComponent(sViewPdf)}&sModelsId=100&token=${app.token}`
    : "";

  const processRef = useRef(null);
  const [processHeight, setProcessHeight] = useState("100%");

  useEffect(() => {
    const { height } = processRef.current.parentNode.getBoundingClientRect();
    setProcessHeight(`${height}px`);
  }, []);

  const processContentRef = useRef(null);
  useEffect(
    () => {
      if (!processContentRef.current) return;
      processContentRef.current.scrollTop = 999999999;
    },
    [makeUpProcessList.length]
  );

  return (
    <div className={styles.process} ref={processRef} style={{ height: processHeight }}>
      {processHeight !== "100%" && (
        <>
          <div className={styles.processContent} ref={processContentRef}>
            {makeUpProcessList.map(item => (
              <div>{item}</div>
            ))}
          </div>
          <div className={styles.processImg}>
            <img src={imgUrl} alt="" />
          </div>
        </>
      )}
    </div>
  );
};

export default CommonBase(MakeUpPDF);
