import useUrlState from "@ahooksjs/use-url-state";
import { Permission } from "@cqsjjb/jjb-common-decorator/permission";
import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, message, Modal, Space } from "antd";
import { useEffect, useRef, useState } from "react";
import FormBuilder from "zy-react-library/components/FormBuilder";
import BackIcon from "zy-react-library/components/Icon/BackIcon";
import DepartmentLeftTree from "zy-react-library/components/LeftTree/Department/Gwj";
import Page from "zy-react-library/components/Page";
import Search from "zy-react-library/components/Search";
import BasicSelectTree from "zy-react-library/components/SelectTree/Basic";
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_ENCLOSED_AREA, NS_ENCLOSED_ENTERPRISE_PERSONNEL_PERMISSIONS } from "~/enumerate/namespace";

function List(props) {
  const [authorizationScopeModalVisible, setAuthorizationScopeModalVisible] = useState(false);
  const [currentInfo, setCurrentInfo] = useState({});

  const [form] = Search.useForm();
  const [urlState, setUrlState] = useUrlState({
    departmentId: "",
    backDepartmentIds: [],
  }, {
    navigateMode: "replace",
    parseOptions: {
      arrayFormat: "index",
    },
    stringifyOptions: {
      arrayFormat: "index",
    },
  });

  const { tableProps, getData } = useTable(props["enclosedEnterprisePersonnelPermissionsList"], {
    form,
    params: () => ({ deptId: urlState.departmentId }),
    manual: true,
  });

  useEffect(() => {
    getData();
  }, [urlState.departmentId]);

  return (
    <Page isShowAllAction={false}>
      <div style={{ display: "flex", gap: 20 }}>
        <div style={{ width: 300 }}>
          <DepartmentLeftTree
            onGetNodePaths={(event) => {
              const departmentId = event.at(-1).id;
              setUrlState({
                departmentId,
                backDepartmentIds: [...urlState.backDepartmentIds, urlState.departmentId],
              });
            }}
          />
        </div>
        <div style={{
          backgroundColor: "rgb(241, 241, 242)",
          width: 10,
          marginTop: "-20px",
          marginBottom: "-20px",
          height: "calc(100vh - 112px)",
        }}
        >
        </div>
        <div style={{ width: "calc(100% - 300px - 50px)" }}>
          <Search labelCol={{ span: 4 }} options={[{ name: "name", label: "姓名" }]} onFinish={getData} form={form} />
          <Table
            toolBarRender={() => (
              <>
                {
                  urlState.departmentId !== "" && (
                    <Button
                      icon={<BackIcon />}
                      onClick={() => {
                        setUrlState({
                          departmentId: urlState.backDepartmentIds.at(-1),
                          backDepartmentIds: urlState.backDepartmentIds.slice(0, -1),
                        });
                      }}
                      ghost
                    >
                      返回
                    </Button>
                  )
                }
              </>
            )}
            columns={[
              { title: "部门", dataIndex: "deptName" },
              { title: "姓名", dataIndex: "name" },
              { title: "岗位", dataIndex: "postName" },
              { title: "手机号", dataIndex: "phone" },
              { title: "车辆数", dataIndex: "vehicleCount" },
              {
                title: "封闭区域权限",
                dataIndex: "mkmjPermission",
                render: (_, record) => record.mkmjPermission === 1 ? "开启" : "关闭",
              },
              {
                title: "是否录入人脸",
                dataIndex: "userFaceUrl",
                render: (_, record) => record.userFaceUrl ? "是" : "否",
              },
              {
                title: "操作",
                width: 200,
                fixed: "right",
                render: (_, record) => (
                  <Space>
                    {props.permission("jgd-ent-permission-authorization-scope") && (
                      <Button
                        type="link"
                        onClick={() => {
                          setAuthorizationScopeModalVisible(true);
                          setCurrentInfo(record);
                        }}
                      >
                        授权范围
                      </Button>
                    )}
                    {props.permission("jgd-ent-permission-personnel-records") && (
                      <Button
                        type="link"
                        onClick={() => {
                          props.history.push(`./personnelRecords?userCard=${ record.userIdCard ? atob(record.userIdCard) : "" }`);
                        }}
                      >
                        人员进出记录
                      </Button>
                    )}
                  </Space>
                ),
              },
            ]}
            {...tableProps}
          />
        </div>
      </div>
      {
        authorizationScopeModalVisible && (
          <AuthorizationScopeModal
            info={currentInfo}
            onCancel={() => {
              setAuthorizationScopeModalVisible(false);
              setCurrentInfo({});
            }}
            getData={getData}
          />
        )
      }
    </Page>
  );
}

const AuthorizationScopeModalComponent = (props) => {
  const [enclosedAreaList, setEnclosedAreaList] = useState([]);

  const closedAreaListTreeRef = useRef([]);

  const [form] = FormBuilder.useForm();

  const getData = async () => {
    const { data } = await props["enclosedEnterprisePersonnelPermissionsInfo"]({ id: props.info.userId });
    form.setFieldsValue({
      ...data,
      mkmjPermission: data.mkmjPermission || 1,
      closedAreaId: (data.areaList || []).map(item => item.closedAreaId),
    });
  };

  const getEnclosedAreaList = async (jurisdictionalCorpId) => {
    const { data } = await props["enclosedAreaDetailListTree"]({ jurisdictionalCorpId });
    setEnclosedAreaList(data);
  };

  useEffect(() => {
    getData();
    getEnclosedAreaList(props.info.corpId);
  }, []);

  const getAreaList = (areaIds) => {
    if (!areaIds || !Array.isArray(areaIds) || areaIds.length === 0) {
      return [];
    }

    const result = [];

    // 递归查找树形结构中的节点
    const findNodesInTree = (tree, ids) => {
      for (const node of tree) {
        // 如果当前节点 ID 在选中列表中，添加到结果集
        if (ids.includes(node.id)) {
          result.push({
            fgsPersonAuthId: props.info.userId,
            closedAreaId: node.id,
            closedAreaName: node.closedAreaName,
          });
        }

        // 如果有子节点，递归查找
        if (node.children && node.children.length > 0) {
          findNodesInTree(node.children, ids);
        }
      }
    };

    // 在树形结构中查找所有选中的节点
    findNodesInTree(closedAreaListTreeRef.current, areaIds);

    return result;
  };

  const onSubmit = (values) => {
    const performSave = async () => {
      const areaList = getAreaList(values.closedAreaId);
      const { success } = await props["enclosedEnterprisePersonnelPermissionsSave"]({
        ...values,
        areaList,
        userId: props.info.userId,
        corpId: props.info.corpId,
        departmentId: props.info.deptId,
      });
      if (success) {
        message.success("操作成功");
        props.onCancel();
        props.getData();
      }
    };

    if (values.mkmjPermission === 2 && props.info.mkmjPermission === 1) {
      Modal.confirm({
        title: "提示",
        content: `确定要给【${props.info.name}】用户关闭门禁权限吗？`,
        onOk: performSave,
      });
    }
    else {
      performSave();
    }
  };

  return (
    <Modal
      open
      title="授权"
      maskClosable={false}
      width={600}
      onCancel={props.onCancel}
      onOk={form.submit}
      confirmLoading={props.enclosedEnterprisePersonnelPermissions.enclosedEnterprisePersonnelPermissionsLoading}
    >
      <FormBuilder
        span={24}
        labelCol={{ span: 8 }}
        showActionButtons={false}
        loading={props.enclosedEnterprisePersonnelPermissions.enclosedEnterprisePersonnelPermissionsLoading}
        onFinish={onSubmit}
        options={[
          {
            name: "mkmjPermission",
            label: "是否授权",
            render: FORM_ITEM_RENDER_ENUM.RADIO,
            items: [{ bianma: 1, name: "是" }, { bianma: 2, name: "否" }],
            componentProps: {
              onChange: () => {
                form.setFieldValue("areaList", []);
              },
            },
          },
          {
            name: "closedAreaId",
            label: "封闭区域",
            render: (
              <BasicSelectTree
                treeData={enclosedAreaList}
                placeholder="封闭区域"
                nameKey="closedAreaName"
                multiple
                onGetData={(data) => {
                  closedAreaListTreeRef.current = data;
                }}
              />
            ),
            dependencies: ["mkmjPermission"],
            hidden: formValues => !(formValues.mkmjPermission === 1),
          },
        ]}
        form={form}
      />
    </Modal>
  );
};

const AuthorizationScopeModal = Connect([NS_ENCLOSED_ENTERPRISE_PERSONNEL_PERMISSIONS, NS_ENCLOSED_AREA], true)(AuthorizationScopeModalComponent);

export default Connect([NS_ENCLOSED_ENTERPRISE_PERSONNEL_PERMISSIONS], true)(Permission(List));
