import { FC, useEffect, useMemo, useState } from "react";
import classNames from "classnames";
import {
  Col,
  Form,
  Input,
  InputNumber,
  Radio,
  Row,
  Select,
  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,
} from "@/api";
import { CONNECT_WITH_SYMBOL_OPTIONS, SYMBOL_OPTIONS } from "../constants";
import { isNull } from "lodash";
import { DageLoading } from "@dage/pc-components";

const { TextArea } = Input;
const CONFIRM_OPTIONS = [
  {
    label: "是",
    value: YES_OR_NO.YES,
  },
  {
    label: "否",
    value: YES_OR_NO.NO,
  },
];

const CreateOrEditIndex: FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const query = new URLSearchParams(location.search);
  const params = useParams();
  const [form] = Form.useForm();
  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 handleSubmit = async () => {
    if (!(await form.validateFields())) return;

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

    if (materialIds)
      rest.materialIds = materialIds.map((i: any) => i.id).join(",");
    if (rest.isPoint === YES_OR_NO.YES) {
      // 打分点
      rest.jsonPoint = {
        api,
        isAdd,
        score,
      };
    }
    if (rest.isWarn === YES_OR_NO.YES) {
      // 告警阈值
      rest.jsonWarn = JSON.stringify(warnData);
    }

    await saveAssIndexApi({
      ...rest,
      level: 1,
      type: params.type,
      id: detail?.id,
    });
    navigate(-1);
  };

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

  const getDetail = async () => {
    try {
      setLoading(true);
      const data = await getAssIndexDetailApi(Number(params.id));
      const pointData =
        data.isPoint === YES_OR_NO.YES ? JSON.parse(data.jsonPoint) : null;
      const warnData =
        data.isWarn === YES_OR_NO.YES ? 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,
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getAssIndexTree();

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

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

  return (
    <PageContainer title="新增指标">
      <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>
        <Form.Item
          label="指标名称"
          required
          name="name"
          rules={[{ required: true, message: "请输入指标名称" }]}
        >
          <Input
            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="reamrk">
          <TextArea
            className="mw650"
            showCount
            maxLength={500}
            placeholder="请输入内容，最多500字"
            style={{ height: 120, resize: "none" }}
          />
        </Form.Item>

        <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>

        <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>

        <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;
