import { Button, Space, Modal, FormInstance, Form, Select } 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 "./user_config";
import "./user.less";
import Move from "./move";
import dayjs from "dayjs";
const { Option } = Select;

const User = (props: Store) => {
  const { usrStore, depStore } = 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 [team, setTeam] = useState<any>(null);
  const [per, setPer] = useState<any>(null);
  const [userId, setId] = useState<Number | null>(null);
  const [depList, setDeplist] = useState<any>([]);

  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(team, per));
    setIsModalOpen(true);
    setRecord(record);
    setId(record.id);
  };
  const onFinish = async (values: any) => {
    let data = {
      ...values,
    };
    if (values.head_img && values.head_img.length > 0) {
      data.head_img = values.head_img[0].url;
    } else {
      data.head_img = "";
    }
    if (!userId) {
      let res = await usrStore.add(data);
      console.log(res);
      if (res) {
        setIsModalOpen(false);
      }
    } else {
      let res = await usrStore.putItem(userId, data);
      if (res) {
        setIsModalOpen(false);
      }
    }
  };
  useEffect(() => {
    usrStore.getlist();
    usrStore.getTeam().then((res) => {
      let data = res.data?.record ?? [];
      for (let index = 0; index < data.length; index++) {
        data[index].label = data[index].name;
        data[index].value = data[index].identity;
      }
      setTeam(data);
    });
    usrStore.getPer().then((res) => {
      let data = res.data?.record ?? [];
      for (let index = 0; index < data.length; index++) {
        data[index].label = data[index].name;
        data[index].value = data[index].identity;
      }
      setPer(data);
    });

    depStore.getlist().then(() => {
      setDeplist(depStore.list);
    });
  }, [usrStore, depStore]);

  const addHandler = () => {
    setProjectConfig(defaultConfig(team, per));
    setId(null);
    setRecord(null)
    setIsModalOpen(true);
  };
  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={usrStore}
          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>
                  <Move />
                  <Button
                    type="dashed"
                    danger
                    size="small"
                    onClick={() => {
                      usrStore.deleteItem(record.id);
                    }}
                  >
                    删除
                  </Button>
                </Space>
              ),
            },
          ]}
          dataSource={usrStore.list}
        />

        <Modal
          title={!userId ? "添加民兵" : "编辑民兵"}
          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="dep_identity"
                label="部门选择"
                name="dep_identity"
              >
                <Select placeholder="">
                  {depList?.map((v: any) => {
                    return (
                      <Option key={v.identity} value={v.identity}>
                        {v.dep_name}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </>
          </SimpleForm>
        </Modal>
      </Space>
    </div>
  );
};

export default inject("usrStore", "depStore")(observer(User));
