import React, { useEffect, useState } from "react";
import { Icon } from "easy-design";
import { FormGroup, FormItem } from "layout";
import { NumberInput } from "../Number";

const { Col } = FormGroup;

const defaultValue = [
  {
    config: {
      suffix: "px",
    },
    displayName: "宽度",
    name: "width",
    type: "number",
    value: 45,
  },
  {
    config: {
      suffix: "px",
    },
    displayName: "高度",
    name: "height",
    type: "number",
    value: 45,
  },
];

export default function EasyImgSize(props) {
  const { lock, path, onChange, value, showLabel } = props;
  const widthNumber = value.find((item) => item.name === "width") ?? defaultValue[0];
  const heightNumber = value.find((item) => item.name === "height") ?? defaultValue[1];
  const handleChange = (path) => {
    return (updateValue) => {
      const key = path[path.length - 1];
      let updated = [{ path, value: Math.floor(updateValue) }];
      if (key === "width" || key === "height") {
        if (lock) {
          const ratio = widthNumber.value / heightNumber.value;
          const anotherUpdateKey = key === "width" ? "height" : "width";

          let anotherUpdateValue =
            anotherUpdateKey === "width"
              ? Math.floor(updateValue * ratio)
              : Math.floor(updateValue / ratio);

          updated.push({
            path: path.slice(0, path.length - 1).concat(anotherUpdateKey),
            value: anotherUpdateValue,
          });
        }
      }

      onChange(updated);
    };
  };

  return (
    <FormGroup>
      <Col span={11}>
        <NumberInput
          label={showLabel ? "宽度" : ""}
          min={1}
          value={widthNumber.value}
          suffix={widthNumber.config.suffix}
          onBlur={handleChange(path.concat(["width"]))}
          onDragEnd={handleChange(path.concat(["width"]))}
        />
      </Col>
      <Col span={2} style={{ paddingLeft: 0, paddingRight: 0, cursor: "pointer", marginLeft: -1 }}>
        <Icon
          type={lock ? "lock_on" : "lock_off"}
          style={{ fontSize: 20 }}
          onClick={() => onChange({ path: path, value: !lock, field: "lock" })}
        />
      </Col>
      <Col span={11}>
        <NumberInput
          label={showLabel ? "高度" : ""}
          min={1}
          value={heightNumber.value}
          suffix={heightNumber.config.suffix}
          onBlur={handleChange(path.concat(["height"]))}
          onDragEnd={handleChange(path.concat(["height"]))}
        />
      </Col>
    </FormGroup>
  );
}
