import SimpleForm from "@/components/form/simple_form";
import { traningConfig } from "@/pages/training/traning_config";
import {
  Button,
  Form,
  FormInstance,
  InputNumber,
  Modal,
  Select,
  SelectProps,
} from "antd";
import React from "react";
import { useState } from "react";
import baseHttp from "@/service/base";
import "./bot.less";
import { Store } from "antd/es/form/interface";
import { inject, observer } from "mobx-react";
import { FormType } from "@/components/form/interface";
import MinusCircleOutlined from "@ant-design/icons/lib/icons/MinusCircleOutlined";
const { Option } = Select;

const Dispath = (props: Store) => {
  const { trainingStore, trainingCatStore } = props;
  const formRef = React.useRef<FormInstance>(null);
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [projectConfig, setProjectConfig] = useState<any>([]);
  const [stashList, setStashList] = useState<any>([]);
  const [userList, setUserList] = useState<any>([]);
  const [data, setData] = useState<SelectProps["options"]>([]);
  const openDispatch = async () => {
    await getList();
    setIsModalOpen(true);
    setProjectConfig([
      ...traningConfig,
      {
        type: FormType.cehckboxGroup,
        label: "参与人员选择",
        name: "user_id",
        value: [],
        checkboxData: userList,
        rules: [{ required: true, message: "请选择参与人员!" }],
      },
    ]);
  };
  const getList = async () => {
    try {
      trainingCatStore.getlist().then(() => {
        setStashList(trainingCatStore.list);
      });
      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 ?? []);
      });
    } catch (error) {
      console.log(error);
    }
  };
  const handleCancle = () => {
    setIsModalOpen(false);
  };
  const handleSubmit = () => {
    formRef.current?.submit();
  };

  const onFinish = (values: any) => {
    let data = {
      ...values,
      score: Number(values.score),
      count: Number(values.count),
    };
    trainingStore.add(data);
    setIsModalOpen(false);
  };
  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 (
    <>
      <span onClick={openDispatch}>训练任务</span>
      <Modal
        title={"发布训练任务"}
        className="owner_model"
        width={800}
        open={isModalOpen}
        afterClose={() => {}}
        onOk={() => {}}
        okText="确定"
        cancelText="取消"
        footer={[
          <Button key="return" ghost onClick={handleCancle}>
            取消
          </Button>,
          <Button
            className="btn-dp"
            key="submit"
            type="primary"
            ghost
            onClick={handleSubmit}
          >
            确定
          </Button>,
        ]}
        onCancel={() => {
          setIsModalOpen(false);
        }}
      >
        <div className="disPatch" style={{ fontSize: "#fff" }}>
          <SimpleForm
            formRef={formRef}
            createCallback={() => {}}
            formName="card_basic"
            colProps={25}
            subBtnName="提交"
            formDatas={projectConfig}
            onFinish={onFinish}
            initialValues={true}
            onFinishFailed={() => {}}
          >
            <>
              <Form.Item
                key="category_identity"
                label="训练类别"
                name="category_identity"
                rules={[{ required: true, message: "请选择训练类别!" }]}
              >
                <Select placeholder="">
                  {stashList?.map((v: any) => {
                    return (
                      <Option key={v.identity} value={v.identity}>
                        {v.name}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
              <Form.List name="supplies_list">
                {(fields, { add, remove }) => (
                  <>
                    {fields.map(({ key, name, ...restField }) => (
                      <div 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",
                            right: "10px",
                            bottom: "20px",
                          }}
                          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>
        </div>
      </Modal>
    </>
  );
};
export default inject("trainingStore", "trainingCatStore")(observer(Dispath));
