import { FC, useEffect, useMemo, useRef, useState } from "react";
import classNames from "classnames";
import {
  Col,
  Form,
  Input,
  InputNumber,
  Radio,
  Row,
  Select,
  Table,
  TreeSelect,
} from "antd";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { FileTemplateTable, FormPageFooter, PageContainer } from "@/components";
import style from "./index.module.scss";
import {
  AssIndexTreeItemType,
  ASS_INDEX_TYPE,
  IAssIndexDetail,
  YES_OR_NO,
} from "@/types";
import {
  getAssIndexDetailApi,
  getAssIndexTreeApi,
  saveAssIndexApi,
  saveAssInspectionApi,
} from "@/api";
import { CONNECT_WITH_SYMBOL_OPTIONS, SYMBOL_OPTIONS } from "../constants";
import { isNull, isNumber } from "lodash";
import { DageLoading } from "@dage/pc-components";
import { getSelectedNodes } from "@/utils";
import {
  InspectionEditable,
  InspectionEditableMethods,
} from "./components/InspectionEditable";
import { EditableFormInstance } from "@ant-design/pro-components";

const { TextArea } = Input;
const CONFIRM_OPTIONS = [
  {
    label: "是",
    value: YES_OR_NO.YES,
  },
  {
    label: "否",
    value: YES_OR_NO.NO,
  },
];
const MUSEUM_LEVEL: Record<number, string> = {
  1: "二级",
  2: "三级",
};

const CreateOrEditIndex: FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const query = new URLSearchParams(location.search);
  const params = useParams();
  const [form] = Form.useForm();
  const editorFormRef = useRef<EditableFormInstance<any>>();
  const inspectionRef = useRef<InspectionEditableMethods | null>(null);
  const [loading, setLoading] = useState(false);
  const [values, setValues] = useState<any>({
    isPoint: YES_OR_NO.YES,
    isWarn: YES_OR_NO.YES,
  });
  const [treeData, setTreeData] = useState<AssIndexTreeItemType[]>([]);
  const isEdit = useMemo(
    () => location.pathname.indexOf("edit") > -1,
    [location]
  );
  const [detail, setDetail] = useState<null | IAssIndexDetail>(null);
  const isFixed = params.type === ASS_INDEX_TYPE.FIXED;
  const parentId = Form.useWatch("parentId", form);
  /** 考察要点 */
  const gistIds = Form.useWatch("gistIds", form);
  /** 指标分值 */
  const scores = useMemo(() => {
    const temp = {
      id: 0,
      one: 0,
      two: 0,
      three: 0,
    };

    gistIds?.forEach((item: any) => {
      if (item.one) temp.one += item.one;
      if (item.two) temp.two += item.two;
      if (item.three) temp.three += item.three;
    });

    return [temp];
  }, [gistIds]);
  const parentNode = useMemo(() => {
    const id = Number(parentId);
    if (!isNumber(id)) return null;

    const targets = getSelectedNodes([id], treeData, true);

    return targets ? targets[0] : null;
  }, [parentId, treeData]);

  const handleSubmit = async () => {
    if (
      !(
        (await form.validateFields()) ||
        (await editorFormRef.current?.validateFields())
      )
    )
      return;

    const { materialIds, api, isAdd, score, warnData, gistIds, ...rest } =
      form.getFieldsValue();

    if (materialIds)
      rest.materialIds = materialIds.map((i: any) => i.id).join(",");
    // 定级指标才有打分点
    if (rest.isPoint === YES_OR_NO.YES && isFixed) {
      rest.jsonPoint = {
        api,
        isAdd,
        score,
      };
    }
    // 告警阈值
    if (rest.isWarn === YES_OR_NO.YES) {
      rest.jsonWarn = JSON.stringify(warnData);
    }
    // 运行指标补全权重
    if (!isFixed && !rest.weight) rest.weight = 0;

    // 先处理考察要点
    let data = null;
    if (Array.isArray(gistIds)) {
      data = await saveAssInspectionApi(
        gistIds.map((item) => {
          const { _id, ...rest } = item;
          return rest;
        })
      );
    }

    await saveAssIndexApi({
      ...rest,
      level: 1,
      type: params.type,
      id: detail?.id,
      gistIds: Array.isArray(data) ? data.join(",") : undefined,
    });
    navigate(-1);
  };

  const filterTreeData = (data: AssIndexTreeItemType[]) => {
    return data.map((item) => {
      const { children, ...rest } = item;
      const temp: AssIndexTreeItemType = {
        ...rest,
        children: [],
      };

      if (temp.level < 2) {
        temp.children = filterTreeData(children);
      }

      return temp;
    });
  };

  const getAssIndexTree = async () => {
    const data = await getAssIndexTreeApi(params.type as ASS_INDEX_TYPE);
    setTreeData(filterTreeData(data));
  };

  const getDetail = async () => {
    try {
      setLoading(true);
      const data = await getAssIndexDetailApi(Number(params.id));
      const pointData =
        data.isPoint === YES_OR_NO.YES && data.jsonPoint
          ? JSON.parse(data.jsonPoint)
          : null;
      const warnData =
        data.isWarn === YES_OR_NO.YES && data.jsonWarn
          ? JSON.parse(data.jsonWarn)
          : null;
      setDetail(data);
      form.setFieldsValue({
        parentId: data.parentId,
        name: data.name,
        remark: data.remark,
        num: data.num,
        isPoint: data.isPoint,
        isWarn: data.isWarn,
        score: pointData?.score,
        api: pointData?.api,
        isAdd: pointData?.isAdd,
        warnData,
        materialIds: data.materials,
        sort: data.sort,
      });
      setValues({
        isPoint: data.isPoint,
        isWarn: data.isWarn,
      });

      if (data.gists) {
        form.setFieldValue(
          "gistIds",
          data.gists.map((i) => ({
            ...i,
            _id: i.id,
          }))
        );
        // inspectionRef.current?.setEditableRowKeys(data.gists.map((i) => i.id));
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getAssIndexTree();

    const parentId = query.get("parentId");
    if (!isNull(parentId)) {
      form.setFieldValue("parentId", parentId);
    }

    if (isEdit) getDetail();
  }, []);

  return (
    <PageContainer title={isEdit ? "编辑指标" : "新增指标"}>
      <Form
        labelCol={{ span: 4 }}
        form={form}
        onFinish={handleSubmit}
        onValuesChange={(v, allValue) => {
          setValues(allValue);
        }}
      >
        <Form.Item label="父级指标" name="parentId">
          <TreeSelect
            disabled={isEdit}
            allowClear
            className="mw650"
            placeholder="请选择"
            treeData={treeData}
            fieldNames={{ label: "name", value: "id" }}
          />
        </Form.Item>
        {!isFixed && (
          <Form.Item label="指标级别">
            {MUSEUM_LEVEL[parentNode?.level as number] || "一级"}
          </Form.Item>
        )}
        <Form.Item
          label="指标名称"
          required
          name="name"
          rules={[{ required: true, message: "请输入指标名称" }]}
        >
          <Input
            disabled={isEdit}
            className="mw650"
            placeholder="请输入内容，最多20字"
            showCount
            maxLength={20}
          />
        </Form.Item>
        <Form.Item label="指标编号" name="num">
          <Input
            className="mw650"
            placeholder="请输入内容，最多20字"
            showCount
            maxLength={20}
          />
        </Form.Item>
        <Form.Item label="指标说明" name="remark">
          <TextArea
            className="mw650"
            showCount
            maxLength={500}
            placeholder="请输入内容，最多500字"
            style={{ height: 120, resize: "none" }}
          />
        </Form.Item>

        {parentNode?.level === 2 && !isFixed && (
          <>
            <Form.Item
              label="考察要点"
              required
              name="gistIds"
              rules={[{ required: true, message: "至少需要填入一个考查要点" }]}
            >
              <InspectionEditable
                ref={inspectionRef}
                editableFormRef={editorFormRef}
              />
            </Form.Item>

            <Form.Item label="指标分值">
              <Table
                rowKey="id"
                dataSource={scores}
                className="mw650"
                pagination={false}
                columns={[
                  {
                    title: "一级博物馆",
                    dataIndex: "one",
                    align: "center",
                  },
                  {
                    title: "二级博物馆",
                    dataIndex: "two",
                    align: "center",
                  },
                  {
                    title: "三级博物馆",
                    dataIndex: "three",
                    align: "center",
                  },
                ]}
              />
              <p className={style.tips}>注：指标分值：=各考查要点分值之和</p>
            </Form.Item>
          </>
        )}

        {isFixed && (
          <>
            <Form.Item
              label="打分点"
              name="isPoint"
              initialValue={values.isPoint}
            >
              <Radio.Group
                options={CONFIRM_OPTIONS}
                optionType="button"
                buttonStyle="solid"
              />
            </Form.Item>
            <Form.Item label=" " colon={false} style={{ marginTop: -14 }}>
              <div className={classNames("mw650", style.panel)}>
                {Boolean(values.isPoint) ? (
                  <>
                    <Form.Item
                      required
                      label="指标分值"
                      labelCol={{ span: 4 }}
                      name="score"
                      rules={[{ required: true, message: "请输入指标分值" }]}
                    >
                      <InputNumber
                        precision={0}
                        placeholder="请输入正整数"
                        className="w160"
                      />
                    </Form.Item>
                    <Form.Item
                      label="数据API"
                      labelCol={{ span: 4 }}
                      name="api"
                    >
                      <Input placeholder="请输入地址" style={{ width: 427 }} />
                    </Form.Item>
                    <Form.Item
                      label="加分项"
                      labelCol={{ span: 4 }}
                      colon={false}
                    >
                      <Form.Item noStyle name="isAdd">
                        <Radio.Group>
                          <Radio value={1}>是</Radio>
                          <Radio value={0}>否</Radio>
                        </Radio.Group>
                      </Form.Item>
                      <span className={style.tips}>
                        注：设为加分项后，该指标的分值不会参与父级指标的计算
                      </span>
                    </Form.Item>
                  </>
                ) : (
                  <Form.Item
                    label="分值：0"
                    labelCol={{ span: 4 }}
                    colon={false}
                  >
                    <span className={style.tips}>
                      注：当指标不作为打分点时，分值=该指标各分项分值（除加分项）之和
                    </span>
                  </Form.Item>
                )}
              </div>
            </Form.Item>
          </>
        )}

        {(isFixed || parentNode?.level === 2) && (
          <>
            <Form.Item
              label="告警阈值"
              name="isWarn"
              initialValue={values.isWarn}
            >
              <Radio.Group
                options={CONFIRM_OPTIONS}
                optionType="button"
                buttonStyle="solid"
              />
            </Form.Item>
            {Boolean(values.isWarn) ? (
              <Form.Item label=" " colon={false} style={{ marginTop: -14 }}>
                <div
                  className={classNames("mw650", style.panel)}
                  style={{ padding: "10px 30px" }}
                >
                  <Row gutter={10}>
                    <Col span={8}>
                      <Form.Item
                        noStyle
                        name={["warnData", "symbol"]}
                        rules={[{ required: true, message: "" }]}
                      >
                        <Select placeholder="请选择" options={SYMBOL_OPTIONS} />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        noStyle
                        name={["warnData", "num"]}
                        rules={[{ required: true, message: "" }]}
                      >
                        <InputNumber
                          precision={0}
                          placeholder="请输入正整数"
                          className="w100"
                        />
                      </Form.Item>
                    </Col>
                    <Col span={4}>
                      <span className={style.required}>（必填）</span>
                    </Col>
                  </Row>

                  <Form.Item noStyle name={["warnData", "and"]}>
                    <Radio.Group
                      options={CONNECT_WITH_SYMBOL_OPTIONS}
                      style={{ margin: "3px 0" }}
                    />
                  </Form.Item>

                  <Row gutter={10}>
                    <Col span={8}>
                      <Form.Item noStyle name={["warnData", "symbol2"]}>
                        <Select
                          allowClear
                          placeholder="请选择"
                          options={SYMBOL_OPTIONS}
                        />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item noStyle name={["warnData", "num2"]}>
                        <InputNumber
                          precision={0}
                          placeholder="请输入正整数"
                          className="w100"
                        />
                      </Form.Item>
                    </Col>
                    <Col span={4}></Col>
                  </Row>
                </div>
              </Form.Item>
            ) : (
              ""
            )}

            <Form.Item label="需上传资料" name="materialIds">
              <FileTemplateTable />
            </Form.Item>
          </>
        )}

        {(parentNode?.level || 0) < 2 && !isFixed && (
          <Form.Item required label="指标权重" name="weight">
            <InputNumber
              precision={0}
              min={1}
              max={100}
              placeholder="请输入1~100的正整数"
              className="mw650 w100"
              addonAfter="%"
            />
          </Form.Item>
        )}

        <Form.Item required label="排序值" name="sort" initialValue={999}>
          <InputNumber
            precision={0}
            min={1}
            max={999}
            placeholder="请输入1~999的数字。数字越小，排序越靠前"
            className="mw650 w100"
          />
        </Form.Item>

        <FormPageFooter onSubmit={handleSubmit} onCancel={() => navigate(-1)} />
      </Form>

      {loading && <DageLoading />}
    </PageContainer>
  );
};

export default CreateOrEditIndex;
