/* eslint-disable */
import React, { useState, useEffect } from "react";
import {
  Button,
  Upload,
  message,
  Progress,
  Modal,
  notification,
  Spin
} from "antd-v4";
import { UploadOutlined } from "@ant-design/icons";
import AntdDraggableModal from "@/components/Common/AntdDraggableModal";
import * as commonBusiness from "@/components/Common/commonBusiness";
import * as commonFunc from "@/components/Common/commonFunc";
import StaticEditTable from "@/components/Common/CommonTable";
import * as commonUtils from "@/utils/utils";
import * as commonServices from "@/services/services";
import styles from "./index.less";

const FileImpositionEvent = props => {
  const [mianhuaUrl, setMiaohuaUrl] = useState("");
  const [fileQueryUrl, setFileQueryUrl] = useState("");
  const [uploadFileUrl, setUploadFileUrl] = useState("");

  useEffect(() => {
    fetch("/pinban.json")
      .then(response => response.json())
      .then(data => {
        const { mianhuaUrl, fileQueryUrl, uploadFileUrl } = data;
        setMiaohuaUrl(mianhuaUrl);
        setFileQueryUrl(fileQueryUrl);
        setUploadFileUrl(uploadFileUrl);
      })
      .catch(error => {
        console.error("Error fetching JSON data:", error);
      });

    const { masterData = {} } = props;
    const { sGenerate_files } = masterData;
    const { fileList = [] } = commonUtils.convertStrToObj(sGenerate_files);
    const pinbanData = fileList.map((filename, index) => ({
      sId: index,
      fileType: filename.split(".").pop(),
      sFileName: filename
    }));
    props.onSaveState({
      pinbanData
    });
  }, []);

  const [bCreating, setBCreating] = useState(false);

  return {
    ...props,
    mianhuaUrl,
    fileQueryUrl,
    uploadFileUrl,
    bCreating,
    setBCreating
  };
};

const FileImposition = baseProps => {
  const { visible } = baseProps;
  if (!visible) return "";
  const props = FileImpositionEvent(baseProps);
  const { onCancel, onOk, fileName, bCreating } = props;

  const divProps = {
    action: props.uploadFileUrl,
    onChange: handleUploadChange.bind(this, props),
    accept: "*/*",
    showUploadList: false,
    multiple: true
    // customRequest: async options => {
    //   const { file, onSuccess, onError } = options;
    //   const formData = new FormData();
    //   formData.append("file", file);

    //   formData.append("savePathStr", "24120138_3");
    //   try {
    //     const response = await fetch(
    //       `${commonConfig.file_host}file/uploadMultiMh`,
    //       {
    //         method: "POST",
    //         body: formData
    //       }
    //     );

    //     if (response.ok) {
    //       const result = await response.json();
    //       console.log("=====result", result);
    //     } else {
    //       onError(new Error("文件上传失败"));
    //     }
    //   } catch (error) {
    //     onError(error);
    //   }
    // }
  };

  const sGenerate_files = commonUtils.convertStrToObj(
    props.masterData.sGenerate_files
  );
  const { previewUrl } = sGenerate_files;

  return (
    <AntdDraggableModal
      width={600}
      title="文件拼板"
      visible={visible}
      onCancel={onCancel}
      onOk={onOk}
      bodyStyle={{
        height: 410,
        overflowY: "auto"
      }}
      style={{
        top: 100,
        height: 500
      }}
      footer={[
        <Button
          key="create"
          type="primary"
          style={{ float: "left" }}
          loading={bCreating}
          onClick={() => {
            if (previewUrl) {
              Modal.confirm({
                title: "温馨提示:",
                content: <div>已生成拼板，是否需要合成新拼板？</div>,
                onOk() {
                  handleCreateFile(props);
                }
              });
            } else {
              handleCreateFile(props);
            }
          }}
        >
          合成拼板
        </Button>,
        <Button
          key="preview"
          type="primary"
          style={{ float: "left" }}
          onClick={() => {
            if (!previewUrl) {
              message.info("请先合成拼板！");
              return;
            }

            props.onSaveState({
              pdfFileVisible: true,
              previewUrl: previewUrl,
              previeTitle: "拼板预览"
            });
          }}
        >
          拼板预览
        </Button>,
        <Button key="back" onClick={onCancel}>
          取消
        </Button>,
        <Button
          key="submit"
          type="primary"
          onClick={() => {
            props.onSubmit();
            onCancel();
          }}
        >
          确定
        </Button>
      ]}
    >
      <Upload {...divProps}>
        <Button>
          <UploadOutlined /> 附件上传
        </Button>
        <span style={{ marginLeft: 10, fontSize: 18 }}>{fileName}</span>
      </Upload>
      <div className={styles.content}>
        <FileTable {...props} />
      </div>
      <RreviewModal {...props} />
    </AntdDraggableModal>
  );
};

const handleCreateFile = async props => {
  props.setBCreating(true);
  const { pinbanSelectedRowKeys = [], pinbanData = [] } = props;

  if (!pinbanData.length) {
    message.info("请先上传附件！");
    return;
  }

  let rowKeys = pinbanSelectedRowKeys;

  if (!pinbanSelectedRowKeys.length) {
    const result = await new Promise(resolve => {
      Modal.confirm({
        title: "温馨提示:",
        content: <div>未勾选附件，是否用全部附件合成拼板？</div>,
        okText: "是",
        cancelText: "否",
        onOk() {
          resolve(true);
        },
        onCancel() {
          resolve(false);
        }
      });
    });
    if (!result) {
      props.setBCreating(false);
      return;
    }

    rowKeys = pinbanData.map(item => item.sId);
  }

  const returnData = await commonServices.postValueService(
    "miaohua",
    {
      method: "auth.create_session",
      user_name: "xly",
      user_pass: "1234"
    },
    props.mianhuaUrl
  );

  const { data = {} } = returnData;
  const { session } = data;
  if (!session) {
    handleDealError(props);
    return;
  }

  const files = pinbanData
    .filter(item => rowKeys.includes(item.sId))
    .map(item => item.sFileName);

  const returnData1 = await commonServices.postValueService(
    "miaohua",
    {
      method: "hub.start_from_whitepaper_with_files_and_variables",
      session,
      whitepaper_name: "XLY-SR",
      input_name: "erp-s&r",
      options: {
        variables: {
          OrderID: "20250222001",
          srheight: "957",
          srwidth: "275",
          fcounts: "616,176",
          StyleP: "label"
        },
        files
      }
    },
    props.mianhuaUrl
  );

  const { data: data1 = {} } = returnData1;
  const { workable_id } = data1;
  if (!workable_id) {
    handleDealError(props);
    return;
  }

  notification.open({
    key: "fileCreating",
    placement: "topRight",
    message: "温馨提示",
    description: (
      <div>
        <Spin />
        {" 拼板文件生成中..."}
      </div>
    )
  });

  let times = 0;
  const timer = setInterval(() => {
    times += 1;
    commonServices
      .postValueService("miaohua", { workable_id }, props.fileQueryUrl)
      .then(({ data }) => {
        const { code } = data;
        if (code === 0) {
          props.setBCreating(false);
          const { sGenerate_files: previewUrl } =
            data.data?.dataList?.[0] || {};
          if (previewUrl) {
            const sGenerate_files = commonUtils.convertStrToObj(
              props.masterData.sGenerate_files
            );

            clearInterval(timer);
            notification.open({
              key: "fileCreating",
              placement: "topRight",
              message: "温馨提示",
              description: <div>拼板文件生成完成！</div>,
              duration: 3
            });

            props.onSaveState1({
              masterData: {
                ...props.masterData,
                sGenerate_files: JSON.stringify({
                  ...sGenerate_files,
                  workableId: workable_id,
                  previewUrl
                }),
                handleType: props.masterData.handleType || "update"
              }
            });
          }
        }
      })
      .catch(e => {
        console.log("=====e", e);
      });

    if (times > 100) {
      clearInterval(timer);
      notification.open({
        key: "fileCreating",
        placement: "topRight",
        message: "温馨提示",
        description: <div>拼板文件生成完成！</div>,
        duration: 3
      });
      handleDealError(props);
    }
  }, 5000);
};

const handleDealError = props => {
  message.error("获取数据失败");
  props.setBCreating(false);
};

const handleGetStrokeColor = percent => {
  if (percent < 30) {
    return "#F50";
  } else if (percent >= 30 && percent < 90) {
    return "#FF9900";
  } else {
    return "#87D068";
  }
};

const handleUploadChange = (props, info) => {
  const { file } = info;
  const { status, percent } = file;
  if (status === undefined) return;
  const percentNew = Number(percent.toFixed(2));
  if (["done", "error"].includes(status)) {
    message.open({
      type: status === "done" ? "success" : "error",
      content: status === "done" ? "文件上传成功" : "文件上传失败",
      duration: 3
    });
    if (status === "done") {
      const sPicturePath = file.response.dataset.rows[0].savePathStr;
      const sGenerate_files = commonUtils.convertStrToObj(
        props.masterData.sGenerate_files
      );
      let { fileList = [] } = sGenerate_files;
      fileList = [
        ...fileList,
        ...sPicturePath.split(",").map(item => item.split("/").pop())
      ];
      props.onSaveState1({
        masterData: {
          ...props.masterData,
          sGenerate_files: JSON.stringify({
            ...sGenerate_files,
            fileList
          }),
          handleType: props.masterData.handleType || "update"
        }
      });
    }
  } else {
    message.open({
      key: "xlyupload",
      type: percent === 100 ? "success" : "loading",
      content: (
        <>
          <span>上传进度:</span>
          <span
            style={{
              display: "inline-block",
              width: 200,
              padding: "0 25px 3px 14px"
            }}
          >
            <Progress
              percent={percentNew}
              strokeColor={handleGetStrokeColor(percentNew)}
            />
          </span>
        </>
      ),
      duration: percent === 100 ? 3 : 0
    });
  }
};

const FileTable = props => {
  const pinbanConfig = {};
  pinbanConfig.gdsconfigformslave = [
    {
      bVisible: true,
      sName: "sFileName",
      showName: "附件名称",
      iFitWidth: 400
    },
    {
      bVisible: true,
      sName: "fileType",
      showName: "附件类型"
    }
  ];
  pinbanConfig.bMutiSelect = true;
  pinbanConfig.bisMutiSelect = true;

  const pinbanColumn = commonFunc.getHeaderConfig(pinbanConfig);

  const tableProps = {
    ...commonBusiness.getTableTypes("pinban", {
      ...props,
      pinbanConfig
    }),
    headerColumn: pinbanColumn,
    fixedHeight: 311,
    enabled: false
  };
  return <StaticEditTable {...tableProps} />;
};

const RreviewModal = props => {
  const { pdfFileVisible, previewUrl, previeTitle } = props;

  return (
    <AntdDraggableModal
      title={previeTitle}
      visible={pdfFileVisible}
      width="100%"
      height="calc(100% - 50px)"
      className={styles.pdfModal}
      style={{ top: 0 }}
      footer={null}
      onCancel={() => {
        props.onSaveState({
          pdfFileVisible: false
        });
      }}
    >
      <div
        style={{
          width: "100%",
          height: "calc(100vh - 67px)",
          overflow: "auto"
        }}
      >
        <iframe
          src={previewUrl}
          style={{ width: "100%", height: "100%" }}
          frameBorder="0"
        />
      </div>
    </AntdDraggableModal>
  );
};

export default FileImposition;
