/* eslint-disable */
import React, { useRef, useState, useEffect } from "react";
import styles from "../index.less";
import SvgBox from "../svg";
import { Select, Button, message, Input, Spin } 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";
const DoubleLayerBox = props => {
  const { onCancel, onOk, title, loading, masterConfig, bFullScreen, tableData, options = [] } = props;
  const { slaveData = {}, masterData = {} } = props.state;
  const [boxList, setBoxList] = useState([]);
  const [tableColum, setTableColum] = useState([]); // 盒身类型
  const [tableDataList, setTableDataList] = useState([]); // 盒长
  const [boxBodyList, setBoxBodyList] = useState([]); // 盒身信息
  const [isDefaultValue, setIsDefaultValue] = useState(true); // 是否默认值
  const [topBoxList, setTopBoxList] = useState([]); // 盒身信息
  const [leftBoxList, setLeftBoxList] = useState([]); // 左边
  const [rightBoxList, setRightBoxList] = useState([]);
  // useEffect(() => {
  //   if (tableData && tableData.length) {
  //     const newTableColum = tableData.map(item => {
  //       return {
  //         ...item,
  //         isEditable: true,
  //         isSelect: false,
  //         selectImage: null,
  //         value: "",
  //       };
  //     });
  //     const newList = newTableColum.filter(
  //       item => item.showName.includes("盒长") || item.showName.includes("盒高") || item.showName.includes("盒宽")
  //     );
  //     const newLists = newTableColum.filter(
  //       item =>
  //         !(item.showName.includes("盒长") || item.showName.includes("盒高") || item.showName.includes("盒宽") || item.showName.includes("盒身"))
  //     );
  //     const bodyList = newTableColum.filter(item => item.showName.includes("盒身"));
  //     newLists.forEach(x => {
  //       if (x.showName === "盒型类别") {
  //         x.showName = "盒型名称";
  //       }
  //     });
  //     setTableColum(newLists);
  //     setBoxBodyList(bodyList);
  //     newList.forEach(item => {
  //       let name = "";
  //       if (item.showName === "盒长") {
  //         name = item.showName + "(L)";
  //       } else if (item.showName === "盒宽") {
  //         name = item.showName + "(W)";
  //       } else if (item.showName === "盒高") {
  //         name = item.showName + "(D)";
  //       }
  //       item.sName = name;
  //     });
  //     setTableDataList(newList);
  //   }
  // }, [tableData]);
  const titleList = [
    "左(上)插位组件",
    "上插位组件",
    "右(上)插位组件",
    "左偏移",
    "左插位组件",
    "左(下)插位组件",
    "右偏移",
    "右插位组件",
    "右(下)插位组件",
    "盒型名称",
    "盒身",
    "个数",
    "首盒长(L)",
    "首盒宽(W)",
    "次盒长(L)",
    "次盒宽(W)",
  ];
  const titleList1 = [
    { name: "左(上)插位组件", value: "dZSCW" },
    { name: "上插位组件", value: "dSCW" },
    { name: "右(上)插位组件", value: "dYSCW" },
    { name: "左偏移", value: "dZPY" },
    { name: "左插位组件", value: "dZCW" },
    { name: "左(下)插位组件", value: "dZXCW" },
    { name: "右偏移", value: "dYPY" },
    { name: "右插位组件", value: "dYCW" },
    { name: "右(下)插位组件", value: "dYXCW" },
  ];
  // tableColum.forEach(item => {
  //   titleList.push(item.showName);
  // });
  // boxBodyList.forEach(item => {
  //   titleList.push(item.showName);
  // });
  // tableDataList.forEach(item => {
  //   titleList.push(item.showName);
  // });
  const newBoxList = [];
  // 盒身信息
  titleList.forEach((item, index) => {
    newBoxList.push({
      value: "",
      sName: item,
      isEditable: true,
      isSelect: false,
      selectValue: null,
      selectLabel: "",
      selectImage: null,
      type: null,
      show: true,
      showName: item, // 参数名称
      sAssignFormula: null,
    });
  });
  if (slaveData && slaveData.length) {
    slaveData.forEach((item, index) => {
      const i = titleList1.findIndex(i => {
        return i.value === item.sCode;
      });
      if (i !== -1) {
        const x = newBoxList.findIndex(z => z.sName === titleList1[i].name);
        newBoxList[x].value = item.iValue;
        newBoxList[x].type = item.sTypes;
        newBoxList[x].showName = item.sName;
        newBoxList[x].selectImage = item.sMakeUpPath;
        newBoxList[x].sName = titleList1[i].name;
        newBoxList[x].sAssignFormula = item.sAssignFormula;
        newBoxList[x].bVisible = item.bVisible;
      }
    });
  }
  // 盒身信息
  if (masterData) {
    newBoxList.forEach((item, index) => {
      if (item.sName === "盒身") {
        newBoxList[index].value = masterData.sBoxBody;
        newBoxList[index].selectImage = masterData.sMakeUpPath;
        newBoxList[index].type = masterData.sTypes;
      } else if (item.sName === "盒长") {
        newBoxList[index].value = masterData.dBoxLength;
      } else if (item.sName === "盒宽") {
        newBoxList[index].value = masterData.dBoxWidth;
      } else if (item.sName === "盒高") {
        newBoxList[index].value = masterData.dBoxHeight;
      } else if (item.sName === "盒型名称") {
        newBoxList[index].value = masterData.sName;
      }
    });
  }
  const arraysAreEqual = (arr1, arr2) => {
    if (arr1.length !== arr2.length) return false;
    return arr1.every((item, index) => item.sName === arr2[index].sName);
  };
  // 有数据的时候 盒型设计需要赋值
  useEffect(() => {
    if (newBoxList.length > 0 && !arraysAreEqual(boxList, newBoxList)) {
      setBoxList(newBoxList);
    }
  }, [newBoxList]);
  const getImage = fileName => {
    // const imageUrl = `${commonConfig.file_host}file/download?savePathStr=${fileName}&sModelsId=100&token=${props.token}`;
    const imageUrl = `${commonConfig.file_host}file/download?savePathStr=${fileName}&scale=0.1&sModelsId=100&token=${props.token}`;
    return imageUrl;
  };
  // 下来框
  const renderOptionWithImage = option => {
    return (
      <Select.Option key={option.sId} value={option.sCode} label={option.sName} image={getImage(option.sMakeUpPath)}>
        <div style={{ display: "flex", alignItems: "center" }}>
          {option.sMakeUpPath ? <img src={getImage(option.sMakeUpPath)} style={{ width: 24, height: 24, marginRight: 8 }} /> : ""}
          <span>{option.sName}</span>
        </div>
      </Select.Option>
    );
  };
  const svgBoxProps = {
    ...props,
    boxList,
    showNew: 0,
  };

  useEffect(() => {
    if (!boxList.length) return;
    const slicedArray = boxList.slice(9, 12);
    // 处理盒型部分
    setBoxBodyList(slicedArray);
  }, [boxList]);
  console.log(tableDataList, "boxList");

  return (
    <div className={styles.boxBody}>
      <div className={styles.boxTop}>
        {topBoxList.map((topItem, index) => (
          <div key={index} className={styles.boxFlex} style={{ display: topItem.show ? "block" : "none" }}>
            <div className={styles.boxTitle}>{topItem.sName}</div>
            {topItem?.selectImage ? (
              <img
                src={topItem?.selectImage}
                alt={topItem.value}
                style={{ width: 40, height: 30, marginRight: 8, position: "absolute", left: 20, top: 24, zIndex: 10 }}
              />
            ) : (
              ""
            )}

            <Select
              optionLabelProp="label"
              className="mySelects"
              style={{ width: 180 }}
              defaultValue={options.length ? options[0].value : ""}
              onSelect={(value, option) => handleSelect(value, option, index, 0)}
              onDropdownVisibleChange={async open => {
                if (open) {
                  props.getSqlOptions(index + 1); // 在下拉菜单打开时调用 getSqlOptions
                }
              }}
            >
              {!loading ? options.map(option => renderOptionWithImage(option)) : ""}
            </Select>
            <div className={styles.boxInput}>
              {/* <div className={styles.text}>参数：</div> */}
              <Input
                value={topItem?.showName}
                onChange={e => handleChangeName(e, index)}
                onFocus={e => handleFocus(e, index)}
                onBlur={e => handleBlur(e, index)}
                readOnly={!topItem?.isEditable}
                className={styles.text}
              />
              <Input
                value={topItem?.value}
                onChange={e => handleChange(e, index)}
                onFocus={e => handleFocus(e, index)}
                onBlur={e => handleBlur(e, index)}
                readOnly={!topItem?.isEditable}
                style={{ width: " 80%" }}
              />
            </div>
          </div>
        ))}
      </div>
      <div className={styles.boxLeft}>
        {leftBoxList.map((item, index) => (
          <div key={index + 3} className={styles.boxFlex} style={{ display: item?.show ? "block" : "none" }}>
            <div className={styles.boxTitle}>{titleList[index + 3]}</div>

            <Select
              optionLabelProp="label"
              className="mySelects"
              style={{ width: 180 }}
              defaultValue={options.length ? options[0].value : ""}
              onSelect={(value, option) => handleSelect(value, option, findIndexBySname(item.sName), 0)}
              onDropdownVisibleChange={async open => {
                if (open) {
                  props.getSqlOptions(findIndexBySname(item.sName) + 1); // 在下拉菜单打开时调用 getSqlOptions
                }
              }}
            >
              {!loading ? options.map(option => renderOptionWithImage(option)) : ""}
            </Select>
            <div className={styles.boxInput}>
              {item?.selectImage ? (
                <img
                  src={item?.selectImage}
                  alt={item.value}
                  style={{
                    width: 40,
                    height: 30,
                    marginRight: 8,
                    position: "absolute",
                    left: 20,
                    top: -35,
                    zIndex: 10,
                  }}
                />
              ) : (
                ""
              )}
              <Input
                value={item?.showName}
                onChange={e => handleChangeName(e, findIndexBySname(item.sName))}
                onFocus={e => handleFocus(e, findIndexBySname(item.sName))}
                onBlur={e => handleBlur(e, findIndexBySname(item.sName))}
                readOnly={!item?.isEditable}
                className={styles.text}
              />
              <Input
                value={item?.value}
                onChange={e => handleChange(e, findIndexBySname(item.sName))}
                onFocus={e => handleFocus(e, findIndexBySname(item.sName))}
                onBlur={e => handleBlur(e, findIndexBySname(item.sName))}
                readOnly={!item?.isEditable}
                style={{ width: " 80%" }}
              />
            </div>
          </div>
        ))}
      </div>
      <div className={styles.boxRight}>
        {rightBoxList.map((item, index) => (
          <div key={findIndexBySname(item.sName)} className={styles.boxFlex} style={{ display: item?.show ? "block" : "none" }}>
            <div className={styles.boxTitle}>{titleList[findIndexBySname(item.sName)]}</div>

            <Select
              optionLabelProp="label"
              className="mySelects"
              style={{ width: 180 }}
              defaultValue={options.length ? options[0].value : ""}
              onSelect={(value, option) => handleSelect(value, option, findIndexBySname(item.sName), 0)}
              onDropdownVisibleChange={async open => {
                if (open) {
                  props.getSqlOptions(findIndexBySname(item.sName) + 1); // 在下拉菜单打开时调用 getSqlOptions
                }
              }}
            >
              {!loading ? options.map(option => renderOptionWithImage(option)) : ""}
            </Select>
            <div className={styles.boxInput}>
              {item?.selectImage ? (
                <img
                  src={item?.selectImage}
                  alt={item.value}
                  style={{
                    width: 40,
                    height: 30,
                    marginRight: 8,
                    position: "absolute",
                    left: 20,
                    top: -35,
                    zIndex: 10,
                  }}
                />
              ) : (
                ""
              )}

              <Input
                value={item?.showName}
                onChange={e => handleChangeName(e, findIndexBySname(item.sName))}
                onFocus={e => handleFocus(e, findIndexBySname(item.sName))}
                onBlur={e => handleBlur(e, findIndexBySname(item.sName))}
                readOnly={!item?.isEditable}
                className={styles.text}
              />
              <Input
                value={item?.value}
                onChange={e => handleChange(e, findIndexBySname(item.sName))}
                onFocus={e => handleFocus(e, findIndexBySname(item.sName))}
                onBlur={e => handleBlur(e, findIndexBySname(item.sName))}
                readOnly={!item?.isEditable}
                style={{ width: " 80%" }}
              />
            </div>
          </div>
        ))}
      </div>
      <div className={styles.boxBottom}>
        <div className={styles.svgBox}>
          <SvgBox {...svgBoxProps} />
        </div>
        <div className={styles.content}>
          <div className={styles.content}>
            {boxBodyList && boxBodyList.length
              ? boxBodyList.map((item, index) => {
                  const uniqueIndex = index + 9;
                  return (
                    <div key={uniqueIndex} className={styles.boxFlex}>
                      <div className={styles.boxInput}>
                        <div className={styles.text} style={{ width: "120px" }}>
                          {item.showName}
                        </div>
                        {boxList[uniqueIndex]?.selectImage ? (
                          <img
                            src={boxList[uniqueIndex]?.selectImage}
                            alt={boxList[uniqueIndex].value}
                            style={{ width: 40, height: 30, marginRight: 8, position: "absolute", left: 120, top: 6, zIndex: 10 }}
                          />
                        ) : (
                          ""
                        )}
                        {isDefaultValue ? <div className={styles.defaultValue}>{boxList[uniqueIndex]?.value}</div> : ""}
                        <Select
                          optionLabelProp="label"
                          className="mySelects"
                          style={{ width: "80%" }}
                          defaultValue={boxList[uniqueIndex]?.value}
                          onSelect={(value, option) => handleSelect(value, option, uniqueIndex, 1)}
                          onDropdownVisibleChange={async open => {
                            if (open) {
                              props.getSqlOptions(10); // 盒身
                            }
                          }}
                        >
                          {!loading ? options.map(option => renderOptionWithImage(option)) : ""}
                        </Select>
                      </div>
                    </div>
                  );
                })
              : ""}
          </div>
        </div>
      </div>
    </div>
  );
};
export default DoubleLayerBox;
