import React, { useEffect, useReducer, useRef, useState } from "react";
import { GatewayOutlined } from "@easyv/react-icons";
import { ConfigProvider, Upload } from "antd";
import { Modal } from "../../../../src";
import { Button } from "../index";
import styles from "./index.less";
import Lines from "./Lines";

const NineImg = ({ ulAfter, url, onChange, config, upControl }) => {
  const [nineShow, setNineShow] = useState(false);
  const vert = [(config.top * 100).toString(), (config.bottom * 100).toString()];
  const horz = [(config.left * 100).toString(), (config.right * 100).toString()];
  const [vertical, setVertical] = useState(!isNaN(config.top) ? horz : ["37", "58.5"]);
  const [horizontal, setHorizontal] = useState(!isNaN(config.left) ? vert : ["33", "59"]);
  const [height, setHeight] = useState();
  const [width, setWidth] = useState();
  const containerRef = useRef(null);

  const handleClick = () => {
    setNineShow(true);
  };

  useEffect(() => {
    dispatch({
      type: "reset",
      value: [
        config.top ? (config.top * 100).toString() : "37",
        config.right ? (config.right * 100).toString() : "59",
        config.bottom ? (config.bottom * 100).toString() : "58.5",
        config.left ? (config.left * 100).toString() : "33",
      ],
    });
  }, [url]);

  const handleClear = () => {
    dispatch({
      type: "reset",
      value: [
        config.top ? (config.top * 100).toString() : "37",
        config.right ? (config.right * 100).toString() : "59",
        config.bottom ? (config.bottom * 100).toString() : "58.5",
        config.left ? (config.left * 100).toString() : "33",
      ],
    });
    setNineShow(false);
  };

  const handleOk = () => {
    setNineShow(false);
    const result = {
      url: ulAfter,
      left: +((vertical[0] < vertical[1] ? vertical[0] : vertical[1]) / 100).toFixed(3),
      top: +((horizontal[0] < horizontal[1] ? horizontal[0] : horizontal[1]) / 100).toFixed(3),
      right: +((vertical[0] > vertical[1] ? vertical[0] : vertical[1]) / 100).toFixed(3),
      bottom: +((horizontal[0] > horizontal[1] ? horizontal[0] : horizontal[1]) / 100).toFixed(3),
    };
    onChange(result);
  };

  const scaleRef = useRef([1, 1]);

  useEffect(() => {
    const img = new Image();
    img.src = url;

    img.onload = function () {
      setHeight(img.height);
      setWidth(img.width);
    };
  }, [url]);

  const [states, dispatch] = useReducer(
    (state, action) => {
      const { type, value } = action;
      if (type === "reset") {
        return value;
      } else if (type === "update") {
        const direction = action.direction;
        let values = [state[value], state[(value + 2) % 4]];
        values = values[0] > values[1] ? [values[1], values[0]] : values;
        if (direction === "vertical") {
          setVertical(values);
        } else {
          setHorizontal(values);
        }
        return state;
      } else {
        let preValue = +state[type];
        if (type === 0 || type === 2) {
          preValue = (
            (((preValue * height) / 100 + value * scaleRef.current[1]) / height) *
            100
          ).toFixed(3);
        } else {
          preValue = (
            (((preValue * width) / 100 + value * scaleRef.current[0]) / width) *
            100
          ).toFixed(3);
        }
        return [
          ...state.slice(0, type),
          Math.min(Math.max(preValue, 0), 100),
          ...state.slice(type + 1),
        ];
      }
    },
    [horizontal[0], vertical[1], horizontal[1], vertical[0]],
  );

  return (
    <div>
      <GatewayOutlined
        title="点9图"
        onClick={handleClick}
        style={{ cursor: "pointer" }}
        className={styles.nineImg}
      ></GatewayOutlined>
      {nineShow && (
        <Modal
          centered={true}
          wrapClassName={styles.moContainer}
          title="上传点9切图"
          visible={nineShow}
          onCancel={handleClear}
          footer={null}
          className={styles.modal}
        >
          <div className={styles.uplodNine} ref={containerRef}>
            <div className={styles.upConter}>
              <img
                style={{ width: "100%", height: "100%", objectFit: "contain" }}
                src={url}
                onDragStart={(e) => {
                  e.preventDefault();
                }}
              />
              <Lines
                direction="vertical"
                i={0}
                values={[states[3], states[1]]}
                dispatch={dispatch}
                containerRef={containerRef}
                imgDimensions={{ width, height }}
              ></Lines>
              <Lines
                direction="vertical"
                i={1}
                values={[states[3], states[1]]}
                dispatch={dispatch}
                containerRef={containerRef}
                imgDimensions={{ width, height }}
              ></Lines>
              <Lines
                direction="horizontal"
                i={0}
                values={[states[0], states[2]]}
                dispatch={dispatch}
                containerRef={containerRef}
                imgDimensions={{ width, height }}
              ></Lines>
              <Lines
                direction="horizontal"
                i={1}
                values={[states[0], states[2]]}
                dispatch={dispatch}
                containerRef={containerRef}
                imgDimensions={{ width, height }}
              ></Lines>
            </div>
            <div style={{ position: "absolute", bottom: "-50px", right: "0px" }}>
              <Upload
                accept={upControl.accept}
                maxSize={upControl.maxSize}
                showUploadList={false}
                withCredentials={true}
                customRequest={upControl.customRequest}
                disabled={upControl.disabled}
              >
                <ConfigProvider autoInsertSpaceInButton={false}>
                  <Button
                    type="primary"
                    style={{
                      borderRadius: "4px",
                      color: "rgba(255, 255, 255, 1)",
                      backgroundColor: "rgba(255, 255, 255, 0.12)",
                      borderColor: "transparent",
                    }}
                    ghost
                  >
                    重新上传
                  </Button>
                </ConfigProvider>
              </Upload>

              <ConfigProvider autoInsertSpaceInButton={false}>
                <Button
                  type="primary"
                  style={{ borderRadius: "4px", marginLeft: "10px" }}
                  onClick={handleOk}
                >
                  确定
                </Button>
              </ConfigProvider>
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
};

export default NineImg;
