import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import {
  Button,
  Cascader,
  Form,
  FormInstance,
  Input,
  Popconfirm,
  Select,
} from "antd";
import { A1addType } from "@/pages/A1Camera/data";
import { MinusCircleOutlined, PlusCircleOutlined } from "@ant-design/icons";
import classNames from "classnames";
import { useDispatch, useSelector } from "react-redux";
import { C1_APIgetlist } from "@/store/action/C1User";
import { RootState } from "@/store";
import { A2_APIadd, A2_APIgetInfo } from "@/store/action/A2Psychz";
import { MessageFu } from "@/utils/message";
import { getTokenInfo } from "@/utils/storage";
import TextArea from "antd/es/input/TextArea";
import { mapDataAll1 } from "@/pages/C1User/AddUser/city";

type Props = {
  openInfo: A1addType;
  closeFu: () => void;
  upTableFu: () => void;
  addTableFu: () => void;
};

function AddPsychz({ openInfo, closeFu, upTableFu, addTableFu }: Props) {
  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null);

  const getInfoFu = useCallback(async (id: number) => {
    const res = await A2_APIgetInfo(id);
    if (res.code === 0) {
      const data = res.data;
      let cityBase: null | string[] = null;
      if (data.province && data.city && data.region)
        cityBase = [data.province, data.city, data.region];
      FormBoxRef.current?.setFieldsValue({
        ...data,
        cityBase,
      });
      setRoomList([data.roomNum]);
    }
  }, []);

  useEffect(() => {
    if (openInfo.txt === "新增") {
      FormBoxRef.current?.setFieldsValue({
        pmUserId: getTokenInfo().user.id,
      });
    } else getInfoFu(openInfo.id);
  }, [getInfoFu, openInfo]);

  // 新增的时候的机房编码的数组
  const [roomList, setRoomList] = useState([""] as string[]);

  // 没有通过校验
  const onFinishFailed = useCallback(() => {
    setIsOk(true);
  }, []);

  const [isOk, setIsOk] = useState(false);

  // 判断机房编码是否重复
  const numIsAgain = useMemo(() => {
    const tempArr = roomList.filter((v) => v);
    return new Set(tempArr).size !== tempArr.length;
  }, [roomList]);

  // 通过校验点击确定
  const onFinish = useCallback(
    async (value: any) => {
      setIsOk(true);

      const tempArr = roomList.filter((v) => v && v.length >= 24);
      if (roomList.length > tempArr.length) return;

      // 校验新增的时候的机房编码
      if (numIsAgain) return;

      const obj = {
        ...value,
        id: openInfo.txt === "新增" ? null : openInfo.id,
        province: value.cityBase ? value.cityBase[0] : null,
        city: value.cityBase ? value.cityBase[1] : null,
        region: value.cityBase ? value.cityBase[2] : null,
        typeIn: "pc",
        roomNum: roomList,
      };

      const res = await A2_APIadd(obj);
      if (res.code === 0) {
        MessageFu.success(`${openInfo.txt}成功!`);
        openInfo.txt === "新增" ? addTableFu() : upTableFu();
        closeFu();
      }
    },
    [
      addTableFu,
      closeFu,
      numIsAgain,
      openInfo.id,
      openInfo.txt,
      roomList,
      upTableFu,
    ]
  );

  // 获取用户列表的所有用户，用于表单的  项目经理 的下拉
  const dispatch = useDispatch();

  useEffect(() => {
    // 获取用户列表所有用户信息
    dispatch(
      C1_APIgetlist(
        {
          pageSize: 99999,
          pageNum: 1,
        },
        true
      )
    );
  }, [dispatch]);

  const { C1TableListAll } = useSelector((state: RootState) => state.C1User);

  return (
    <div className={styles.AddPsychz}>
      <div className="A2addMain">
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          labelCol={{ span: 3 }}
          name="basic"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item label="站址地区" name="cityBase">
            <Cascader
              style={{ width: 300 }}
              options={mapDataAll1}
              placeholder="请选择地点"
            />
          </Form.Item>

          <Form.Item
            label="详细地址"
            name="address"
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <TextArea placeholder="请输入内容" showCount maxLength={50} />
          </Form.Item>

          <Form.Item
            label="站址名称"
            name="name"
            rules={[{ required: true, message: "请输入站址名称!" }]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input maxLength={20} showCount placeholder="请输入内容" />
          </Form.Item>

          <Form.Item
            label="站址编号"
            name="siteNum"
            rules={[{ required: true, message: "请输入站址编号!" }]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input maxLength={20} showCount placeholder="请输入内容" />
          </Form.Item>
          <Form.Item
            label="项目经理"
            name="pmUserId"
            rules={[{ required: true, message: "请选择项目经理!" }]}
          >
            <Select
              style={{ width: 300 }}
              placeholder="请选择"
              options={C1TableListAll}
            />
          </Form.Item>

          {/* {openInfo.txt === "新增" ? ( */}
          <div className="e_row">
            <div className="e_rowL">
              <span> * </span>机房编码：
            </div>
            <div
              className={classNames(
                "e_rowR",
                roomList.length >= 10 || numIsAgain ? "e_rowRErr" : ""
              )}
            >
              <div className="e_rowRightTit">
                {roomList.length >= 10 ? <> 最多可添加10个!&emsp;&emsp;</> : ""}
                {numIsAgain ? "机房编码重复!" : ""}
              </div>

              {roomList.map((v, i) => (
                <div
                  className={classNames(
                    "e_rowRrow",
                    roomList.length >= 10 ? "e_rowRrowIconHide" : "",
                    isOk && (!v || v.length < 24) ? "e_rowRrowErr" : "",
                    openInfo.txt === "编辑" ? "e_rowRrowEdit" : ""
                  )}
                  key={i}
                >
                  <>
                    {i === 0 ? (
                      <PlusCircleOutlined
                        rev={undefined}
                        onClick={() => setRoomList([...roomList, ""])}
                      />
                    ) : (
                      <Popconfirm
                        title="删除后无法恢复，是否删除?"
                        okText="删除"
                        cancelText="取消"
                        onConfirm={() =>
                          setRoomList(roomList.filter((c, ci) => ci !== i))
                        }
                        okButtonProps={{ loading: false }}
                      >
                        <MinusCircleOutlined rev={undefined} />
                      </Popconfirm>
                    )}
                  </>
                  <Input
                    value={v}
                    onChange={(e) => {
                      // console.log(e.target.value.replace(/[^\d]/g, ""));

                      setRoomList(
                        roomList.map((c, ci) =>
                          ci === i ? e.target.value.replace(/[^\d]/g, "") : c
                        )
                      );
                    }}
                    maxLength={24}
                    showCount
                    placeholder="请输24位纯数字"
                  />
                  <div className="e_rowRrowTit">
                    {v.length === 0 ? "请输入机房编码!" : "请输入24位纯数字!"}
                  </div>
                </div>
              ))}
            </div>
          </div>
          {/* 确定和取消按钮 */}
          <br />
          <Form.Item className="A2addBtn">
            <Button type="primary" htmlType="submit">
              提交
            </Button>
            &emsp;
            <Popconfirm
              title="放弃编辑后，信息将不会保存!"
              okText="放弃"
              cancelText="取消"
              onConfirm={closeFu}
              okButtonProps={{ loading: false }}
            >
              <Button>取消</Button>
            </Popconfirm>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}

const MemoAddPsychz = React.memo(AddPsychz);

export default MemoAddPsychz;
