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";
import TaskArchives from "../training/task_archives";
import EmUser from "./emUser";
const Emergency = (props: Store) => {
  const { emergencyStore, trainingStore } = props;
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [emUserModel, setEmUserModel] = useState<boolean>(false);

  const [projectConfig, setProjectConfig] = useState<any>([]);
  const formRef = React.useRef<FormInstance>(null);
  const [record, setRecord] = useState<any>(null);
  const [identity, setIdentity] = 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: "accomplish",
      render: (status) =>
        status === 1 ? (
          <span style={{ color: "black" }}>进行中</span>
        ) : (
          <span style={{ color: "green" }}>已完成</span>
        ),
    },
    {
      title: "物资归还状态",
      dataIndex: "supplies_status",
      render: (supplies_status) =>
        supplies_status === 2 ? "已归还" : "未归还",
    },
    {
      title: "操作",
      dataIndex: "id",
      render: (any, record) => (
        <Space wrap>
          <Button
            type="dashed"
            size="small"
            onClick={() => {
              edit(record);
            }}
          >
            编辑 
          </Button>
          {record.accomplish === 1 ? (
            <Button
              type="dashed"
              size="small"
              onClick={() => {
                emergencyStore.fish(record.identity);
              }}
            >
              完成
            </Button>
          ) : null}
          <Button
            type="dashed"
            danger
            size="small"
            onClick={() => {
              dele(record);
            }}
          >
            删除
          </Button>
          <TaskArchives
            taskId={record?.identity}
            category_identity={record.archives_category_identity}
          />
          <Button
            type="dashed"
            size="small"
            onClick={() => {
              setIdentity(record?.identity);
              setEmUserModel(true);
            }}
          >
            人员查看
          </Button>
          {record.supplies_status === 2 ? null : (
            <Button
              type="dashed"
              size="small"
              onClick={() => {
                trainingStore.back(record?.identity, 1);
                emergencyStore.getlist();
              }}
            >
              物资归还
            </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("/v1/team/list", null).then((res) => {
      let data = res.data?.record ?? [];
      data.forEach((item) => {
        item.label = item.name;
        item.value = item.identity;
      });
      setUserList(data ?? []);
    });
  }, [emergencyStore]);

  const onFinishFailed = () => {};
  const handleSearch = (newValue: string) => {
    if (newValue === "") return;
    baseHttp.get("/v1/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="训练人员"
          width={1200}
          open={emUserModel}
          footer={null}
          onCancel={() => {
            setEmUserModel(false);
          }}
        >
          <EmUser id={identity} />
        </Modal>
        <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}
            onFinishFailed={onFinishFailed}
          >
            <Form.List name="supplies_list">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }) => (
                    <div key={key} style={{position:"relative"}}>
                      <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
                        style={{
                          position: "absolute",
                          bottom: "10px",
                          left: "300px",
                        }}
                        onClick={() => remove(name)}
                      />
                    </div>
                  ))}
                  <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", "trainingStore")(observer(Emergency));
