import SimpleForm from "@/components/form/simple_form";
import {
  Button,
  Form,
  FormInstance,
  InputNumber,
  Modal,
  Select,
  SelectProps,
} from "antd";
import { Store } from "antd/es/form/interface";
import React, { useEffect } from "react";
import { useState } from "react";
import baseHttp from "@/service/base";
import MinusCircleOutlined from "@ant-design/icons/lib/icons/MinusCircleOutlined";
import { EmConfig } from "@/pages/emergency/em_column";
import { inject, observer } from "mobx-react";

const Emr = (props: Store) => {
  const { emergencyStore, homeStore } = props;
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const formRef = React.useRef<FormInstance>(null);
  const [projectConfig, setProjectConfig] = useState<any>([]);
  const [data, setData] = useState<SelectProps["options"]>([]);
  const [userList, setUserList] = useState<Array<any>>([]);
  const openDispatch = () => {
    setProjectConfig(EmConfig(userList));
    setIsModalOpen(true);
  };
  const onFinishFailed = () => {};

  const onFinish = (values: any) => {
    let data = {
      ...values,
      long: values.marker["lng"],
      lat: values.marker["lat"],
    };
    let task_video: any = [];
    for (let i = 0; i < values.task_video.length; i++) {
      let item = values.task_video[i];
      task_video.push({
        device: item.split("-")[0],
        channel: item.split("-")[1],
      });
    }
    data.task_video = task_video;
    emergencyStore.add(data);
    setIsModalOpen(false);
    homeStore.getNewTask();
  };
  const handleSearch = (newValue: string) => {
    if (newValue === "") return;
    baseHttp.get("/supplies/list/serch", { name: newValue }).then((res) => {
      let data = res.data?.record ?? [];
      data.forEach((item) => {
        item.text = item.name;
        item.value = item.identity;
      });
      setData(data ?? []);
    });
  };
  useEffect(() => {
    emergencyStore.getlist();
    baseHttp.get("/team/list", null).then((res) => {
      let data = res.data?.record ?? [];
      data.forEach((item) => {
        item.label = item.name;
        item.value = item.identity;
      });
      setUserList(data ?? []);
    });
  }, [emergencyStore]);
  return (
    <>
      <span onClick={openDispatch}> 应急处突</span>
      <Modal
        title={"应急处突"}
        className="owner_model"
        width={1000}
        open={isModalOpen}
        afterClose={() => formRef.current?.resetFields()}
        onOk={() => formRef.current?.submit()}
        okText="确定"
        cancelText="取消"
        centered
        onCancel={() => {
          setIsModalOpen(false);
        }}
      >
        <div
          className="disPatch"
          style={{
            fontSize: "#fff",
            height: 600,
            overflowY: "auto",
            marginTop: "20px",
          }}
        >
          <SimpleForm
            formRef={formRef}
            createCallback={() => {
              formRef.current?.setFieldsValue(null);
            }}
            formName="card_basic"
            colProps={25}
            subBtnName="提交"
            formDatas={projectConfig}
            onFinish={onFinish}
            initialValues={true}
            childrenPosi={true}
            onFinishFailed={onFinishFailed}
          >
            <>
              <Form.List name="supplies_list">
                {(fields, { add, remove }) => (
                  <>
                    {fields.map(({ key, name, ...restField }) => (
                      <>
                        <Form.Item
                          {...restField}
                          label={"物资"}
                          name={[name, "supplies_identity"]}
                          rules={[{ required: true, message: "请选择物资" }]}
                        >
                          <Select
                            showSearch
                            placeholder={props.placeholder}
                            style={props.style}
                            defaultActiveFirstOption={false}
                            suffixIcon={null}
                            filterOption={false}
                            onSearch={handleSearch}
                            notFoundContent={null}
                            options={(data || []).map((d) => ({
                              value: d.value,
                              label: d.text,
                            }))}
                          />
                        </Form.Item>
                        <Form.Item
                          {...restField}
                          name={[name, "num"]}
                          label={"数量"}
                          rules={[
                            { required: true, message: "请输入物资数量" },
                          ]}
                        >
                          <InputNumber placeholder="请输入物资数量" />
                        </Form.Item>
                        <MinusCircleOutlined onClick={() => remove(name)} />
                      </>
                    ))}
                    <Form.Item>
                      <div style={{ textAlign: "center" }}>
                        <Button
                          style={{ width: 300 }}
                          type="dashed"
                          onClick={() => add()}
                          block
                        >
                          添加物资
                        </Button>
                      </div>
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </>
          </SimpleForm>
        </div>
      </Modal>
    </>
  );
};

export default inject("emergencyStore", "homeStore")(observer(Emr));
