import { Button, Space, Modal, FormInstance, Form } 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 { FormType } from "@/components/form/interface";
import baseHttp from "@/service/base";
import dayjs from "dayjs";
import DebounceSelect from "@/components/form/featch_select";
interface UserValue {
  label: string;
  value: string;
}
const Patrol = (props: Store) => {
  const { patrolStore, usrStore } = 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 [, setUserList] = useState<Array<any>>([]);
  const [value] = useState<UserValue[]>([]);

  const columns: ColumnsType<UserDataType> = [
    { title: "任务标题", dataIndex: "title" },
    { title: "任务描述", dataIndex: "patrol_desc" },
    { title: "任务地点", dataIndex: "address" },
    { title: "任务开始时间", dataIndex: "start_time" },
    { title: "任务结束时间", dataIndex: "end_time" },
    { title: "任务积分", dataIndex: "score" },
    {
      title: "完成状态",
      dataIndex: "status",
      render: (status) =>
        status === 0 ? (
          <span>进行中</span>
        ) : (
          <span style={{ color: "green" }}>已完成</span>
        ),
    },
    {
      title: "操作",
      dataIndex: "id",
      render: (any, record) => (
        <Space wrap>
          <Button
            type="dashed"
            size="small"
            onClick={() => {
              edit(record);
            }}
          >
            编辑
          </Button>
          {record.status === 0 ? (
            <Button
              type="dashed"
              size="small"
              onClick={() => {
                patrolStore.fish(record.identity);
              }}
            >
              完成
            </Button>
          ) : null}
          <Button
            type="dashed"
            danger
            size="small"
            onClick={() => {
              patrolStore.deleteItem(record.identity);
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];
  const edit = (record) => {
    let data = {
      ...record,
      start_time: dayjs(record.start_time),
      end_time: dayjs(record.end_time),
    };
    setProjectConfig(defaultConfig);
    setIsModalOpen(true);
    formRef.current?.setFieldsValue(data);
    setRecord(data);
    setId(record.id);
  };
  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],
      });
    }
    let data = {
      ...values,
      score: Number(values.score ?? 0),
      user_identity: values.user_identity.map((item) => item.value),
    };
    data.task_video = task_video;
    if (!tagId) {
      patrolStore.add(data);
    } else {
      patrolStore.putItem(tagId, data);
    }
    setIsModalOpen(false);
  };
  useEffect(() => {
    patrolStore.getlist();
    baseHttp.get("/v1/user/list", null).then((res) => {
      let data = res.data?.record ?? [];
      data.forEach((item) => {
        item.label = item.user_name;
        item.value = item.identity;
      });
      setUserList(data ?? []);
    });
  }, [patrolStore]);
  const defaultConfig = [
    {
      type: FormType.input,
      label: "任务标题",
      name: "title",
      value: "",
      rules: [{ required: true, message: "请输入任务标题!" }],
    },
    {
      type: FormType.input,
      label: "任务描述",
      name: "patrol_desc",
      value: "",
    },
    {
      type: FormType.input,
      label: "巡逻地点",
      name: "address",
      value: "",
      rules: [{ required: true, message: "请输入巡逻地点!" }],
    },
    {
      type: FormType.date,
      label: "开始时间",
      name: "start_time",
      value: "",
      rules: [{ required: true, message: "请输入任务开始时间!" }],
    },
    {
      type: FormType.date,
      label: "任务结束时间",
      name: "end_time",
      value: "",
      rules: [{ required: true, message: "请选择任务结束时间!" }],
    },
    {
      type: FormType.input,
      label: "任务积分设置",
      name: "score",
      value: "",
      rules: [{ required: true, message: "请输入任务积分!" }],
    },
    {
      type: FormType.treeVideo,
      label: "视频地址",
      name: "task_video",
      value: [],
      rules: [{ required: true, message: "请选择视频地址!" }],
    },
    // {
    //   type: FormType.cehckboxGroup,
    //   label: "任务参与人",
    //   name: "user_identity",
    //   value: [],
    //   checkboxData: userList,
    //   rules: [{ required: true, message: "请选择参与人!" }],
    // },
  ];
  const onFinishFailed = () => {};
  async function fetchUserList(username: string): Promise<UserValue[]> {
    return usrStore.serchUser(username).then((res) => {
      return res.data.record.map((item) => ({
        label: item.user_name,
        value: item.identity,
      }));
    });
  }
  // 用户选择回调
  return (
    <div className="contentBox">
      <Space direction="vertical" size="middle" style={{ display: "flex" }}>
        <Space direction="horizontal" size={"middle"}>
          <Button
            type="default"
            onClick={() => {
              setProjectConfig(defaultConfig);
              setId(null);
              setIsModalOpen(true);
            }}
          >
            任务发布
          </Button>
        </Space>

        <BTable
          store={patrolStore}
          columns={columns}
          dataSource={patrolStore.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={12}
            subBtnName="提交"
            formDatas={projectConfig}
            onFinish={onFinish}
            initialValues={true}
            onFinishFailed={onFinishFailed}
            childrenPosi={false}
          >
            <>
              <Form.Item
                key={"user_identity"}
                label={"巡逻人员"}
                name={"user_identity"}
                rules={[{ required: true, message: "请选择巡逻人员!" }]}
              >
                <DebounceSelect
                  mode="multiple"
                  value={value}
                  placeholder="输入搜索"
                  fetchOptions={fetchUserList}
                  style={{ width: "100%" }}
                />
              </Form.Item>
            </>
          </SimpleForm>
        </Modal>
      </Space>
    </div>
  );
};

export default inject("patrolStore", "usrStore")(observer(Patrol));
