import React, {useState, useEffect, useRef} from 'react';
import styles from './styles.less';
import {Modal, Button, Icon, message} from 'antd';
import ShowItem, {dragEventList} from './ShowItem';
import {apiRequest} from "../../utils/request";
import {getContainer} from "../../utils/utils";

let fakeFileInfo = {
  path: '/u/202112/22111913hyia.png',
  name: '摇摇后摇',
};


export default function PictureSignature({
                                           json,
                                           disabled,
                                           basicUrl,
                                           onChangeFile,
                                           // fileInfo,
                                           ...others
                                         }) {
  let imageRef = useRef();
  const [fileInfo, setFileInfo] = useState(others?.fileInfo);
  const [openEdit, setOpenEdit] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [otherProps, setOtherProps] = useState({});
  const [imageInfo, setImageInfo] = useState({
    width: 100,
    height: 100,
  });
  const changeShowModal = () => {
    setShowModal(!showModal);
  };
  // console.log(json);

  useEffect(() => {
    if (json.otherProps) {
      try {
        let func = new Function(json.otherProps);
        let otherPropsX = func();
        setOtherProps(otherPropsX);
        dragEventList(setOtherProps, otherPropsX);
        let image = new Image(); //新建一个img标签（还没嵌入DOM节点)
        image.src = basicUrl + fileInfo?.path;
        image.onload = () => {
          setImageInfo({
            width: image.width,
            height: image.height,
          });
        };
        // console.log(otherPropsX);
      } catch (e) {
        console.log('签章组件 其余配置项出错,没有返回一个正确的值');
        return false;
      }
    }
  }, [json.otherProps]);

  const {ModalProps, signConfig, footerButtons, originButtons} = otherProps;

  const handleClickButton = (clickType) => {
    switch (clickType) {
      case 'startEdit':
        setOpenEdit(true);
        break;
      case 'confirm':
        onChangeFile({...fileInfo});
        changeShowModal();
        break;
      case 'save':
        apiRequest('/ImageLibApi/merge', {
          background: fileInfo?.path,
          content: JSON.stringify({
            objs: otherProps.signConfig,
          }),
        }).then((res) => {
          if (res && res.path) {
            message.success('操作成功');
            let newPath = res.path;
            fileInfo.originPath = fileInfo.path;
            fileInfo.path = newPath;
            setFileInfo({...fileInfo});
            setOpenEdit(false);
          }
        })
        break;
      case 'restore':
        if (fileInfo.originPath) {
          fileInfo.path = fileInfo.originPath;
          setFileInfo({...fileInfo});
          setOpenEdit(false);
        }
        break;
      default:
        return true;
    }
  }

  const Footer = () => {
    if (disabled) {
      return null;
    }
    if (openEdit) {
      return footerButtons.map(g => {
        return (
          <Button type={g.type}
                  key={g.key}
                  onClick={() => {
                    handleClickButton(g.clickType)
                  }}
          >
            {g.name}
          </Button>
        );
      });
    } else {
      return originButtons.map(g => {
        return (
          <Button type={g.type}
                  key={g.key}
                  onClick={() => {
                    handleClickButton(g.clickType)
                  }}
          >
            {g.name}
          </Button>
        );
      });
    }
  };
  if (!fileInfo) {
    return null;
  }

  return (
    <div className={styles.outSideDiv} ref={imageRef}
    >
      {fileInfo && fileInfo?.path && (
        <img
          className={styles.onePic}
          src={basicUrl + fileInfo?.path}
          alt={fileInfo.name}
          onClick={changeShowModal}
        />
      )}
      {showModal && (
        <Modal
          visible={true}
          destroyOnClose={true}
          maskClosable={false}
          onCancel={changeShowModal}
          // getContainer={() => {getContainer(imageRef.current)}}
          getContainer={false}
          className={styles.ModalClass}
          footer={<Footer/>}
          title={'图片签章'}
          width={'90vw'}
          bodyStyle={{
            minHeight: '800px',
            overflow: 'auto',
            padding: '20px',
            maxWidth: '99%',
            maxHeight: '99%',
          }}
          {...ModalProps}
        >
          <div className={styles.modalParentDiv}>
            {openEdit && ( // 开启签章功能
              <div
                className={styles.modalDiv}
                style={{
                  backgroundImage: `url(${basicUrl + fileInfo?.path})`,
                  width: imageInfo.width,
                  height: imageInfo.height,
                }}
                alt={'拖拽区域'}
                draggable={false}
                id={'dropZone'}
              >
                {Array.isArray(signConfig) &&
                signConfig.map(g => {
                  return (
                    <div
                      key={g.key}
                      data-mes={g.key}
                      draggable={false}
                      className={styles.oneSetItem}
                      style={{
                        top: g.y,
                        left: g.x,
                      }}
                    >
                      <div className={styles.draggableIcon} draggable={true}>
                        <Icon type="edit"/>
                      </div>
                      <ShowItem {...g}
                                basicUrl={basicUrl}
                      />
                    </div>
                  );
                })}
              </div>
            )}
            {!openEdit && ( // 不开启签章功能 只是预览图片
              <div className={styles.readOnlyImage}>
                <img
                  src={basicUrl + fileInfo?.path}
                  alt={fileInfo.name}
                />
              </div>
            )}
          </div>
        </Modal>
      )}
    </div>
  );
}

export function SignArray(props){
  const {value, onChange, basicUrl, json,  } = props;
  // console.log(props);
  let files = value?.files || [];
  const onChangeFile = (newFielInfo) => {
    for(let item of files){
      if((item.path || item.originPath) === newFielInfo.originPath){
        item = newFielInfo;
      }
    }
    value.files = files;
    onChange({files});
  }
  return <div>
    {
      files.map((g) => {
        return <PictureSignature json={json}
                                 basicUrl={basicUrl}
                                 fileInfo={g}
                                 onChangeFile={onChangeFile}

        />
      })
    }
  </div>
}
