import React, {
  useRef,
  useState,
  useEffect,
  forwardRef,
  useImperativeHandle,
} from "react";
import { Form, Input, Select, message } from "antd";
import { Modal, Button, Table, Radio } from "antd";
import Formular from "./components/Formular";
import API2 from "../../../api/alarm";
import styles from "./complex.module.less";
import oneNode from "./components/oneNode";
import { useMemoizedFn } from "ahooks";

const { Search } = Input;

function TranslateText(arr) {
  const dtLanguage = localStorage.getItem("dtLanguage");
  if (!Array.isArray(arr)) {
    return arr;
  }

  if (arr.length < 2 && arr.length > 0) {
    return arr?.[0];
  }

  if (dtLanguage === "en") {
    return arr?.[1];
  }

  return arr?.[0];
}

const Complex = (props, ref) => {
  const { editId, groupList = [], showList } = props;

  const [form] = Form.useForm();
  const formuRef = useRef();
  // const [alarmId, setAlarmId] = useState(searchParams.get('alarm_id'))
  // const [token, setToken] = useState(searchParams.get('token'))
  // const [apiUrl, setApiUrl] = useState(decodeURIComponent(searchParams.get('api_url')) + '/')
  const [data, setData] = useState();

  const [loading, setLoading] = useState(false);
  const [deviceList, setDeviceList] = useState([]);
  const [paginationProps, setPaginationProps] = useState({
    pageSize: 10,
    current: 1,
    showTotal: (total) => `共${total}条`,
    // showQuickJumper: true,
    // showSizeChanger:true,
    // size:'Large',
  });
  const [alarmId, setAlarmId] = useState(null);
  const [type, setType] = useState(0);
  const [ruleOptions, setRuleOptions] = useState([]);

  const handleTableChange = async (pagination) => {
    setPaginationProps({ ...pagination, showTotal: (total) => `共${total}条` });
    // setCurrentPage(pagination.current);
    // setPageSize(pagination.pageSize)
  };

  useEffect(() => {
    onSearch("");
  }, []);

  useEffect(() => {
    async function run() {
      if (alarmId && alarmId != -1) {
        const { state, data } = await API2.detailAlarm(Number(alarmId));
        form.setFieldsValue({
          name: data.name,
          alarm_level: data.alarm_level,
          group_id: data.group_id,
        });
        formuRef.current.backEndInput(data.formula);
        setData(data);
      } else {
        form.resetFields();
        setData(null);
      }
    }
    run();
  }, [alarmId]);

  const onModalOk = useMemoizedFn(async () => {
    if (type === 0) {
      props.onConfirm(null);
      return;
    }
    if (alarmId == -1) {
      const value = await form.validateFields();
      const obj = {
        ...value,
        formula: formuRef.current.getFinalStr(),
        ext_notify_list: [],
        is_complex: true,
        type: 1,
        sub_type: 12,
        status: 1,
        defer_unit: 2,
      };

      const { state } = await API2.addRule(obj);
      if (state === 0) {
        message.success("保存成功");
        props.onConfirm();
      }
    } else {
      const value = await form.validateFields();

      const obj = {
        ...data,
        ...value,
        formula: formuRef.current.getFinalStr(),
        ext_notify_list: [],
      };
      const { state } = await API2.editRule(obj);
      if (state === 0) {
        message.success("保存成功");
        props.onConfirm(data.id);
      }
    }
    form.resetFields();
    props.onConfirm();
  });

  useImperativeHandle(ref, () => {
    return {
      ok: onModalOk,
    };
  });

  const symbClick = (e) => {
    let innerText = e.target.innerText;
    if (innerText === "≥") {
      innerText = ">=";
    } else if (innerText === "≤") {
      innerText = "<=";
    } else if (innerText === "&&(and)") {
      innerText = "&&";
    } else if (innerText === "||(or)") {
      innerText = "||";
    }
    formuRef.current.dtInsertFormular(innerText);
    if (innerText === "()") {
      //判断为括号则把光标移到括号中间
      formuRef.current.moveInTextNode();
    }
  };

  const insertToFomular = (poi) => {
    const { point_id, name } = poi;
    const res = oneNode(point_id, name);
    formuRef.current.dtInsertFormular(res);
  };

  const columns = [
    {
      title: TranslateText(["点位编号", "Point id"]),
      dataIndex: "point_id",
      ellipsis: true,
    },
    {
      title: TranslateText(["点位名称", "Point name"]),
      dataIndex: "name",
      ellipsis: true,
    },
  ];

  const onSearch = async (v) => {
    const res = await API2.searchPoint({
      key_word: v ?? "",
      count: 50,
      type: 1,
      no_child: true,
    });
    if (res.state === 0) {
      setDeviceList(res.data || []);
      return;
    }
    setDeviceList([]);
  };

  const clickTableRow = (record) => {
    // child.current.handlePickPoint({name:record.name, point_id:record.point_id})
    insertToFomular({ name: record.name, point_id: record.point_id });
  };
  const onModalCancel = () => {
    props.onConfirm();
    form.resetFields();
  };

  useEffect(() => {
    function run() {
      if (editId && editId !== -1) {
        setAlarmId(editId);
        if (showList) {
          setType(1);
        }
      } else if (showList) {
        setType(0);
      }
    }
    run();
  }, [editId, showList]);

  useEffect(() => {
    async function run() {
      if (showList) {
        const res = await API2.getRuleList();
        setRuleOptions(
          res?.data?.rules?.map((item) => ({
            label: item.name,
            value: item.id,
          }))
        );
      }
    }
    run();
  }, [showList]);

  useEffect(() => {
    if (type === 2) {
      setAlarmId(-1);
    } else if (alarmId === -1 && type !== 2) {
      setAlarmId(null);
    }
  }, [type, alarmId]);

  return (
    <div className={styles.wrapper}>
      <div className="main">
        <div className="left">
          <Form
            name="basic"
            autoComplete="off"
            form={form}
            requiredMark={false}
            labelAlign="right"
            colon={false}
            labelCol={{
              span: 4,
            }}
            wrapperCol={{
              span: 15,
            }}
          >
            {showList && (
              <>
                <Form.Item label="类型">
                  <Radio.Group
                    value={type}
                    onChange={(e) => setType(e.target.value)}
                  >
                    <Radio value={0}>无规则</Radio>
                    <Radio value={1}>关联规则</Radio>
                    <Radio value={2}>新建规则</Radio>
                  </Radio.Group>
                </Form.Item>
                {type === 1 && (
                  <Form.Item label="关联规则">
                    <Select
                      value={alarmId}
                      onChange={setAlarmId}
                      style={{ width: 240 }}
                      options={ruleOptions}
                      placeholder={TranslateText(["请选择", "Please choose"])}
                    />
                  </Form.Item>
                )}
              </>
            )}
            {(!showList || type !== 0) && (
              <>
                <Form.Item
                  label={TranslateText(["告警名称", "Alarm name"])}
                  name="name"
                  rules={[
                    {
                      required: true,
                      message: TranslateText([
                        "请输入告警名称",
                        "Please input",
                      ]),
                    },
                  ]}
                >
                  <Input
                    placeholder={TranslateText([
                      "请输入告警名称",
                      "Please input",
                    ])}
                    style={{ width: "240px" }}
                  />
                </Form.Item>

                <Form.Item
                  label={TranslateText(["条件符号", "Symbol"])}
                  // name="symb"
                >
                  <div className="symb" style={{ width: "500px" }}>
                    <Button type="primary" onClick={symbClick}>
                      ()
                    </Button>
                    <Button type="primary" onClick={symbClick}>
                      {"&&(and)"}
                    </Button>
                    <Button type="primary" onClick={symbClick}>
                      {"||(or)"}
                    </Button>
                    <Button type="primary" onClick={symbClick}>
                      ≥
                    </Button>
                    <Button type="primary" onClick={symbClick}>
                      {">"}
                    </Button>
                    <Button type="primary" onClick={symbClick}>
                      =
                    </Button>
                    <Button type="primary" onClick={symbClick}>{`<`}</Button>
                    <Button type="primary" onClick={symbClick}>
                      ≤
                    </Button>
                    <Button type="primary" onClick={symbClick}>
                      +
                    </Button>
                    <Button type="primary" onClick={symbClick}>
                      -
                    </Button>
                    <Button type="primary" onClick={symbClick}>
                      ×
                    </Button>
                    <Button type="primary" onClick={symbClick}>
                      ÷
                    </Button>
                  </div>
                </Form.Item>

                <Form.Item
                  label={TranslateText(["条件编辑", "Edit"])}
                  // name="formu"
                >
                  <Formular ref={formuRef} key={`${type}-${alarmId}`} />
                </Form.Item>

                <Form.Item
                  label={TranslateText(["告警组", "Alarm group"])}
                  name={"group_id"}
                >
                  <Select
                    style={{ width: 240 }}
                    options={[
                      ...[
                        {
                          label: "未分组",
                          value: 0,
                        },
                      ],
                      ...(groupList?.map((item) => {
                        return {
                          label: item?.name,
                          value: item?.id,
                        };
                      }) ?? []),
                    ]}
                    placeholder={TranslateText(["请选择", "Please choose"])}
                  />
                </Form.Item>

                <Form.Item
                  label={TranslateText(["告警级别", "Alarm level"])}
                  name="alarm_level"
                  rules={[
                    {
                      required: true,
                      message: TranslateText([
                        "请输入告警级别",
                        "Please input",
                      ]),
                    },
                  ]}
                >
                  <Select
                    placeholder={TranslateText(["请选择", "Please choose"])}
                    style={{ width: "240px" }}
                  >
                    <Select.Option value={1}>
                      {TranslateText(["低", "Low"])}
                    </Select.Option>
                    <Select.Option value={2}>
                      {TranslateText(["中", "Medium"])}
                    </Select.Option>
                    <Select.Option value={3}>
                      {TranslateText(["高", "High"])}
                    </Select.Option>
                  </Select>
                </Form.Item>
              </>
            )}
          </Form>
        </div>

        {(!showList || type !== 0) && (
          <>
            <div
              style={{
                borderRight: "1px solid rgba(255, 255, 255, 0.12)",
                marginLeft: "16px",
              }}
            ></div>

            <div className="right">
              <div className="header">
                <Search
                  placeholder={TranslateText([
                    "请输入点位名称",
                    "Please input",
                  ])}
                  onSearch={onSearch}
                  style={{ width: "240px" }}
                  // className={styles.deviceListTreeSearch}
                />
              </div>
              <Table
                onRow={(record) => {
                  return {
                    onClick: (event) => {
                      clickTableRow(record);
                    }, // 点击行
                  };
                }}
                key={deviceList}
                loading={loading}
                columns={columns}
                dataSource={deviceList}
                rowKey="point_id"
                // className="deviceListTable"
                pagination={paginationProps}
                onChange={handleTableChange}
                size="middle"
              />
            </div>
          </>
        )}
      </div>
    </div>
  );
};

export default forwardRef(Complex);
