import { Permission } from "@cqsjjb/jjb-common-decorator/permission";
import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, message, Modal, Space } from "antd";
import { useEffect, useState } from "react";
import FormBuilder from "zy-react-library/components/FormBuilder";
import AddIcon from "zy-react-library/components/Icon/AddIcon";
import Page from "zy-react-library/components/Page";
import Search from "zy-react-library/components/Search";
import PersonnelSelect from "zy-react-library/components/Select/Personnel/Gwj";
import DepartmentSelectTree from "zy-react-library/components/SelectTree/Department/Gwj";
import Table from "zy-react-library/components/Table";
import { FORM_ITEM_RENDER_ENUM } from "zy-react-library/enum/formItemRender";
import useTable from "zy-react-library/hooks/useTable";
import { NS_APPROVER_USER } from "~/enumerate/namespace";

function ApproverUser(props) {
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [currentId, setCurrentId] = useState("");
  const [form] = Search.useForm();
  const { tableProps, getData } = useTable(props["approvalUserList"], {
    form,
  });
  const onDelete = (record) => {
    Modal.confirm({
      title: "删除确认",
      content: "确定要删除吗？",
      onOk: async () => {
        const { success } = await props["approvalUserDelete"]({ id: record.id });
        if (success) {
          message.success("删除成功");
          getData();
        }
      },
    });
  };

  return (
    <Page isShowAllAction={false}>
      <Search
        labelCol={{ span: 4 }}
        options={[
          { name: "deptId", label: "部门", render: (<DepartmentSelectTree />) },
          { name: "userName", label: "姓名" },
        ]}
        form={form}
        onFinish={getData}
      />
      <Table
        toolBarRender={() => (
          <Space>
            {props.permission(props.addBtn || "jgd-first-level-approver-add") && (
              <Button
                type="primary"
                icon={<AddIcon />}
                onClick={() => setAddModalVisible(true)}
              >
                新增
              </Button>
            )}
          </Space>
        )}
        columns={[
          { title: "部门", dataIndex: "deptName" },
          { title: "姓名", dataIndex: "userName" },
          { title: "岗位", dataIndex: "postName" },
          { title: "审批权限", dataIndex: "approvalPermission", render: (_, record) => {
            const approvalPermission = [];
            if (record.personnelPermissionFlag === 1) {
              approvalPermission.push("人员");
            }
            if (record.vehiclePermissionFlag === 1) {
              approvalPermission.push("车辆");
            }
            if (record.temporaryPermissionFlag === 1) {
              approvalPermission.push("临时访客");
            }
            return approvalPermission.join("，");
          } },
          {
            title: "操作",
            fixed: "right",
            width: 120,
            render: (_, record) => (
              <Space>
                {props.permission(props.editBtn || "jgd-first-level-approver-edit") && (
                  <Button
                    type="link"
                    onClick={() => {
                      setAddModalVisible(true);
                      setCurrentId(record.id);
                    }}
                  >
                    编辑
                  </Button>
                )}
                {props.permission(props.delBtn || "jgd-first-level-approver-del") && (
                  <Button
                    type="link"
                    danger
                    onClick={() => onDelete(record)}
                  >
                    删除
                  </Button>
                )}
              </Space>
            ),
          },
        ]}
        {...tableProps}
      />

      {addModalVisible && (
        <AddModal
          onCancel={() => {
            setAddModalVisible(false);
            setCurrentId("");
          }}
          checkExistByUserId={props["checkExistByUserId"]}
          id={currentId}
          getData={getData}
        />
      )}
    </Page>
  );
}

function AddModalComponent(props) {
  const [form] = FormBuilder.useForm();
  const personUnderDepartmentId = FormBuilder.useWatch("deptId", form);

  const [oldApproverType, setOldApproverType] = useState([]);

  const getData = async () => {
    const { data } = await props["approvalUserInfo"]({ id: props.id });
    const approverType = [
      data.personnelPermissionFlag === 1 ? 1 : null,
      data.vehiclePermissionFlag === 1 ? 0 : null,
      data.temporaryPermissionFlag === 1 ? 2 : null,
    ].filter(item => item !== null);
    form.setFieldsValue({
      ...data,
      approverType,
    });
    setOldApproverType(approverType);
  };

  useEffect(() => {
    props.id && getData();
  }, []);

  const onSubmit = async (values) => {
    const { approverType, ...rest } = values;
    const submitData = {
      ...rest,
      personnelPermissionFlag: approverType?.includes(1) ? 1 : 0,
      vehiclePermissionFlag: approverType?.includes(0) ? 1 : 0,
      temporaryPermissionFlag: approverType?.includes(2) ? 1 : 0,
      id: props.id,
    };
    const { success } = await props[!props.id ? "approvalUserAdd" : "approvalUserUpdate"](submitData);
    if (success) {
      props.onCancel();
      props.getData();
      message.success(`${props.id ? "编辑" : "新增"}成功`);
    }
  };

  return (
    <Modal
      open
      onCancel={props.onCancel}
      onOk={form.submit}
      title={props.id ? "编辑" : "新增"}
      maskClosable={false}
      confirmLoading={props.approverUser.approvalUserLoading}
      width={600}
    >
      <FormBuilder
        labelCol={{ span: 8 }}
        form={form}
        span={24}
        loading={props.approverUser.approvalUserLoading}
        onFinish={onSubmit}
        showActionButtons={false}
        options={[
          {
            name: "deptId",
            label: "部门",
            render: (
              <DepartmentSelectTree
                onGetLabel={(label) => {
                  form.setFieldValue("deptName", label);
                }}
                onChange={() => {


                  form.setFieldValue("userId", "");
                  form.setFieldValue("userName", "");
                  form.setFieldValue("corpId", "");
                  form.setFieldValue("corpName", "");
                  form.setFieldValue("postId", "");
                  form.setFieldValue("postName", "");
                }}
                disabled={!!props.id}
              />
            ),
          },
          { name: "deptName", label: "部门名称", onlyForLabel: true },
          {
            name: "userId",
            label: "审批人",
            rules: [
              {
                validateTrigger: "onChange",
                validator: async (_, value) => {
                  if (!value || props.id) {
                    return Promise.resolve();
                  }
                  const { data } = await props.checkExistByUserId({ userId: value });
                  if (data?.available) {
                    return Promise.resolve();
                  }
                  if(!data.available){
                    form.setFieldValue("userId", undefined);
                  }
                  throw new Error(data?.availableMessage || "该审批人已录入，不可重复添加");
                },
              },
            ],
            render: (
              <PersonnelSelect
                params={{ departmentId: personUnderDepartmentId,employmentFlag: 1 }}
                onGetLabel={(label) => {
                  form.setFieldValue("userName", label);
                }}

                onGetOption={(option) => {

                  form.setFieldValue("corpId", option.corpinfoId);
                  form.setFieldValue("corpName", option.corpinfoName);
                  form.setFieldValue("postId", option.postId);
                  form.setFieldValue("postName", option.postName);
                }}
                disabled={!!props.id}

              />
            ),

          },
          { name: "userName", label: "审批人名称", onlyForLabel: true },
          { name: "corpId", label: "企业ID", onlyForLabel: true },
          { name: "corpName", label: "企业名称", onlyForLabel: true },
          { name: "postId", label: "岗位ID", onlyForLabel: true },
          { name: "postName", label: "岗位名称", onlyForLabel: true },
          {
            name: "approverType",
            label: "审批权限",
            render: FORM_ITEM_RENDER_ENUM.CHECKBOX,
            items: [
              { bianma: 1, name: "人员", disabled: oldApproverType.includes(1) },
              { bianma: 0, name: "车辆", disabled: oldApproverType.includes(0) },
              { bianma: 2, name: "临时访客", disabled: oldApproverType.includes(2) },
            ],
          },
        ]}
      />
    </Modal>
  );
}

const AddModal = Connect([NS_APPROVER_USER], true)(AddModalComponent);
export default Connect([NS_APPROVER_USER], true)(Permission(ApproverUser));
