import SimpleForm from "@/components/form/simple_form";
import { traningConfig } from "@/pages/training/traning_config";
import {
  Button,
  Form,
  FormInstance,
  InputNumber,
  message,
  Modal,
  Select,
  SelectProps,
} from "antd";
import React, { useEffect } 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,homeStore } = 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: "team_id",
        value: [],
        checkboxData: userList,
        rules: [{ required: true, message: "请选择参与队伍!" }],
      },
     
    ]);
  };
  useEffect(() => {
    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 ?? []);
    });
  }, []);
  const getList = async () => {
    try {
      trainingCatStore.getlist().then(() => {
        setStashList(trainingCatStore.list);
      });
    } catch (error) {
      console.log(error);
    }
  };
  const handleCancle = () => {
    setIsModalOpen(false);
  };
  const handleSubmit = () => {
    formRef.current?.submit();
  };

  const onFinish = (values: any) => {
    let task_videos: any = [];
    for (let i = 0; i < values.task_video.length; i++) {
      let item = values.task_video[i];
      task_videos.push({
        device: item.split("-")[0],
        channel: item.split("-")[1],
      });
    }
    if (!task_videos || task_videos.length === 0) {
      message.error("请选择视频设备");
      return;
    }
    if (values.score === 0 || values.score === null) {
      message.error("请完善训练积分");
      return;
    }
    if (values.count === 0 || values.count === null) {
      message.error("请完善训练次数");
      return;
    }
    let data = {
      ...values,
      score: Number(values.score),
      count: Number(values.count),
    };
    data.task_video = task_videos;
    trainingStore.add(data).then(()=>{
      console.log("添加成功")
      message.error("任务发布成功");
      homeStore.getNewTask()
    }); 
    
    setIsModalOpen(false);
  };
  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 (
    <>
      <span onClick={openDispatch}>训练任务</span>
      <Modal
        title={"发布训练任务"}
        className="owner_model"
        centered
        width={1000}
        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", height: "600px", overflowY: "auto" }}
        >
          <SimpleForm
            formRef={formRef}
            createCallback={() => {}}
            formName="card_basic"
            colProps={25}
            subBtnName="提交"
            span={4}
            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
                        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
                          onClick={() => remove(name)}
                          style={{
                            position: "absolute",
                            top: "66px",
                            right: "20px",
                            color: "#fff",
                          }}
                        />
                      </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","homeStore")(observer(Dispath));
