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, 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 DictionarySelect from "zy-react-library/components/Select/Dictionary";
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_STOCK_PERSONNEL_AND_VEHICLES } from "~/enumerate/namespace";

function List(props) {
  const [authorizationModalVisible, setAuthorizationModalVisible] = 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["stockPersonnelAndVehiclesList"], {
    form,
    params: () => ({ departmentId: 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: "departmentName" },
              { title: "姓名", dataIndex: "userName" },
              { title: "岗位", dataIndex: "postName" },
              { title: "手机号", dataIndex: "userPhone" },
              { title: "车辆数", dataIndex: "vehicleCount" },
              { title: "门禁权限", dataIndex: "mkmjPermission", render: (_, record) => record.mkmjPermission === 1 ? "开启" : "关闭" },
              { title: "是否录入人脸", dataIndex: "userFaceUrl", render: (_, record) => record.userFaceUrl ? "是" : "否" },
              { title: "是否录入身份证号", dataIndex: "userCard", render: (_, record) => record.userCard ? "是" : "否" },
              {
                title: "操作",
                width: 300,
                fixed: "right",
                render: (_, record) => (
                  <Space>
                    {props.permission(props.authorizationScopeBtn || "jgd-io-stock-pv-edit") && (
                      <Button
                        type="link"
                        disabled={!record.userFaceUrl || !record.userCard}
                        onClick={() => {
                          setCurrentInfo(record);
                          setAuthorizationModalVisible(true);
                        }}
                      >
                        授权范围
                      </Button>
                    )}
                    {props.permission(props.personnelRecordsBtn || "jgd-io-stock-pv-show") && (
                      <Button
                        type="link"
                        onClick={() => {
                        // TODO
                          props.history.push(`./personnelRecords?userCard=${record.userCard}`);
                        }}
                      >
                        人员进出记录
                      </Button>
                    )}
                    {props.permission(props.vehicleManagementBtn || "jgd-io-stock-pv-add") && (
                      <Button
                        type="link"
                        onClick={() => {
                          const params = new URLSearchParams({
                            id: record.userId || "",
                            userName: record.userName || "",
                            departmentId: record.departmentId || "",
                            departmentName: record.departmentName || "",
                            corpinfoId: record.corpinfoId || "",
                            corpName: record.corpName || "",
                          }).toString();
                          props.history.push(`./vehicleManagement/list?${params}`);
                        }}
                      >
                        车辆管理
                      </Button>
                    )}
                  </Space>
                ),
              },
            ]}
            {...tableProps}
          />
        </div>
      </div>
      {
        authorizationModalVisible && (
          <AuthorizationModalVisible
            onCancel={() => {
              setAuthorizationModalVisible(false);
              setCurrentInfo("");
            }}
            info={currentInfo}
            personBelongType={props.personBelongType}
            getData={getData}
          />
        )
      }
    </Page>
  );
}

const AuthorizationModalVisibleComponent = (props) => {
  const [form] = FormBuilder.useForm();
  let authorizationArea = [];

  try {
    const gateLevelAuthArea = typeof props.info.gateLevelAuthArea === "string"
      ? JSON.parse(props.info.gateLevelAuthArea)
      : props.info.gateLevelAuthArea;
    authorizationArea = Array.isArray(gateLevelAuthArea?.area) ? gateLevelAuthArea.area : [];
  }
  catch {
    authorizationArea = [];
  }

  const onSubmit = async (values) => {
    const { userId, corpinfoId, corpName, departmentId, departmentName, userName, userFaceUrl, userPhone, userCard } = props.info;
    const { success } = await props["stockPersonnelAndVehiclesAuthorization"]({
      ...values,
      userId,
      corpinfoId,
      corpName,
      departmentId,
      departmentName,
      userName,
      userFaceUrl,
      userPhone,
      userCard,
      personBelongType: props.personBelongType || 1,
      gateLevelAuthArea: JSON.stringify({ area: values.area }),
    });
    if (success) {
      message.success("操作成功");
      props.onCancel();
      props.getData();
    }
  };

  return (
    <Modal
      title="授权范围"
      open
      width={600}
      maskClosable={false}
      onCancel={props.onCancel}
      onOk={form.submit}
      confirmLoading={props.stockPersonnelAndVehicles.stockPersonnelAndVehiclesLoading}
    >
      <FormBuilder
        loading={props.stockPersonnelAndVehicles.stockPersonnelAndVehiclesLoading}
        form={form}
        showActionButtons={false}
        onFinish={onSubmit}
        span={24}
        labelCol={{ span: 8 }}
        values={{
          mkmjPermission: String(props.info.mkmjPermission || 1),
          gateLevelAuthArea: authorizationArea[0]?.bianma,
          area: authorizationArea,
        }}
        options={[
          {
            name: "mkmjPermission",
            label: "是否授权",
            render: FORM_ITEM_RENDER_ENUM.RADIO,
            items: [{ bianma: "1", name: "是" }, { bianma: "2", name: "否" }],
          },
          {
            name: "gateLevelAuthArea",
            label: "授权港区",
            render: (
              <DictionarySelect
                dictValue="HG_AUTH_AREA"
                onGetOption={(option) => {
                  const area = option ? [{ value: option.dictLabel, bianma: option.dictValue }] : [];
                  form.setFieldValue("area", area);
                }}
              />
            ),
            dependencies: ["mkmjPermission"],
            hidden: formValues => !(formValues.mkmjPermission === "1"),
          },
          { name: "area", label: "访问港区", onlyForLabel: true },
        ]}
      />
    </Modal>
  );
};

const AuthorizationModalVisible = Connect([NS_STOCK_PERSONNEL_AND_VEHICLES], true)(AuthorizationModalVisibleComponent);

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