import { Button, Space, Modal, FormInstance, Form } from "antd";
import { inject, observer } from "mobx-react";
import BTable from "@/components/b_table";
import { useEffect, useState } from "react";
import { Store } from "antd/lib/form/interface";
import SimpleForm from "@/components/form/simple_form";
import React from "react";
import { columns, defaultConfig } from "./config";
import dayjs from "dayjs";
import DebounceSelect from "@/components/form/featch_select";
interface UserValue {
  label: string;
  value: string;
}
const PatrolBrigade = (props: Store) => {
  const { usrStore, patrolBrigadeStore } = 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 [userId, setId] = useState<Number | null>(null);
  const [value, setValue] = useState<UserValue[]>([]);
  const edit = (record) => {
    record = {
      ...record,
      vet_in_time: dayjs(record.vet_in_time),
      vet_out_time: dayjs(record.vet_out_time),
      imageUrl: [{ url: record.imageUrl }],
    };
    setProjectConfig(defaultConfig());
    setIsModalOpen(true);
    setRecord(record);
    setId(record.id);
  };
  const onFinish = async (values: any) => {
    var list:any = []
    values.user_identity.forEach((item)=>{
      list.push({
        note:values.note,
        identity_type:values.identity_type,
        assigned_team:values.assigned_team,
        user_identity: item.value
      })
    })
    if (!userId) {
      let res = await patrolBrigadeStore.add({list:list});
      if (res) {
        setIsModalOpen(false);
      }
    } else {
      let res = await usrStore.putItem(userId, values);
      if (res) {
        setIsModalOpen(false);
      }
    }
  };
  useEffect(() => {
    patrolBrigadeStore.getlist();
  }, [patrolBrigadeStore]);

  const addHandler = () => {
    setProjectConfig(defaultConfig());
    setId(null);
    setRecord(null);
    setIsModalOpen(true);
  };

  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,
      }));
    });
  }
  const onFinishFailed = () => {};
  return (
    <div className="contentBox">
      <Space direction="vertical" size="middle" style={{ display: "flex" }}>
        <Space direction="horizontal" size={"middle"}>
          <Button type="default" onClick={() => addHandler()}>
            绑定巡防成员
          </Button>
        </Space>
        <BTable
          store={patrolBrigadeStore}
          scroll={{ x: "max-content" }}
          columns={[
            ...columns,
            {
              title: "操作",
              fixed: "right",
              with: 200,
              render: (any, record) => (
                <Space wrap>
                  <Button
                    type="dashed"
                    size="small"
                    onClick={() => edit(record)}
                  >
                    编辑
                  </Button>
                </Space>
              ),
            },
          ]}
          dataSource={patrolBrigadeStore.list}
        />

        <Modal
          title={"绑定巡防成员"}
          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={"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(
  "usrStore",
  "patrolBrigadeStore"
)(observer(PatrolBrigade));
