import {
  Button,
  Space,
  Modal,
  FormInstance,
  Form,
  Select,
  GetProps,
  Tree,
} from "antd";
import { inject, observer } from "mobx-react";
import { useEffect, useState } from "react";
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 DirectoryTree from "antd/lib/tree/DirectoryTree";
const { Option } = Select;
const Dep = (props: Store) => {
  const { 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 [org, setOrg] = useState<any>(null);
  const [tagId, setId] = useState<Number | null>(null);

  const edit = (record) => {
    let data = {
      ...record,
      head_img: [{ url: record.head_img }],
    };
    setProjectConfig(defaultConfig);
    setIsModalOpen(true);
    formRef.current?.setFieldsValue(data);
    setRecord(data);
    setId(record.id);
  };
  const onFinish =async (values: any) => {
    if (!tagId) {
      await depStore.add(values);
    } else {
      await depStore.putItem(tagId, values);
    }
    await getOrg();
    setIsModalOpen(false);
  };
  useEffect(() => {
    getOrg();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [depStore]);

  const getOrg = () => {
    depStore.getOrg().then((v) => {
      let morg = v.data.record;
      setOrg(morg);
    });
  };

  const defaultConfig = [
    {
      type: "input",
      label: "部门名称",
      name: "dep_name",
      value: "",
      rules: [{ required: true, message: "请输入部门名称!" }],
    },
    {
      type: "input",
      label: "部门描述",
      name: "remark",
      value: "",
      rules: [{ required: true, message: "请输入部门描述" }],
    },
    {
      type: FormType.radio,
      label: "第三方机构",
      name: "other",
      radioData: [
        {
          key: "是",
          val: 1,
        },
        {
          key: "否",
          val: 2,
        },
      ],
      value: "",
      rules: [{ required: true, message: "请输入部门描述" }],
    },
  ];
  const onFinishFailed = () => {};
  type DirectoryTreeProps = GetProps<typeof Tree.DirectoryTree>;

  const onSelect: DirectoryTreeProps["onSelect"] = (keys, info) => {
    // console.log("Trigger Select", keys, info);
  };

  const onExpand: DirectoryTreeProps["onExpand"] = (keys, info) => {
    // console.log("Trigger Expand", keys, info);
  };

  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>
        <DirectoryTree
          multiple
          defaultExpandAll
          onSelect={onSelect}
          onExpand={onExpand}
          treeData={org}
          titleRender={(nodeData: any) => {
            console.log(nodeData)
            return (
              <>
                {nodeData.dep_name}
                <span
                  style={{ marginLeft: "10px", color: "blue" }}
                  onClick={() => {
                    edit(nodeData);
                  }}
                >
                  编辑
                </span>
                <span
                  style={{ marginLeft: "10px", color: "blue" }}
                  onClick={() => {
                    depStore.deleteItem(nodeData.id).then(()=>{
                      getOrg()
                    });
                  }}
                >
                  删除
                </span>
              </>
            );
          }}
        />
        <Modal
          title={!record ? "添加部门" : "编辑部门"}
          width={800}
          open={isModalOpen}
          afterClose={() => formRef.current?.resetFields()}
          onOk={() => formRef.current?.submit()}
          okText="确定"
          cancelText="取消"
          onCancel={() => {
            setId(null);
            setRecord(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="pdep_id" label="上级部门" name="pdep_id">
                <Select placeholder="">
                  {depStore.list?.map((v: any) => {
                    return (
                      <Option key={v.id} value={v.id}>
                        {v.dep_name}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </>
          </SimpleForm>
        </Modal>
      </Space>
    </div>
  );
};

export default inject("depStore")(observer(Dep));
