import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { C1openInfoType, C1options } from "../data";
import {
  Button,
  Cascader,
  Form,
  FormInstance,
  Input,
  Popconfirm,
  Select,
} from "antd";
import classNames from "classnames";
import { C1_APIadd, C1_APIgetInfo } from "@/store/action/C1User";
import { MessageFu } from "@/utils/message";
import { mapDataAll2 } from "./city";

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

function AddUser({ openInfo, closeFu, upTableFu, addTableFu }: Props) {
  const getInfoFu = useCallback(async (id: number) => {
    const res = await C1_APIgetInfo(id);
    if (res.code === 0) {
      FormBoxRef.current?.setFieldsValue(res.data);
      setIsRoleId(res.data.roleId);

      setCityList(JSON.parse(res.data.webCity));
    }
  }, []);

  useEffect(() => {
    if (openInfo.txt === "编辑用户") {
      // 发接口拿详情
      getInfoFu(openInfo.id);
    }
  }, [getInfoFu, openInfo]);

  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null);

  // 手动的 表单 外的校验
  const [isOk, setIsOk] = useState(false);

  // 角色选择 项目经理 和 铁塔审核员。为铁塔审核员的时候 显示 选择 城市的按钮
  const [isRoleId, setIsRoleId] = useState<null | 3 | 4>(null);

  // 添加的城市列表
  type CityListType = {
    id: string;
    txt: string[] | undefined;
  };

  const [cityList, setCityList] = useState([] as CityListType[]);

  const cityListRes = useMemo(() => {
    return cityList.filter((v) => v.txt);
  }, [cityList]);

  // 级联选择器的改变
  const cityChangeFu = useCallback(
    (value: any, id: string) => {
      setCityList(
        cityList.map((v) => ({
          ...v,
          txt: v.id === id ? value : v.txt,
        }))
      );
    },
    [cityList]
  );

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

  // 通过校验点击确定
  const onFinish = useCallback(
    async (value: any) => {
      setIsOk(true);
      if (!cityListRes.length && value.roleId === 4) return;

      let scopeCity = [] as string[];

      if (value.roleId === 4) {
        const cityTemp = cityListRes.map((v) => v.txt);
        cityTemp.forEach((v) => {
          scopeCity.push(v![1]);
        });
      }

      const obj = {
        ...value,
        id: openInfo.txt === "新增用户" ? null : openInfo.id,
        scopeCity: scopeCity.join(","),
        webCity: JSON.stringify(cityListRes),
      };

      const res = await C1_APIadd(obj);

      if (res.code === 0) {
        MessageFu.success(
          openInfo.txt === "新增用户" ? "新增成功!" : "编辑成功!"
        );
        openInfo.txt === "新增用户" ? addTableFu() : upTableFu();
        closeFu();
      }
    },
    [addTableFu, cityListRes, closeFu, openInfo.id, openInfo.txt, upTableFu]
  );

  return (
    <div className={classNames(styles.AddUser)}>
      <div className="C1addMain">
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          labelCol={{ span: 3 }}
          name="basic"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="用户名"
            name="userName"
            rules={[
              { required: true, message: "请输入内容，6-15字" },
              {
                validator: (_: any, value: any) => {
                  if (value) {
                    const reg = new RegExp(/^[a-zA-Z0-9_]{6,15}$/);
                    const flag = reg.test(value);
                    if (flag) return Promise.resolve(value);
                    else
                      return Promise.reject(
                        "用户名只包含字母、数字和下划线，最少 6 个字符!"
                      );
                  } else return Promise.resolve(value);
                },
              },
            ]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input
              disabled={openInfo.txt === "编辑用户"}
              maxLength={15}
              showCount
              placeholder="请输入内容，6-15字"
            />
          </Form.Item>

          <div className="e_row" hidden={openInfo.txt === "编辑用户"}>
            <div className="e_rowL">
              <span> </span>初始密码：
            </div>
            <div className="e_rowR">123456</div>
          </div>

          <Form.Item
            label="真实姓名"
            name="realName"
            rules={[{ required: true, message: "请输入真实姓名!" }]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input
              maxLength={10}
              showCount
              placeholder="请输入内容，最多10字"
            />
          </Form.Item>

          <Form.Item
            label="手机号"
            name="phone"
            rules={[
              {
                pattern: /^1[3-9][0-9]{9}$/,
                message: "请输入正确格式的手机号!",
              },
            ]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input maxLength={11} showCount placeholder="请输入11位手机号" />
          </Form.Item>

          <Form.Item
            label="角色"
            name="roleId"
            rules={[{ required: true, message: "请选择角色!" }]}
          >
            <Select
              value={isRoleId}
              onChange={(e) => setIsRoleId(e)}
              style={{ width: 300 }}
              placeholder="请选择"
              options={C1options.filter((v) => v.value !== "全部")}
            />
          </Form.Item>

          {isRoleId === 4 ? (
            <div className="e_row e_rowCenten">
              <div className="e_rowL">
                <span>* </span>城市：
              </div>
              <div className="e_rowR">
                <Button
                  disabled={cityList.length >= 20}
                  type="primary"
                  onClick={() =>
                    setCityList([
                      ...cityList,
                      { id: Date.now() + "", txt: undefined },
                    ])
                  }
                >
                  新增
                </Button>
                &emsp;
                <div
                  className={classNames(
                    "e_rowRtit",
                    isOk && !cityListRes.length ? "e_rowRtitShow" : ""
                  )}
                >
                  至少添加一个城市 并 选择地点
                </div>
                <div
                  className={classNames(
                    "e_rowRtit",
                    cityList.length >= 20 ? "e_rowRtitShow" : ""
                  )}
                >
                  &emsp;&emsp;最多只能添加20个城市
                </div>
              </div>
            </div>
          ) : null}

          {/* 城市列表 */}
          <div className="e_rowCity" hidden={isRoleId === 3}>
            {cityList.map((v) => (
              <div className="e_rowRList" key={v.id}>
                <Cascader
                  value={v.txt}
                  style={{ width: 300 }}
                  options={mapDataAll2}
                  placeholder="请选择地点"
                  onChange={(e) => cityChangeFu(e, v.id)}
                />
                &emsp;
                <Popconfirm
                  title="删除后无法恢复，是否删除?"
                  okText="删除"
                  cancelText="取消"
                  onConfirm={() =>
                    setCityList(cityList.filter((c) => c.id !== v.id))
                  }
                  okButtonProps={{ loading: false }}
                >
                  <Button size="small" type="text" danger>
                    删除
                  </Button>
                </Popconfirm>
              </div>
            ))}
          </div>

          {/* 确定和取消按钮 */}
          <br />
          <Form.Item className="C1addBtn">
            <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 MemoAddUser = React.memo(AddUser);

export default MemoAddUser;
