import React, {
  useCallback,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import { Modal, Row, Col, Form, Input, Select, message } from "antd";
import { Button } from "../Button";
import { request } from "../utils";

const ModalClient = React.memo((props) => {
  const {
    visible = false,
    title,
    onOk = () => {},
    onCancel = () => {},
    children,
  } = props;
  return (
    <Modal
      className="modalClient"
      destroyOnClose
      visible={visible}
      closable={false}
      footer={null}
      width={536}
      bodyStyle={{ padding: "32px" }}
    >
      <div className="modalClient-header">{title}</div>
      <div className="modalClient-body">{children}</div>
      <div className="modalClient-footer">
        <Button title="确认" size="large" onClick={onOk} />
        <Button
          title="取消"
          type="default"
          size="large"
          ghost
          onClick={onCancel}
        />
      </div>
      <style jsx>{`
        .modalClient-header {
          height: 32px;
          font-size: 28px;
          color: rgb(0 0 0/0.85);
          letter-spacing: 0px;
          line-height: 32px;
          margin-bottom: 42px;
        }
        .modalClient-footer {
          text-align: right;
          padding-top: 32px;
        }
      `}</style>
      <style jsx global>{`
        .modalClient .ant-form-item-label {
          text-align: left;
        }
        .modalClient .ant-form-item-label > label {
          font-size: 24px;
        }
        .modalClient .ant-form-large .ant-form-item-control-input {
          min-height: 56px;
        }
        .modalClient
          .ant-select-single.ant-select-lg:not(.ant-select-customize-input)
          .ant-select-selector::after,
        .modalClient
          .ant-select-single.ant-select-lg:not(.ant-select-customize-input)
          .ant-select-selector
          .ant-select-selection-item,
        .modalClient
          .ant-select-single.ant-select-lg:not(.ant-select-customize-input)
          .ant-select-selector
          .ant-select-selection-placeholder {
          line-height: 56px;
        }
        .modalClient .ant-form-large .ant-form-item-label > label,
        .modalClient
          .ant-select-single.ant-select-lg:not(.ant-select-customize-input)
          .ant-select-selector {
          height: 56px;
        }
        .modalClient .ant-input-lg {
          line-height: 54px;
          padding: 0 11px;
        }
        .modalClient p,
        .modalClient .ant-input-lg,
        .modalClient .ant-select-lg {
          font-size: 24px;
        }
        .modalClient .item-line {
          text-align: center;
          line-height: 56px;
        }
        .modalClient.ant-select-item {
          font-size: 18px;
          line-height: 32px;
        }
      `}</style>
    </Modal>
  );
});

// 设置
export const ModelSetting = React.forwardRef((props, ref) => {
  const {} = props;
  const callbackRef = useRef(() => {});
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);

  const handleCancel = useCallback(() => setVisible(false), []);

  const [equipList, setEquipList] = useState([]);
  const [operationList, setOperationList] = useState([]);
  const [workShopList, setWorkShopList] = useState([]);

  // 查询包装机
  const getEquip = useCallback((gid) => {
    if (gid) {
      request({
        method: "POST",
        url: `${window.config.mesUrl}/mdgeneric/md/bmWorkCenter/getEquipByOperationGid?operationGid=${gid}`,
      }).then(({ data, success } = {}) => {
        if (!success) data = [];
        setEquipList(data);
      });
    }
  }, []);

  // 工序变化
  const onOperationChange = useCallback(
    (code, a, data) => {
      if (!data) data = operationList;
      // console.log("val", key, value, data);
      let {gid: operationGid, name} = data.find((item) => item.code === code) || {};
      getEquip(operationGid);
      form.setFieldsValue({
        operationName: name,
        operationCode: code,
        equipName: undefined,
        equipCode: undefined,
      });
      setEquipList([]);
    },
    [operationList, form, getEquip]
  );

  // 查询工序
  const getOperation = useCallback(
    (gid, callback) => {
      if (gid) {
        request({
          method: "POST",
          url: `${window.config.mesUrl}/mdgeneric/md/bmWorkCenter/getOpByWorkCenter?workCenterGid=${gid}`,
        }).then(({ data, success } = {}) => {
          if (!success) data = [];
          setOperationList(data);
          if (callback) {
            callback(data);
          } else if (data.length) {
            let { name, code } = data[0];
            form.setFieldsValue({
              operationName: name,
              equipName: code,
            });
            onOperationChange(code,undefined, data)
          }
        });
      } else setOperationList([]);
    },
    [onOperationChange]
  );

  // 车间变化
  const onWorkShopChange = useCallback(
    (key = {}) => {
      let { gid: workShopGid, name: value } = workShopList.find(({ code }) => code === key) || {};
      getOperation(workShopGid);
      form.setFieldsValue({
        workCenterCode: key,
        workCenterName: value,
        operationName: undefined,
        operationCode: undefined,
        equipName: undefined,
        equipCode: undefined,
      });
      setOperationList([]);
      setEquipList([]);
    },
    [workShopList, form, getOperation]
  );

  // 查询车间
  const getWorkShop = useCallback((callback) => {
    request({
      method: "POST",
      url: `${window.config.mesUrl}/mdgeneric/md/bmWorkCenter/findAllWithPage`,
      bodys: {
        // removePermission: true,
        page: -1,
        pageSize: -1,
        sorted: "createTime desc",
        filter: "type eq 'workshop'",
      },
    }).then(({ data, success } = {}) => {
      if (!success) data = [];
      setWorkShopList(data);
      callback && callback(data);
    });
  }, []);

  // 设备变化
  const onEquipChange = useCallback(
    (key) => {
      let { name: value} = equipList.find(({ code }) => code === key) || {}
      form.setFieldsValue({
        equipName: value,
        equipCode: key,
      });
    },
    [form, equipList]
  );

  // 初始化
  const init = useCallback(
    (data, callback) => {
      setVisible(true);
      form.resetFields();
      form.setFieldsValue(data);
      callbackRef.current = callback;
      let { workCenterCode, operationCode } = data;
      getWorkShop((res) => {
        if (workCenterCode) {
          let gid = res.find(({ code }) => code === workCenterCode)?.gid;
          getOperation(gid, (res) => {
            if (operationCode) {
              let gid = res.find(({ code }) => code === operationCode)?.gid;
              getEquip(gid);
            }
          });
        }
      });
    },
    [form, getWorkShop, getOperation, getEquip]
  );

  const handleOk = useCallback(() => {
    let formData = form.getFieldValue();
    if (["", null, undefined].includes(formData.workCenterCode))
      return message.error("请完善车间！");
    if (["", null, undefined].includes(formData.equipCode))
      return message.error("请完善包装机！");
    if (["", null, undefined].includes(formData.bagWeight))
      return message.error("请完善包装袋重量！");
    if (["", null, undefined].includes(formData.packSpecs))
      return message.error("请完包装规格！");
    if (["", null, undefined].includes(formData.upperLimit))
      return message.error("请完善上限值！");
    if (["", null, undefined].includes(formData.lowerLimit))
      return message.error("请完善下限值！");
    // console.log("form", formData);
    return new Promise((resolve, reject) => {
      request({
        url: `${window.config.mesUrl}/prodexec/prodexec/packageEquipment/setPackInfo`,
        bodys: formData,
      }).then((res) => {
          handleCancel();
          callbackRef.current();
        })
        .finally(() => {
          resolve();
        });
    });
  }, [handleCancel, form, workShopList, equipList]);

  useImperativeHandle(
    ref,
    () => ({
      show: init,
    }),
    [init]
  );
  return (
    <ModalClient
      visible={visible}
      title="设置"
      onCancel={handleCancel}
      onOk={handleOk}
    >
      <Form
        form={form}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        // onFieldsChange={ onFieldsChange }
        autoComplete="off"
        size="large"
      >
        <Form.Item label="车间" name="workCenterName">
          <Select
            placeholder="选择车间"
            onSelect={onWorkShopChange}
            // labelInValue
          >
            {workShopList.map(({ code, name }) => (
              <Select.Option value={code} key={code} className="modalClient">
                {name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="工序" name="operationName">
          <Select
            placeholder="选择工序"
            onSelect={onOperationChange}
            // labelInValue
          >
            {operationList.map(({ code, name }) => (
              <Select.Option value={code} key={code} className="modalClient">
                {name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="包装机" name="equipName">
          <Select
            placeholder="选择包装机"
            onSelect={onEquipChange}
            // labelInValue
          >
            {equipList.map(({ code, name }) => (
              <Select.Option value={code} key={code} className="modalClient">
                {name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="包装袋重量" name="bagWeight">
          <Input addonAfter="KG" placeholder="填写包装袋重量" />
        </Form.Item>
        <Form.Item label="包装规格" name="packSpecs">
          <Input addonAfter="KG" placeholder="填写包装规格" />
        </Form.Item>
        <Form.Item label="上限-下限">
          <Input.Group>
            <Row gutter={8}>
              <Col span={11}>
                <Form.Item name={"upperLimit"} noStyle>
                  <Input addonAfter="KG" placeholder="上限" />
                </Form.Item>
              </Col>
              <Col span={2}>
                <div className="item-line">-</div>
              </Col>
              <Col span={11}>
                <Form.Item name={"lowerLimit"} noStyle>
                  <Input addonAfter="KG" placeholder="下限" />
                </Form.Item>
              </Col>
            </Row>
          </Input.Group>
        </Form.Item>
      </Form>
    </ModalClient>
  );
});

// 中断
export const ModelBreak = React.forwardRef((props, ref) => {
  const {} = props;
  const callbackRef = useRef(() => {});
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);

  const handleCancel = useCallback(() => setVisible(false), []);

  const handleOk = useCallback(() => {
    let formData = form.getFieldValue();
    if (["", null, undefined].includes(formData.reason))
      return message.error("请完善中断原因！");
    return new Promise((resolve, reject) => {
      request({
        url: `${window.config.mesUrl}/prodexec/prodexec/packageEquipment/interruptPack`,
        bodys: {
          gid: formData.gid,
        },
      })
        .then((res) => {
          if (res.success) {
            handleCancel();
            callbackRef.current();
          } else message.error(res.message || "操作失败！");
        })
        .finally(() => {
          resolve();
        });
    });
  }, [handleCancel]);
  useImperativeHandle(
    ref,
    () => ({
      show() {
        setVisible(true);
      },
      show: (data, callback) => {
        setVisible(true);
        form.resetFields();
        form.setFieldsValue(data);
        callbackRef.current = callback;
      },
    }),
    [form]
  );
  return (
    <ModalClient
      visible={visible}
      title="中断原因"
      onCancel={handleCancel}
      onOk={handleOk}
    >
      <Form autoComplete="off" size="large" form={form}>
        <Form.Item name="reason">
          <Input.TextArea placeholder="填写设备故障原因" rows={4} />
        </Form.Item>
      </Form>
    </ModalClient>
  );
});

// 结束
export const ModelFinish = React.forwardRef((props, ref) => {
  const {} = props;
  const [form, setForm] = useState([]);
  const callbackRef = useRef(() => {});
  const [visible, setVisible] = useState(false);
  const handleCancel = useCallback(() => setVisible(false), []);
  const handleOk = useCallback(() => {
    return new Promise((resolve, reject) => {
      request({
        url: `${window.config.mesUrl}/prodexec/prodexec/packageEquipment/endPack`,
        bodys: form,
      })
        .then((res) => {
          if (res.success) {
            handleCancel();
            callbackRef.current();
            message.success("包装完成！");
          } else message.error(res.message || "操作失败！");
        })
        .finally(() => {
          resolve();
        });
    });
  }, [handleCancel, form]);
  useImperativeHandle(
    ref,
    () => ({
      show: (data, callback) => {
        setVisible(true);
        setForm(data);
        callbackRef.current = callback;
      },
    }),
    []
  );
  return (
    <ModalClient
      visible={visible}
      title="结束"
      onCancel={handleCancel}
      onOk={handleOk}
    >
      <p>是否确认结束？</p>
    </ModalClient>
  );
});

// 超产
export const ModelOverproductionBatch = React.forwardRef((props, ref) => {
  const { } = props;
  const [form] = Form.useForm();
  const codeRef = useRef();
  const callbackRef = useRef(() => {});
  const [visible, setVisible] = useState(false);
  const handleCancel = useCallback(() => setVisible(false), []);
  const handleOk = useCallback(() => {
    let formData = form.getFieldValue();
    if (codeRef.current && codeRef.current === formData.outBatch) {
      message.error("超产批号不能与原单号一致！");
    } else { 
      callbackRef.current && callbackRef.current(formData.outBatch);
      handleCancel();
    };
  }, [handleCancel, form]);
  useImperativeHandle(
    ref,
    () => ({
      show(code, callback) {
        codeRef.current = code;
        callbackRef.current = callback;
        setVisible(true);
      },
    }),
    []
  );
  return (
    <ModalClient
      visible={visible}
      title="超产批号"
      onCancel={handleCancel}
      onOk={handleOk}
    >
      <Form autoComplete="off" size="large" form={form}>
        <Form.Item name="outBatch">
          <Input placeholder="填写超产批号" allowClear/>
        </Form.Item>
      </Form>
    </ModalClient>
  );
});

// 超量打印
export const ModelOverPrint = React.forwardRef((props, ref) => {
  const {} = props;
  const [form, setForm] = useState("");
  const callbackRef = useRef(() => {});
  const [visible, setVisible] = useState(false);
  const handleCancel = useCallback(() => setVisible(false), []);
  const handleOk = useCallback(() => {
    return callbackRef.current(handleCancel);
  }, [handleCancel, form]);
  useImperativeHandle(
    ref,
    () => ({
      show: (data, callback) => {
        setVisible(true);
        setForm(data);
        callbackRef.current = callback;
      },
    }),
    []
  );
  return (
    <ModalClient
      visible={visible}
      title="确认打印"
      onCancel={handleCancel}
      onOk={handleOk}
    >
      <p>{ form }</p>
    </ModalClient>
  );
});