import {
  Button,
  Space,
  Modal,
  FormInstance,
  Form,
  InputNumber,
  Select,
  SelectProps,
} from "antd";
import { inject, observer } from "mobx-react";
import type { ColumnsType } from "antd/es/table";
import BTable from "@/components/b_table";
import { useEffect, useState } from "react";
import { UserDataType } from "@/model/userModel";
import { Store } from "antd/lib/form/interface";
import SimpleForm from "@/components/form/simple_form";
import React from "react";
import baseHttp from "@/service/base";
import MinusCircleOutlined from "@ant-design/icons/lib/icons/MinusCircleOutlined";
import { EmConfig } from "./em_column";

const Emergency = (props: Store) => {
  const { emergencyStore } = props;
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [projectConfig, setProjectConfig] = useState<any>([]);
  const formRef = React.useRef<FormInstance>(null);
  const [record, setRecord] = useState<any>(null);
  const [tagId, setId] = useState<Number | null>(null);
  const [userList, setUserList] = useState<Array<any>>([]);
  const [data, setData] = useState<SelectProps["options"]>([]);

  const columns: ColumnsType<UserDataType> = [
    { title: "应急处突名称", dataIndex: "emergency_name" },
    { title: "目标位置", dataIndex: "target_location" },
    { title: "目标精度", dataIndex: "long" },
    { title: "目标纬度", dataIndex: "lat" },
    { title: "任务描述", dataIndex: "desc" },
    {
      title: "完成状态",
      dataIndex: "status",
      render: (status) =>
        status === 0 ? (
          <span style={{ color: "green" }}>进行中</span>
        ) : (
          <span style={{ color: "red" }}>已完成</span>
        ),
    },
    {
      title: "操作",
      dataIndex: "id",
      render: (any, record) => (
        <Space wrap>
          <Button
            type="dashed"
            size="small"
            onClick={() => {
              edit(record);
            }}
          >
            编辑
          </Button>
          <Button
            type="dashed"
            size="small"
            onClick={() => {
              emergencyStore.deleteItem(record.id);
            }}
          >
            完成
          </Button>
          <Button
            type="dashed"
            danger
            size="small"
            onClick={() => {
              dele(record);
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];
  const dele = (record) => {
    emergencyStore.deleteItem(record.identity);
  };
  const edit = (record) => {
    setProjectConfig(EmConfig(userList));

    setIsModalOpen(true);
    formRef.current?.setFieldsValue(record);
    setRecord(record);
    setId(record.id);
  };
  const onFinish = (values: any) => {
    let data = {
      ...values,
      long: values.marker["lng"],
      lat: values.marker["lat"],
    };
    if (!tagId) {
      emergencyStore.add(data);
    } else {
      emergencyStore.putItem(tagId, data);
    }
    setIsModalOpen(false);
  };
  useEffect(() => {
    emergencyStore.getlist();
    baseHttp.get("/user/list", null).then((res) => {
      let data = res.data?.record ?? [];
      data.forEach((item) => {
        item.label = item.account;
        item.value = item.identity;
      });
      setUserList(data ?? []);
    });
  }, [emergencyStore]);

  const onFinishFailed = () => {};
  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 ?? []);
    });
  };

  const handleChange = (newValue: string) => {
    // setValue(newValue);
  };
  // 用户选择回调
  return (
    <div className="contentBox">
      <Space direction="vertical" size="middle" style={{ display: "flex" }}>
        <Space direction="horizontal" size={"middle"}>
          <Button
            type="default"
            onClick={() => {
              setProjectConfig(EmConfig(userList));
              setId(null);
              setIsModalOpen(true);
            }}
          >
            任务发布
          </Button>
        </Space>

        <BTable
          store={emergencyStore}
          columns={columns}
          dataSource={emergencyStore.list}
        />
        <Modal
          title={!tagId ? "任务发布" : "任务编辑"}
          width={1200}
          open={isModalOpen}
          afterClose={() => formRef.current?.resetFields()}
          onOk={() => formRef.current?.submit()}
          okText="确定"
          cancelText="取消"
          onCancel={() => {
            setId(null);
            setIsModalOpen(false);
          }}
        >
          <SimpleForm
            formRef={formRef}
            createCallback={() => {
              formRef.current?.setFieldsValue(record);
            }}
            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}
                          onChange={handleChange}
                          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>
        </Modal>
      </Space>
    </div>
  );
};

export default inject("emergencyStore")(observer(Emergency));
