import {
  Button,
  Space,
  Modal,
  FormInstance,
  Form,
  Select,
  InputNumber,
  SelectProps,
  message,
} 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 dayjs from "dayjs";
import { traningConfig } from "./traning_config";
import { FormType } from "@/components/form/interface";
import TraningUser from "./traningUser";
import MinusCircleOutlined from "@ant-design/icons/lib/icons/MinusCircleOutlined";
import TaskArchives from "./task_archives";

const { Option } = Select;

const Trainings = (props: Store) => {
  const { trainingStore, trainingCatStore } = props;
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [isModalOpenUser, setIsModalOpenUser] = 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 [stashList, setStash] = useState<any>(null); // 仓库列表
  const [userList, setUserList] = useState<Array<any>>([]);
  const [data, setData] = useState<SelectProps["options"]>([]);

  const columns: ColumnsType<UserDataType> = [
    { title: "任务标题", dataIndex: "title", width: 200 },
    { title: "任务描述", dataIndex: "desc", width: 200 },
    { title: "任务地点", dataIndex: "address", width: 200 },
    {
      title: "任务开始时间",
      dataIndex: "start_time",
      render: (start_time) => (
        <span>{dayjs(start_time).format("YYYY-MM-DD")}</span>
      ),
      width:200
    },
    {
      title: "任务结束时间",
      dataIndex: "end_time",
      render: (end_time) => (
        <span>{dayjs(end_time).format("YYYY-MM-DD")}</span>
      ),
      width:200
    },
    { title: "任务积分设置", dataIndex: "score", width: 200 },
    { title: "任务类别", dataIndex: "category_name", width: 200 },
    {
      title: "任务状态",
      dataIndex: "status",
      render: (status) =>
        status === 1 ? (
          <span style={{ color: "black" }}>进行中</span>
        ) : (
          <span style={{ color: "green" }}>已完成</span>
        ),
      width: 200,
    },
    {
      title: "物资归还状态",
      width: 200,
      dataIndex: "supplies_status",
      render: (supplies_status) =>
        supplies_status === 2 ? "已归还" : "未归还",
    },
    {
      title: "操作",
      dataIndex: "id",
      width: 200,
      fixed: "right",
      render: (any, record) => (
        <Space wrap>
          <Button
            type="dashed"
            size="small"
            onClick={() => {
              edit(record);
            }}
          >
            编辑
          </Button>
          {record.status !== 2 ? (
            <Button
              type="dashed"
              size="small"
              onClick={() => {
                trainingStore.fish(record.identity);
              }}
            >
              完成
            </Button>
          ) : null}
          <Button
            type="dashed"
            danger
            size="small"
            onClick={() => {
              dele(record);
            }}
          >
            删除
          </Button>
          <Button
            type="dashed"
            size="small"
            onClick={() => {
              trainingStore.id = record?.identity;
              setIsModalOpenUser(true);
            }}
          >
            训练人员管理 
          </Button>
          <TaskArchives
            taskId={record?.identity}
            category_identity={record.identity}
          />
          {record.supplies_status === 1 ? (
            <Button
              type="dashed"
              size="small"
              onClick={() => {
                trainingStore.back(record?.identity, 2);
              }}
            >
              物资归还
            </Button>
          ) : null}
        </Space>
      ),
    },
  ];
  const dele = (record) => {
    trainingStore.deleteItem(record.identity);
  };
  const edit = (record) => {
    let data = {
      ...record,
      start_time: dayjs(record.start_time),
      end_time: dayjs(record.end_time),
    };
    setProjectConfig([
      ...traningConfig,
      {
        type: FormType.cehckboxGroup,
        label: "参与人员选择",
        name: "user_id",
        value: [],
        checkboxData: userList,
        rules: [{ required: true, message: "请选择参与人员!" }],
      },
    ]);
    setIsModalOpen(true);
    formRef.current?.setFieldsValue(data);
    setRecord(data);
    setId(record.id);
  };

  useEffect(() => {
    trainingStore.getlist();
  }, [trainingStore]);
  useEffect(() => {
    trainingCatStore.getlist().then(() => {
      setStash(trainingCatStore.list);
    });
    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 ?? []);
    });
  }, [trainingCatStore]);

  const onFinish = (values: any) => {
    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],
      });
    }
    if (!task_video || task_video.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_video;
    if (!tagId) {
      trainingStore.add(data);
    } else {
      trainingStore.putItem(tagId, data);
    }
    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);
  };
  // 任务发布handler
  const fabu = () => {
    setProjectConfig([
      ...traningConfig,
      {
        type: FormType.cehckboxGroup,
        label: "参与队伍选择",
        name: "team_id",
        value: [],
        checkboxData: userList,
        rules: [{ required: true, message: "请选择参与队伍!" }],
      },
    ]);
    setId(null);
    setIsModalOpen(true);
  };
  const onFinishFailed = () => {};
  // 用户选择回调
  return (
    <div className="contentBox">
      <Space direction="vertical" size="middle" style={{ display: "flex" }}>
        <Space direction="horizontal" size={"middle"}>
          <Button onClick={() => fabu()}>任务发布</Button>
        </Space>
        <BTable
          store={trainingStore}
          columns={columns}
          dataSource={trainingStore.list}
        />
        <Modal
          title={!tagId ? "任务发布" : "任务编辑"}
          width={800}
          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.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>
        </Modal>

        <Modal
          title="训练人员"
          width={1200}
          open={isModalOpenUser}
          footer={null}
          onCancel={() => {
            setIsModalOpenUser(false);
          }}
        >
          <TraningUser />
        </Modal>
      </Space>
    </div>
  );
};

export default inject("trainingStore", "trainingCatStore")(observer(Trainings));
