import React, { useState, useRef, useEffect,useImperativeHandle } from "react";
import { connect } from "react-redux";
import { Modal, Form, Row, Col, Spin } from "@douyinfe/semi-ui";
import { IconTickCircle } from "@douyinfe/semi-icons";

import moment from "moment";

function nvrModal(props) {
  const { modalName ,nvrRef} = props;
  const { dispatch, actions, vender, close } = props;
  const nvrData = props.nvrData || {}; //修改时传来的值
  const form = useRef();
  const [visible, setVisible] = useState(false); //是否显示弹框
  const [isloading, setloading] = useState(false); //是否显示loading
  const [loadingTip, setloadingTip] = useState("获取中...请稍后..."); //loading tip的值
  const [step, setstep] = useState("none"); //第几步
  const [okText, setokText] = useState("测试校验"); //ok弹框text  右边
  const [cancelText, setcancelText] = useState("取消"); //取消弹框text  左边
  const [formObj, setformObj] = useState(); //接口入参

  function showDialog() {
    //打开弹框
    setVisible(true);
  }
  function positionForm(val) {
    let zz = /^(-?\d+)(\.\d+)?$/;
    if (!val) {
      return "请输入或拾取高德经纬度坐标";
    } else if (val.split(",").length != 2) {
      return "请输入格式为116.354169,39.835452的经纬度坐标";
    } else if (!zz.test(val.split(",")[0])) {
      return "只能填写数字";
    } else if (!zz.test(val.split(",")[1])) {
      return "只能填写数字";
    } else {
      return "";
    }
  }
  function handleOk() {
    //点击弹框确定  右边按钮
    if (step == "none") {
      form.current
        .validate()
        .then((values) => {
          //表单校验
          console.log(values)
          let valuesObj = JSON.parse(JSON.stringify(values));
          valuesObj.longitude = values.position.split(",")[0];
          valuesObj.latitude = values.position.split(",")[1];
          delete valuesObj.position;
          if (nvrData.id) {
            valuesObj.id = nvrData.id;
          }
          var front = new moment(); //验证前时间
          setloading(true);
          dispatch(
            actions.equipmentWarehouse.getCheck({
              serialNo: valuesObj.serialNo,
            })
          ).then((res) => {
            var after = new moment();  //验证后时间
            var duration = moment.duration(after.diff(front))._data.milliseconds;
            if (res.success) {
              setTimeout(
                () => {
                  setloadingTip("已完成");
                  setTimeout(() => {
                    setstep("block");
                    setloading(false);
                    setokText("确认");
                    setcancelText("上一步");
                    setloadingTip("获取中...请稍后...");
                  }, 1000);
                },
                duration > 2000 ? 0 : 2000 - duration
              );
            } else {
              setTimeout(
                () => {
                  setloadingTip("校验失败");
                  setTimeout(() => {
                    setstep("none");
                    setloading(false);
                    setokText("测试校验");
                    setcancelText("取消");
                    setloadingTip("获取中...请稍后...");
                  }, 1000);
                },
                duration > 2000 ? 0 : 2000 - duration
              );
            }
          });
          setformObj(valuesObj);
        })
        .catch((errors) => {
          //表单校验失败
          console.log("errors", errors);
        });
    } else {
      dispatch(actions.equipmentWarehouse.addchangeNvr(formObj)).then((res) => {
        setVisible(false);
        close();
      });
    }
  }
  function handleAfterClose() {
    //在关闭之后
    setstep("none");
    setokText("测试校验");
    setcancelText("取消");
  }
  function handleCancel() {
    //点击弹框取消  左边按钮
    if (step == "none") {
      setVisible(false);
    } else {
      setstep("none");
      setokText("测试校验");
      setcancelText("取消");
    }
  }
  function handleLocation() {
    //高德经纬度
    window.open("https://lbs.amap.com/tools/picker", "_blank");
  }
  useImperativeHandle(nvrRef, () => ({
    //传给父组件方法
    //aa即为子组件暴露给父组件的方法
    nvrNumber: ()=>formObj.serialNo
  }));
  return (
    <>
      <div onClick={showDialog}>{modalName == "add" ? "添加NVR" : "修改"}</div>
      <Modal
        title={modalName == "add" ? "添加NVR" : "修改NVR"}
        okText={okText}
        cancelText={cancelText} //取消按钮
        visible={visible}
        onOk={handleOk}
        width={607}
        afterClose={handleAfterClose}
        onCancel={handleCancel}
      >
        <Spin tip={loadingTip} spinning={isloading}>
          <div
            style={{
              paddingLeft: 16,
              display: step == "none" ? "block" : "none",
            }}
          >
            <Form
              allowEmpty
              labelPosition="left"
              labelAlign="left"
              labelWidth="90px"
              onValueChange={(values) => console.log(values)}
              getFormApi={(formApi) => (form.current = formApi)}
            >
              <Row>
                <Col span={12}>
                  <Form.Input
                    maxLength="39"
                    field="serialNo"
                    label="设备编号:"
                    initValue={nvrData.serialNo || ""}
                    placeholder="请输入设备编号"
                    style={{ width: 149 }}
                    rules={[{ required: true, message: "请输入设备编号" }]}
                  />
                </Col>
                <Col span={12}>
                  <Form.InputNumber
                    formatter={(value) => `${value}`.replace(/\D/g, "")}
                    hideButtons={true}
                    maxLength="15"
                    field="regionCode"
                    label="行政区区码:"
                    initValue={nvrData.regionCode || ""}
                    placeholder="请输入行政区区码"
                    style={{ width: 149 }}
                  />
                </Col>
                <Col span={24}>
                  <Form.Input
                    maxLength="36"
                    field="name"
                    label="设备名称:"
                    initValue={nvrData.name || ""}
                    placeholder="请输入设备名称"
                    style={{ width: 421 }}
                    rules={[
                      {
                        required: true,
                        message: "请输入设备名称、常用项目或位置定义",
                      },
                    ]}
                  />
                </Col>
                <Col span={24}>
                  <Form.Select
                    label="设备厂家:"
                    field="venderId"
                    initValue={nvrData.venderId || null}
                    placeholder="请选择设备厂家"
                    style={{ width: 421 }}
                    rules={[{ required: true, message: "请选择设备厂家" }]}
                  >
                    {vender.map((item, index) => (
                      <Form.Select.Option key={index} value={item.id}>
                        {item.name}
                      </Form.Select.Option>
                    ))}
                  </Form.Select>
                </Col>
                <Col span={24} style={{ display: "flex" }}>
                  <Form.Input
                    maxLength="39"
                    field="position"
                    label="安装位置:"
                    initValue={
                      nvrData.longitude && nvrData.latitude
                        ? nvrData.longitude + "," + nvrData.latitude
                        : ""
                    }
                    placeholder="请输入或拾取高德经纬度坐标"
                    style={{ width: 386 }}
                    validate={positionForm}
                    rules={[
                      {
                        required: true,
                        message: "请输入或拾取高德经纬度坐标",
                      },
                    ]}
                  />
                  <div
                    style={{
                      width: 32,
                      height: 32,
                      background: "#1859C1",
                      marginLeft: 4,
                      display: "flex",
                      justifyContent: "center",
                      alignItems: "center",
                      cursor: "pointer",
                      marginTop: 12,
                      borderRadius: 3 + "px",
                    }}
                    onClick={handleLocation}
                  >
                    <img
                      src="../../../assets/images/background/location.png"
                      width={16}
                      height={20}
                    />
                  </div>
                </Col>
              </Row>
            </Form>
          </div>

          <div style={{ height: 224, display: step }}>
            <div
              style={{
                paddingTop: 50,
                display: "flex",
                justifyContent: "center",
              }}
            >
              <IconTickCircle style={{ color: "#04B234", fontSize: 60 }} />
            </div>
            <div
              style={{
                marginTop: 20,
                display: "flex",
                justifyContent: "center",
              }}
            >
              已完成NVR设备测试和校验，是否确认添加？
            </div>
          </div>
        </Spin>
      </Modal>
    </>
  );
}

function mapStateToProps(state) {
  const { auth, global, members, vender } = state;
  return {
    loading: members.isRequesting,
    user: auth.user,
    actions: global.actions,
    members: members.data,
    vender: vender.data || [], //设备厂家
  };
}

export default connect(mapStateToProps)(nvrModal);
