import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import styles from "./index.module.scss";
import {
  Button,
  Cascader,
  DatePicker,
  Form,
  FormInstance,
  Input,
  InputNumber,
  Popconfirm,
  Select,
} from "antd";
import mapDataAll from "./data";
import dayjs from "dayjs";
import TextArea from "antd/es/input/TextArea";
import { MessageFu } from "@/utils/message";
import classNames from "classnames";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import { A1_APIaddProject, A1_APIgetInfoById } from "@/store/action/A1Project";
import { A1TableType } from "@/types";
import AuthCom from "@/components/AuthCom";
import { getTokenInfo } from "@/utils/storage";

const { RangePicker } = DatePicker;

type Props = {
  pageType: { txt: string; id: number };
  closeFu: () => void;
  addFu: () => void;
  editFu: (val: string) => void;
};

function A1Add({ pageType, closeFu, addFu, editFu }: Props) {
  const [lookInfo, setLookInfo] = useState({} as A1TableType);

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

  const userInfo = useMemo(() => {
    return getTokenInfo().user;
  }, []);

  const getInfoFu = useCallback(async (id: number) => {
    const res = await A1_APIgetInfoById(id);
    if (res.code === 0) {
      const info = res.data.entity;
      setLookInfo(info);

      const province = info.province ? info.province.split("-") : "";

      const dateScope = info.dateScope ? info.dateScope.split(" 至 ") : "";

      FormBoxRef.current?.setFieldsValue({
        ...info,
        province,
        dateScope: dateScope ? [dayjs(dateScope[0]), dayjs(dateScope[1])] : "",
      });

      // 回显的时候闪动 问题
      setIsOk(true);
    }
  }, []);

  useEffect(() => {
    if (!pageType.id) {
      // 新增
      setIsOk(true);
    } else {
      // 编辑
      getInfoFu(pageType.id);
    }
  }, [getInfoFu, pageType.id]);

  // 从仓库 获取 项目状态的下拉框 数据
  const statusArr = useSelector(
    (state: RootState) => state.A2Dict.A2Tab1_1Obj.status
  );

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

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

  // 通过校验点击确定
  const onFinish = useCallback(
    async (value: any) => {
      //  项目周期的处理
      let dateScope = "";
      if (value.dateScope && value.dateScope.length >= 1) {
        dateScope =
          dayjs(value.dateScope[0]).format("YYYY-MM-DD") +
          " 至 " +
          dayjs(value.dateScope[1]).format("YYYY-MM-DD");
      }

      // 项目地点的处理
      let province = "";
      if (value.province && value.province.length)
        province = value.province.join("-");

      const obj = {
        ...value,
        id: pageType.txt === "add" ? null : pageType.id,
        dateScope,
        amount: value.amount ? value.amount : "",
        province,
      };
      const res = await A1_APIaddProject(obj);
      if (res.code === 0) {
        if (pageType.txt === "add") {
          MessageFu.success("新增成功!");
          addFu();
        } else if (pageType.txt === "edit") {
          MessageFu.success("编辑成功!");
          editFu(value.num + " - " + value.name);
        }
        closeFu();
      }
    },
    [addFu, closeFu, editFu, pageType.id, pageType.txt]
  );

  

  return (
    <div className={styles.A1Add}>
      <div
        className={classNames(
          "A1AddMain",
          pageType.txt === "look" ? "A1AddMainLook" : ""
        )}
      >
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          name="basic"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          initialValues={{
            snapPmUser: userInfo.realName
          }}
        >
          <Form.Item
            label="项目编号"
            name="num"
            rules={[{ required: true, message: "请输入项目编号!" }]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input
              style={{ width: 600 }}
              maxLength={30}
              showCount
              placeholder={
                isOk
                  ? pageType.txt === "look"
                    ? "（空）"
                    : "请输入内容，不能重复"
                  : ""
              }
            />
          </Form.Item>

          <Form.Item
            label="项目名称"
            name="name"
            rules={[{ required: true, message: "请输入项目名称!" }]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input
              style={{ width: 600 }}
              maxLength={30}
              showCount
              placeholder={
                isOk ? (pageType.txt === "look" ? "（空）" : "请输入内容") : ""
              }
            />
          </Form.Item>

          <Form.Item label="建设单位" name="unit">
            <Input
              style={{ width: 600 }}
              maxLength={30}
              showCount
              placeholder={
                isOk ? (pageType.txt === "look" ? "（空）" : "请输入内容") : ""
              }
            />
          </Form.Item>

          <Form.Item label="项目地点" name="province">
            <Cascader
              style={{ width: 300 }}
              options={mapDataAll}
              placeholder={
                isOk ? (pageType.txt === "look" ? "（空）" : "请选择省/市") : ""
              }
            />
          </Form.Item>

          <Form.Item
            label="项目状态"
            name="statusId"
            rules={[{ required: true, message: "请选择项目状态!" }]}
          >
            <Select
              placeholder={
                isOk ? (pageType.txt === "look" ? "（空）" : "请选择") : ""
              }
              style={{ width: 300 }}
              options={statusArr.map((v) => ({ value: v.id, label: v.name }))}
            />
          </Form.Item>

          <Form.Item
            label="项目经理"
            name="snapPmUser"
          >
            <Input
              style={{ width: 600 }}
              maxLength={30}
              showCount
              placeholder={
                isOk ? (pageType.txt === "look" ? "（空）" : "请输入内容") : ""
              }
            />
          </Form.Item>

          <Form.Item
            label="商务经理"
            name="snapBmUser"
          >
            <Input
              style={{ width: 600 }}
              maxLength={30}
              showCount
              placeholder={
                isOk ? (pageType.txt === "look" ? "（空）" : "请输入内容") : ""
              }
            />
          </Form.Item>

          {pageType.txt === "look" ? (
            <div className="e_row">
              <div className="e_rowL">
                <span> </span>项目周期：
              </div>
              <div className="e_rowR e_rowRLook">
                {isOk
                  ? lookInfo.dateScope
                    ? lookInfo.dateScope
                    : "（空）"
                  : ""}
              </div>
            </div>
          ) : (
            <Form.Item label="项目周期" name="dateScope">
              <RangePicker style={{ width: 300 }} />
            </Form.Item>
          )}

          <Form.Item label="项目简介" name="description">
            <TextArea
              style={{ width: 600 }}
              autoSize
              placeholder={
                isOk ? (pageType.txt === "look" ? "（空）" : "请输入内容") : ""
              }
              showCount
              maxLength={500}
            />
          </Form.Item>

          {pageType.txt === "look" ? (
            <AuthCom aId="1082">
              <div className="e_row">
                <div className="e_rowL">
                  <span> </span>项目金额：
                </div>
                <div className="e_rowR e_rowRLook">
                  {isOk
                    ? lookInfo.amount
                      ? "￥" + lookInfo.amount
                      : "（空）"
                    : ""}
                </div>
              </div>
            </AuthCom>
          ) : (
            <Form.Item label="项目金额" name="amount">
              <InputNumber
                style={{ width: 300 }}
                addonBefore="￥"
                maxLength={10}
                placeholder="请输入数字，最多10位"
              />
            </Form.Item>
          )}

          {/* 确定和取消按钮 */}
          <div className="A1AddBtn">
            {pageType.txt === "look" ? null : ( // <Button onClick={closeFu}>关 闭</Button>
              <>
                <Popconfirm
                  title="放弃编辑后，信息将不会保存!"
                  okText="放弃"
                  cancelText="取消"
                  onConfirm={closeFu}
                  okButtonProps={{ loading: false }}
                >
                  <Button>取消</Button>
                </Popconfirm>{" "}
                &emsp;&emsp;
                <Button type="primary" htmlType="submit">
                  保存
                </Button>
              </>
            )}
          </div>
        </Form>
      </div>
    </div>
  );
}

const MemoA1Add = React.memo(A1Add);

export default MemoA1Add;
