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, userSerchConfig } 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 serchFormRef = 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) => {
    let records = {
      ...record,
      vet_in_time: dayjs(record.vet_in_time),
      vet_out_time: dayjs(record.vet_out_time),
      team_link_user:record.team.map(item => item.team_identity),
      pers_link_user:record.pers.map(item=>item.pers_identity),
      head_img:[{ url: record.head_img }],
    };
    let config = defaultConfig(team, per)
    config.forEach((e:any)=>{
      if (e.name==="head_img"){
        e.value =[{ url: record.head_img }];
      }
    })
    setProjectConfig(config);
    setIsModalOpen(true);
    setRecord(records);
    setId(records.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);
      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 onSerchFinish = (values: any) => {
    usrStore.getlist(values);
  };
  const onFinishFailed = () => {};
  return (
    <div className="contentBox">
      <Space direction="vertical" size="middle" style={{ display: "flex" }}>
        <Space
          direction="horizontal"
          size={"middle"}
          style={{ display: "flex", justifyContent: "space-between" }}
        >
          <Button type="default" onClick={() => addHandler()}>
            添加民兵
          </Button>
          <SimpleForm
            formRef={serchFormRef}
            createCallback={() => {}}
            formName="serch_basic"
            colProps={30}
            span={8}
            layout="inline"
            formDatas={userSerchConfig}
            onFinish={onSerchFinish}
            initialValues={true}
            onFinishFailed={onFinishFailed}
          >
            <Space>
              <Button
                type="primary"
                onClick={() => {
                  serchFormRef.current?.submit();
                }}
              >
                查询
              </Button>
              <Button
                onClick={() => {
                  serchFormRef.current?.resetFields();
                  serchFormRef.current?.submit();
                }}
              >
                重置
              </Button>
            </Space>
          </SimpleForm>
        </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 id={record.identity} />
                  <Button
                    type="dashed"
                    danger
                    size="small"
                    onClick={() => {
                      usrStore.deleteItem(record.id);
                    }}
                  >
                    删除
                  </Button>
                  <Button
                    type="dashed"
                    size="small"
                    onClick={() => {
                      usrStore.reSetPwd(record.identity);
                    }}
                  >
                    重置密码
                  </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));
