/*
 * @Author: cclu
 * @Date: 2021-12-13 11:01:23
 * @LastEditTime: 2024-08-30 10:20:24
 * @LastEditors: cclu 1106109051@qq.com
 * @Description: 角色管理
 * @FilePath: \cloud-platform\src\pages\Setting\Roles\index.tsx
 */

import ProTable from "@ant-design/pro-table";
import useRequest from "@ahooksjs/use-request";
import React, { useState, useRef } from "react";
import { PlusOutlined, SearchOutlined } from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-layout";
import ProDescriptions from "@ant-design/pro-descriptions";
import {
  Button,
  Drawer,
  Form,
  message,
  Popconfirm,
  TreeSelect,
  Switch,
  Row,
  Col,
  Tree,
  Card,
  Space,
  Badge,
  Tabs
} from 'antd';
import { ModalForm, ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea } from "@ant-design/pro-form";

import type { FormInstance } from 'antd';
import type { SystemRoleModel } from "./data";
import type { CurrentUser } from '@/models/user';
import type { ConnectState } from "@/models/connect";
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { ProDescriptionsItemProps } from "@ant-design/pro-descriptions"

import {
  deleteRole,
  getRoleList,
  updataRole,
  getSystemMenuTree,
  getSystemRoleDetail,
  getSystemRoleCount,
  handleSynchroUserSystemRoleDetailList,
  newUpdataRole, handleGetUserList, handleGetSYSTEMROLEDetail
} from './service'

import { connect } from "umi";
import { getOnwer } from "@/services/options";
import ProCard from "@ant-design/pro-card";
import { getUserList, getUserTypeTree } from "@/pages/Setting/Users/service";
import type { UserModel } from "@/pages/Setting/Users/data";
import './style.less'
import moment from "moment";
import { synchroBehaviorRecord } from "@/services/user";
import session from "@/utils/session";

/**
 * @description: 新增或更新角色信息
 * @param {item} 角色对象
 * @return {boolean} 是否成功
 */
const handleAddUpdate = async (item: SystemRoleModel) => {
  const loading = message.loading("正在提交...")

  const result = await newUpdataRole(item as SystemRoleModel)
  loading()
  if (result.Result_Code !== 100) {
    message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`)
    return false
  }



  message.success(item.SYSTEMROLE_ID ? "更新成功！" : "新建成功！")
  return result
}
/**
 * @description: 删除角色
 * @param {string} SYSTEMROLE_ID 角色id
 * @return {boolean}
 */
const handleDelete = async (SYSTEMROLE_ID: number) => {
  const hide = message.loading('正在删除...');
  try {
    const result = await deleteRole(SYSTEMROLE_ID)

    hide();
    if (result.Result_Code !== 100) {
      message.error(`${result.Result_Code}:删除失败`)
      return false
    }
    message.success("删除成功！")
    return true
  } catch (error) {
    hide();
    message.error("删除失败")
    return false
  }
}

// 数字角标生成
const renderBadge = (count: number, active = false) => {
  return (
    <Badge
      count={count}
      style={{
        marginTop: -2,
        marginLeft: 4,
        color: active ? '#1890FF' : '#999',
        backgroundColor: active ? '#E6F7FF' : '#eee',
      }}
    />
  );
};

// 角色管理 页面主体函数
const RoleList: React.FC<{ currentUser: CurrentUser | undefined }> = (props) => {

  const { currentUser } = props
  const actionRef = useRef<ActionType>();
  const actionUserRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const formUserRef = useRef<FormInstance>();
  const [roleTree, setRoleTree] = useState<any[]>(); // 树结构数据菜单 用于弹出编辑时选择上级角色
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<SystemRoleModel | any>(); // 当前选中的行 角色
  const [rowDetail, setRowDetail] = useState<any>(); // 当前选中的行 角色
  const [roleCheckedMenu, setRoleCheckedMenu] = useState<React.Key[]>(); // 当前选中的行 角色 roleCheckedMenu 格式为[2-x,1-x] 2-为模块，1-为menu
  const [createModalVisible, handleModalVisible] = useState<boolean>(false); // 分布更新窗口的弹窗

  // 判断是否点击了表格的查询按钮
  const clickTableBtnRef = useRef<boolean>(false)

  const [activeKey, setActiveKey] = useState<React.Key>(`${currentUser?.UserPattern}`); // 树结构数据分类 用于弹出编辑时选择上级
  // 更上一层的tab选择
  const [bigTabSelect, setBigTabSelect] = useState<string>('1')
  // 查询系统角色数量
  const { loading: typeCountLoading, data: typeCount } = useRequest(getSystemRoleCount)
  // 根据角色id查询权限树
  const { run: getRoleMenu, data: roleMenuTree } = useRequest(async (SystemRoleId?: number) => {
    const data = await getSystemMenuTree(SystemRoleId ? `${SystemRoleId}` : '')
    return data
  }, { manual: true })

  // const ueserCloudTab = currentUser?.UserPattern === 9000 ? leftTab : currentUser?.UserPattern === 1000 ?[{ key: `1000`, name: '业主' },{ key: `4000`, name: '供应商' }]:leftTab.filter(n => n.key === `${currentUser?.UserPattern}`)
  // const { run: getUserTypeMenu, loading: typeLoading, data: userTypeTree } = useRequest((type) => getUserTypeTree({ UserTypePattern: type }))
  const [userTypeId, setUserTypeId] = useState<any>();
  // 请求角色树的loading
  const [roleLoading, setRoleLoading] = useState<boolean>(false)
  // 角色树数据
  const [roleTreeData, setRoleTreeData] = useState<any>()
  // 角色类型树默认选择
  const [defaultRoleTree, setDefaultRoleTree] = useState<any>()
  // 选择行的详情
  const [selectRowDetail, setSelectRowDetail] = useState<any>()
  // 默认选择的人
  const [defaultSelectRole, setDefaultSelectRole] = useState<any>()
  // 用戶列表
  const [userList, setUserList] = useState<any>()
  // 搜索条件
  const [searchParams, setSearchParams] = useState<any>()
  // 用戶列表数据
  const [userTableData, setUserTableData] = useState<any>()
  // loading
  const [tableLoading, setTableLoading] = useState<boolean>(false)
  // 当前新增觉得 可以选的父级角色的列表
  const [currentSelectParentRoleList, setCurrentSelectParentRoleList] = useState<any>([])

  // 表格配置列数据
  const columns: ProColumns<SystemRoleModel>[] = [
    {
      title: '角色名称',
      dataIndex: 'SYSTEMROLE_NAME',
      hideInDescriptions: true,
      render: (_, record) => {
        return <a key="fname" onClick={() => {
          getRoleMenu(record.SYSTEMROLE_ID)
          setCurrentRow(record)
          setShowDetail(true)
        }}>{_}</a>
      }
    },
    {
      title: '业主单位',
      dataIndex: 'SYSTEMROLE_PROVINCE',
      hideInSearch: activeKey !== '1000',
      hideInTable: activeKey !== '1000',
      request: async () => {
        const options = await getOnwer()
        return options;
      },
      span: 2,
    },
    {
      title: '显示顺序',
      dataIndex: 'SYSTEMROLE_INDEX',
      hideInSearch: true
    },
    {
      title: '状态',
      dataIndex: 'ShowStatus',
      // hideInSearch: true,
      hideInTable: true,
      filters: true,
      valueType: 'select',
      initialValue: "1",
      valueEnum: {
        "all": { text: '全部', status: 'Default' },
        "0": { text: '无效', status: 'Default' },
        "1": { text: '有效', status: 'Processing' },
      },

    },
    {
      title: '状态',
      dataIndex: 'SYSTEMROLE_STATUS',
      hideInSearch: true,
      filters: true,
      valueType: 'select',
      initialValue: "1",
      valueEnum: {
        "all": { text: '全部', status: 'Default' },
        "0": { text: '无效', status: 'Default' },
        "1": { text: '有效', status: 'Processing' },
      },

    },
    {
      title: '说明',
      dataIndex: 'SYSTEMROLE_DESC',
      hideInSearch: true,
      span: 2,
    },
    {
      title: '操作',
      valueType: 'option',
      dataIndex: 'option',
      hideInDescriptions: true,
      render: (text, record) => {
        if (currentUser?.UserPattern === 9000 || (record?.SYSTEMROLE_PROVINCE && record?.SYSTEMROLE_ID !== currentUser?.TopSystemRoleId) || bigTabSelect === '2')
          return (<Space>
            <a
              key="editable"
              onClick={async () => {
                if (showDetail) {
                  setShowDetail(false);
                }
                getRoleMenu(record?.SYSTEMROLE_PID)
                const roleDetail = await getSystemRoleDetail(record.SYSTEMROLE_ID) // 获取当前角色的 权限配置

                const rolekeys = roleDetail.SystemModuleList ? roleDetail?.SystemModuleList.map((n: number) => `2-${n}`) : []
                setRoleCheckedMenu(rolekeys);
                console.log('currentRow', { ...roleDetail })
                setCurrentRow({ ...roleDetail });
                handleModalVisible(true);

              }}
            >
              编辑
            </a>
            <a
              key="editable"
              onClick={async () => {
                handleModalVisible(true);
                if (showDetail) {

                  setShowDetail(false);
                }
                setCurrentRow({ SYSTEMROLE_PID: record?.SYSTEMROLE_ID, SYSTEMROLE_STATUS: 1 }); // 配置子角色的父级id为当前行id
                getRoleMenu(record?.SYSTEMROLE_ID) // 获取当前父级的可使用权限
                setRoleCheckedMenu([])
              }}
            >
              添加子角色
            </a>
            <Popconfirm  // 删除按钮功能
              title="确认删除该项目记录吗?"
              onConfirm={async () => {
                if (record) {

                  const { SYSTEMROLE_ID } = record
                  const success = (SYSTEMROLE_ID ? await handleDelete(SYSTEMROLE_ID) : false)
                  if (success) {
                    if (actionRef.current) {
                      actionRef.current.reload();
                    }
                    handleModalVisible(false)
                    setCurrentRow(undefined)
                  }
                }
              }}
            >
              <a>无效</a>
            </Popconfirm>
          </Space>
          )
        return (<a
          key="editable"
          onClick={async () => {
            handleModalVisible(true);
            if (showDetail) {

              setShowDetail(false);
            }
            setCurrentRow({ SYSTEMROLE_PID: record?.SYSTEMROLE_ID, SYSTEMROLE_STATUS: 1 }); // 配置子角色的父级id为当前行id
            getRoleMenu(record?.SYSTEMROLE_ID) // 获取当前父级的可使用权限
            setRoleCheckedMenu([])
          }}
        >
          添加子角色
        </a>)
      }
    }
  ]

  // 选择人表格的columns
  const userColumns = [
    {
      title: '查询账号',
      dataIndex: 'searchKey',
      hideInDescriptions: true,
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入账号/用户名称/业主单位/手机号'
      }
    },
    {
      title: '账号',
      dataIndex: 'USER_PASSPORT',
      hideInSearch: true,
    },
    {
      title: '用户名称',
      dataIndex: 'USER_NAME',
      hideInDescriptions: true,
      hideInSearch: true,
    },
    {
      title: '手机号',
      dataIndex: 'USER_MOBILEPHONE',
      hideInSearch: true
    },
    {
      title: '状态',
      dataIndex: 'USER_STATUS',
      // hideInSearch: true,
      filters: true,
      onFilter: true,
      valueType: 'select',
      initialValue: "1",
      valueEnum: {
        "all": { text: '全部', status: 'Default' },
        "0": { text: '无效', status: 'Default' },
        "1": { text: '有效', status: 'Processing' },
      },
    },
    {
      title: '业主单位',
      dataIndex: 'PROVINCE_UNIT',
      hideInSearch: true,
      width: 150,
      ellipsis: true,
    },
  ]

  // 拿到角色的左边树
  const handleGetRoleTree = async (type: any) => {
    if (!type) {
      return
    }
    setRoleLoading(true)
    const data = await getUserTypeTree({ UserTypePattern: type })
    setRoleLoading(false)
    console.log('data', data)
    if (data && data.length > 0) {
      setRoleTreeData(data)
    } else {
      setRoleTreeData([])
    }
  }
  // 拿到用户列表数据
  const handleGetUserTableData = async (tableTab?: any, typeId?: any, params?: any) => {
    if (!typeId) {
      return
    }
    setTableLoading(true)
    const req = {
      ...params,
      USER_PATTERN: tableTab,
      UserTypeIds: typeId || '',
      current: 1,
      pageSize: 999999,
      keyWord: params?.searchKey ? { key: "USER_PASSPORT,USER_NAME,USER_MOBILEPHONE,PROVINCE_UNIT", value: params?.searchKey } : null, // 关键词查询
    }
    const data = await getUserList(req)
    if (data.data && data.data.length > 0) {
      setUserTableData(data.data)
      console.log('data.data', data.data)
      if (currentRow?.UserIds && currentRow?.UserIds.length > 0) {
        const list: any = []
        currentRow?.UserIds.forEach((item: any) => {
          data.data.forEach((subItem: any) => {
            if (item === subItem.USER_ID) {
              list.push(subItem)
            }
          })
        })
        setSelectRowDetail(list)
      }
    } else {
      setUserTableData([])
    }
    setTableLoading(false)
    clickTableBtnRef.current = false
  }

  // 记录用户操作行为
  const handleRecordUser = () => {
    const baseInfo = session.get('basicInfo')
    const browser = session.get('browserVersion')
    const systemInfo = session.get('systemBasin')
    synchroBehaviorRecord({
      USER_ID: currentUser?.ID,
      USER_NAME: currentUser?.Name,
      USER_PASSPORT: currentUser?.UserName,
      USER_MOBILEPHONE: currentUser?.UserMobilephone,
      BEHAVIORRECORD_TYPE: 1001,
      BEHAVIORRECORD_EXPLAIN: '修改了角色',
      BEHAVIORRECORD_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
      SOURCE_PLATFORM: '驿商云平台',
      USER_LOGINIP: baseInfo?.ip ? baseInfo?.ip : '',
      USER_LOGINPLACE: `${baseInfo?.prov ? baseInfo?.prov : ''}${baseInfo?.prov && baseInfo?.city ? '-' : ''}${baseInfo?.city ? baseInfo?.city : ''}`,
      BROWSER_VERSION: browser || '',
      OPERATING_SYSTEM: systemInfo || '',
    })
  }


  return (<PageContainer header={{
    title: '',
    breadcrumb: {},
  }}>


    <ProTable<SystemRoleModel>
      headerTitle={<div>
        <div style={{ width: '100%', marginBottom: '16px' }}>
          <Tabs
            activeKey={bigTabSelect}
            onChange={(e) => {
              console.log('e', e)
              setBigTabSelect(e)
              actionRef.current?.reload()
            }}
            items={[{ label: '模块角色', key: '1' }, { label: '用户角色', key: '2' }]}
          />
        </div>
        <div style={{ width: '100%', boxSizing: 'border-box', paddingLeft: '16px' }}>
          <Tabs
            activeKey={activeKey}
            onChange={(e) => {
              console.log('e', e)
              setActiveKey(e as string)
            }}
            items={bigTabSelect === '1' ? currentUser?.UserPattern === 9000 ?
              [
                {
                  key: '1000',
                  label: <span>业主{renderBadge(!typeCountLoading ? typeCount?.OwnerUnitCount : '', activeKey === '1000')}</span>,
                },
                {
                  key: '4000',
                  label: <span>供应商{renderBadge(!typeCountLoading ? typeCount?.SupplierCount : '', activeKey === '4000')}</span>,
                },
                {
                  key: '2000',
                  label: <span>商户{renderBadge(!typeCountLoading ? typeCount?.MerchantCount : '', activeKey === '2000')}</span>,
                },
                {
                  key: '3000',
                  label: <span>游客{renderBadge(!typeCountLoading ? typeCount?.TouristCount : '', activeKey === '3000')}</span>,
                },

                {
                  key: '9000',
                  label: <span>内部人员{renderBadge(!typeCountLoading ? typeCount?.AdminCount : '', activeKey === '9000')}</span>,
                },
              ] : currentUser?.UserPattern === 1000 ? [
                {
                  key: '1000',
                  label: <span>业主{renderBadge(!typeCountLoading ? typeCount?.OwnerUnitCount : '', activeKey === '1000')}</span>,
                },
                // {
                //   key: '2000',
                //   label: <span>商户{renderBadge(!typeCountLoading ? typeCount?.MerchantCount : '', activeKey === '2000')}</span>,
                // },
                {
                  key: '4000',
                  label: <span>供应商{renderBadge(!typeCountLoading ? typeCount?.SupplierCount : '', activeKey === '4000')}</span>,
                }
              ] : [] : [
              {
                key: '1000',
                label: <span>业主</span>,
              },
              {
                key: '4000',
                label: <span>供应商</span>,
              },
            ]}
          />
        </div>
      </div>}
      rowKey="SYSTEMROLE_ID"
      actionRef={actionRef}
      request={async (params) => {
        // , SystemRolePID: currentUser?.TopSystemRoleId
        console.log('bigTabSelect', bigTabSelect)
        let req: any = {}
        if (bigTabSelect === '2') {
          req = {
            ShowStatus: params.ShowStatus === '1' ? true : params.ShowStatus === '0' ? false : '',
            SYSTEMROLE_TYPE: 2000,
            SystemRolePattern: params.SystemRolePattern
          }
        } else {
          req = {
            ShowStatus: params.ShowStatus === '1' ? true : params.ShowStatus === '0' ? false : '',
            // current: 1,
            // pageSize: 20,
            SystemRolePattern: params.SystemRolePattern
          }
        }

        const list = await getRoleList(req)
        console.log('list', list)
        if (list && list.length > 0) {
          list.forEach((item: any) => {
            item.label = item.SYSTEMROLE_NAME
            if (item.children && item.children.length > 0) {
              item.children.forEach((subItem: any) => {
                subItem.label = subItem.SYSTEMROLE_NAME
              })
            }
          })
        }
        setRoleTree(list)
        return { data: list, success: true };
      }}
      params={{ SystemRolePattern: activeKey, SYSTEMROLE_TYPE: bigTabSelect }}
      pagination={false}
      columns={columns}
      toolbar={{
        actions: [
          <Button
            key="new"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              getRoleMenu(currentUser?.TopSystemRoleId)
              // 新增角色时，若账号为内部账号则默认角色父级为-1 ，否则则为账号所属角色的父级角色

              console.log('bigTabSelectbigTabSelect', bigTabSelect);
              console.log('currentUsercurrentUser', currentUser);



              setCurrentRow({ SYSTEMROLE_PID: bigTabSelect === '1' ? currentUser?.TopSystemRoleId : '-1', SYSTEMROLE_STATUS: 1 })
              handleModalVisible(true)
            }}
          >角色</Button>,
        ],
        // menu: {
        //     type: 'tab',
        //     activeKey,
        //     items: currentUser?.UserPattern === 9000 ? [
        //         {
        //             key: '1000',
        //             label: <span>业主{renderBadge(!typeCountLoading ? typeCount?.OwnerUnitCount : '', activeKey === '1000')}</span>,
        //         },
        //       {
        //         key: '4000',
        //         label: <span>供应商{renderBadge(!typeCountLoading ? typeCount?.SupplierCount : '', activeKey === '4000')}</span>,
        //       },
        //         {
        //             key: '2000',
        //             label: <span>商户{renderBadge(!typeCountLoading ? typeCount?.MerchantCount : '', activeKey === '2000')}</span>,
        //         },
        //         {
        //             key: '3000',
        //             label: <span>游客{renderBadge(!typeCountLoading ? typeCount?.TouristCount : '', activeKey === '3000')}</span>,
        //         },
        //
        //         {
        //             key: '9000',
        //             label: <span>内部人员{renderBadge(!typeCountLoading ? typeCount?.AdminCount : '', activeKey === '9000')}</span>,
        //         },
        //     ] : currentUser?.UserPattern === 1000 ?[
        //       {
        //         key: '1000',
        //         label: <span>业主{renderBadge(!typeCountLoading ? typeCount?.OwnerUnitCount : '', activeKey === '1000')}</span>,
        //       },
        //       {
        //         key: '4000',
        //         label: <span>供应商{renderBadge(!typeCountLoading ? typeCount?.SupplierCount : '', activeKey === '4000')}</span>,
        //       }
        //     ]:[],
        //     onChange: (key) => {
        //         setActiveKey(key as string);
        //     },
        // }
      }}
    />
    {/* 角色信息编辑弹出框 */}
    <ModalForm
      layout={'horizontal'}
      wrapperCol={{ span: 16 }}
      labelCol={{ span: 6 }}
      title={currentRow ? '角色编辑' : '角色新增'}
      width={bigTabSelect === '1' ? 1024 : 1400}
      visible={createModalVisible}
      formRef={formRef}
      onVisibleChange={(value) => {
        handleModalVisible(value)
        console.log('currentRow', currentRow)
        if (value) {
          formRef.current?.setFieldsValue(
            currentRow ? { ...currentRow, SYSTEMROLE_PID: currentRow.SYSTEMROLE_PID === -1 ? null : currentRow.SYSTEMROLE_PID } : { SYSTEMROLE_STATUS: 1 },
          );
          if (bigTabSelect === '2') {
            console.log('currentRow?.UserTypeIds', currentRow?.UserTypeIds)
            if (currentRow?.SYSTEMROLE_ID) {
              handleGetUserTableData(currentRow?.SYSTEMROLE_PATTERN, currentRow?.UserTypeIds.toString(), searchParams)
              if (currentRow?.UserIds && currentRow?.UserIds.length > 0) {
                const list: any = []
                currentRow?.UserIds.forEach((item: any) => {
                  list.push(item.toString())
                })
                setDefaultSelectRole(currentRow?.UserIds)
              }
              if (currentRow?.UserTypeIds && currentRow?.UserTypeIds.length > 0) {
                const list: any = []
                currentRow?.UserTypeIds.forEach((item: any) => {
                  list.push(item.toString())
                })
                setDefaultRoleTree(list)
              }
              handleGetRoleTree(currentRow?.SYSTEMROLE_PATTERN)
            }
          }

          setCurrentSelectParentRoleList(roleTree)

        } else {
          setRoleCheckedMenu([])
          formRef.current?.resetFields();
          formUserRef.current?.resetFields()
          setCurrentRow(undefined);
          setRoleTreeData([])
          setSelectRowDetail([])
          setUserTableData([])
          setDefaultSelectRole([])
          setDefaultRoleTree([])

          setCurrentSelectParentRoleList([])
        }
      }}
      onFinish={async (value) => {

        let newValue: any = { ...value, SYSTEMROLE_PROVINCE: value?.SYSTEMROLE_PROVINCE || '' }
        if (currentRow) { // 编辑数据
          newValue = { ...currentRow, ...newValue, SYSTEMROLE_PID: value.SYSTEMROLE_PID || -1 }
        }
        newValue.SYSTEMROLE_PROVINCE = !currentUser?.SuperAdmin ? currentUser?.ProvinceCode : newValue.SYSTEMROLE_PROVINCE   // 当操作员是正常用户 则所属业主为他的账号归属的业主；若为内部账号，则所属业主为他所选择的业主
        newValue.SYSTEMROLE_STATUS = newValue.SYSTEMROLE_STATUS ? 1 : 0 // 当操作员是正常用户 则所属业主为他的账号归属的业主；若为内部账号，则所属业主为他所选择的业主
        if (roleCheckedMenu) { // 编辑角色时 是否配置了角色的权限 若配置 则取出配置的模块id
          const moduleKey = roleCheckedMenu.filter(n => n.indexOf('2-') > -1)
          newValue.SystemModuleList = moduleKey.map(n => Number(n.replace('2-', '')))
        } else {
          newValue.SystemModuleList = []
        }

        console.log('newValue', newValue)
        if (bigTabSelect === '2') {
          newValue.SYSTEMROLE_TYPE = 2000
        }

        const success = await handleAddUpdate(newValue);
        handleRecordUser()
        console.log('success', success)
        if (success) {
          if (bigTabSelect === '2') {
            console.log('selectRowDetail', selectRowDetail)
            const req: any = {
              SYSTEMROLE_ID: success.Result_Data.SYSTEMROLE_ID,
              DetailList: []
            }
            const list: any = []
            if (selectRowDetail && selectRowDetail.length > 0) {
              selectRowDetail.forEach((item: any) => {
                list.push({ USER_ID: item.USER_ID, SYSTEMROLE_ID: success.Result_Data.SYSTEMROLE_ID, OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'), SYSTEMROLE_TYPE: 2000 })
              })
            }
            req.DetailList = list
            const data = await handleSynchroUserSystemRoleDetailList(req)
            console.log('data213123', data)
          }


          if (actionRef.current) {
            actionRef.current.reload();
          }

          // handleModalVisible(false);
          return true
        }
        return false
      }}
    >
      {
        bigTabSelect === '1' ?
          <Row>
            <Col span={12}>
              <ProFormText
                name="SYSTEMROLE_NAME"
                label="角色名称"
                placeholder="请输入角色名称"
                rules={[
                  {
                    required: true,
                    message: '请输入角色名称',
                  },
                ]}
              />

              <Form.Item
                name="SYSTEMROLE_PID"
                label="父级角色"
              >
                <TreeSelect
                  placeholder="请选择父级角色"
                  dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
                  // treeData={roleTree}
                  treeData={currentSelectParentRoleList}
                  onSelect={(value: any) => {
                    getRoleMenu(value)
                    return value
                  }}
                  fieldNames={{
                    label: 'SYSTEMROLE_NAME',
                    value: "SYSTEMROLE_ID",
                    children: "children"
                  }}
                  allowClear
                >
                </TreeSelect >
              </Form.Item>
              <ProFormSelect
                name="SYSTEMROLE_PATTERN"
                label="角色类型"
                placeholder="请选择角色类型"
                rules={[
                  {
                    required: true,
                    message: '请选择角色类型',
                  },
                ]}
                options={[
                  { label: '业主', value: 1000 },
                  { label: '商户', value: 2000 },
                  { label: '游客', value: 3000 },
                  { label: '供应商', value: 4000 },
                  { label: '内部人员', value: 9000 }
                ]}
                fieldProps={{
                  onChange: async (e: any) => {
                    console.log('eee', e);
                    const req = {
                      ShowStatus: true,
                      SYSTEMROLE_STATUS: 1,
                      // current: 1,
                      // pageSize: 20,
                      SystemRolePattern: e
                    }
                    const list = await getRoleList(req)
                    console.log('listlistlist', list);
                    setCurrentSelectParentRoleList(list)
                    if (list && list.length > 0) {
                      formRef.current?.setFieldsValue({ SYSTEMROLE_PID: list[0].SYSTEMROLE_ID })
                    } else {
                      formRef.current?.setFieldsValue({ SYSTEMROLE_PID: "" })
                    }
                  }
                }}
              ></ProFormSelect>
              {currentUser?.UserPattern === 9000 && <ProFormSelect
                name="SYSTEMROLE_PROVINCE"
                label="业主单位"
                placeholder="请选择业主单位"
                request={async () => {
                  const options = await getOnwer()
                  return options;
                }}
                allowClear
                fieldProps={{
                  fieldNames: {
                    title: 'label',
                    // key: "value"
                  }
                }}

              />}
              <ProFormDigit
                name="SYSTEMROLE_INDEX"
                label="显示顺序"
                placeholder="请输入显示顺序"
                min={0}
                max={9999}
                fieldProps={{ precision: 0 }}
              />

              <Form.Item
                name="SYSTEMROLE_STATUS"
                label="是否有效"
              >
                <Switch
                  checkedChildren="有"
                  unCheckedChildren="无"
                  defaultChecked={currentRow ? !!currentRow.SYSTEMROLE_STATUS : true}
                />
              </Form.Item>
              <ProFormTextArea
                name="SYSTEMROLE_DESC"
                label="备注说明"
                placeholder="请输入说明"
              />

            </Col>
            <Col span={12}>
              <Form.Item label="角色权限" labelCol={{ span: 6 }} name="SystemModuleList">
                <Card style={{ borderColor: "#97D6FE", height: 386 }}
                  size="small"
                  title="可选模块权限" headStyle={{ backgroundColor: '#E7F7FF' }}
                  extra={<a onClick={() => {
                    setRoleCheckedMenu([])
                    formRef.current?.setFieldsValue({ SystemModuleList: [] })
                  }}>取消选择</a>}>

                  <Tree
                    checkable
                    checkedKeys={roleCheckedMenu}
                    defaultCheckedKeys={roleCheckedMenu}
                    defaultExpandedKeys={roleCheckedMenu}
                    height={330}
                    treeData={roleMenuTree}
                    onCheck={(checkedKeys: React.Key[] | any) => {

                      setRoleCheckedMenu(checkedKeys)
                      return checkedKeys
                    }}
                    fieldNames={
                      { title: "label" }
                    }
                  />
                </Card>
              </Form.Item>
            </Col>
          </Row> :
          <Row>
            <Col span={8}>
              <ProFormSelect
                name="SYSTEMROLE_PATTERN"
                label="角色类型"
                placeholder="请选择角色类型"
                rules={[
                  {
                    required: true,
                    message: '请选择角色类型',
                  },
                ]}
                options={[
                  { label: '业主', value: 1000 },
                  { label: '商户', value: 2000 },
                  { label: '游客', value: 3000 },
                  { label: '供应商', value: 4000 },
                  { label: '内部人员', value: 9000 }
                ]}
                fieldProps={{
                  onChange: (e) => {
                    handleGetRoleTree(e)
                  }
                }}
              ></ProFormSelect>
              {currentUser?.UserPattern === 9000 && <ProFormSelect
                name="SYSTEMROLE_PROVINCE"
                label="业主单位"
                placeholder="请选择业主单位"
                request={async () => {
                  const options = await getOnwer()
                  return options;
                }}
                allowClear
                fieldProps={{
                  fieldNames: {
                    title: 'label',
                    // key: "value"
                  }
                }}

              />}
            </Col>

            <Col span={8}>
              <ProFormText
                name="SYSTEMROLE_NAME"
                label="角色名称"
                placeholder="请输入角色名称"
                rules={[
                  {
                    required: true,
                    message: '请输入角色名称',
                  },
                ]}
              />
            </Col>
            <Col span={8}>
              <Form.Item
                name="SYSTEMROLE_PID"
                label="父级角色"
              >
                <TreeSelect
                  placeholder="请选择父级角色"
                  dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
                  treeData={roleTree}
                  onSelect={(value: any) => {
                    getRoleMenu(value)
                    return value
                  }}
                  fieldNames={{
                    label: 'SYSTEMROLE_NAME',
                    value: "SYSTEMROLE_ID",
                    children: "children"
                  }}
                  allowClear
                >
                </TreeSelect >
              </Form.Item>
            </Col>
            <Col span={8}>
              <ProFormDigit
                name="SYSTEMROLE_INDEX"
                label="显示顺序"
                placeholder="请输入显示顺序"
                min={0}
                max={9999}
                fieldProps={{ precision: 0 }}
              />
            </Col>
            <Col span={8}>
              <Form.Item
                name="SYSTEMROLE_STATUS"
                label="是否有效"
              >
                <Switch
                  checkedChildren="有"
                  unCheckedChildren="无"
                  defaultChecked={currentRow ? !!currentRow.SYSTEMROLE_STATUS : true}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <ProFormTextArea
                name="SYSTEMROLE_DESC"
                label="备注说明"
                placeholder="请输入说明"
              />
            </Col>
            <Col span={24}>
              <div style={{ width: '100%', display: 'flex', height: '500px' }}>
                <ProCard
                  style={{ width: "300px" }}
                  className="pageTable-leftnav pageTable-leftnav-role"
                  bodyStyle={{ padding: 0, paddingTop: 20, paddingLeft: 20, width: "300px" }}
                  colSpan={"300px"}
                  headerBordered
                >
                  {roleTreeData && roleTreeData.length > 0 ? <Tree
                    checkable
                    treeData={roleTreeData}
                    fieldNames={{
                      title: "label",
                      key: "key"
                    }}
                    defaultCheckedKeys={currentRow?.SYSTEMROLE_ID ? defaultRoleTree : []}
                    blockNode
                    defaultExpandedKeys={["205"]}
                    onCheck={(checkedKeys: React.Key[] | any, info) => {
                      console.log('info', info)
                      const selectedIds = info.checkedNodes.filter(n => n?.type === 1)
                      setUserTypeId(selectedIds.map(n => n?.value)?.toString() || '')
                    }}
                  /> : ''}
                </ProCard>
                <div style={{
                  width: 'calc(100% - 300px)',
                  paddingTop: 0,
                  paddingBottom: 0,
                  paddingRight: 0
                }}>
                  <ProTable<UserModel>
                    // headerTitle="账号管理"
                    rowKey="USER_ID"
                    className={'rolesTableBox'}
                    actionRef={actionUserRef}
                    formRef={formUserRef}
                    options={false}
                    scroll={{ y: 340 }}
                    loading={tableLoading}
                    search={{
                      span: 8,
                      optionRender: ({ searchText }, { form }) => {
                        return [
                          <Button
                            key="sub"
                            type={'primary'}
                            onClick={() => {
                              // const tableTab = formRef.current?.getFieldValue('SYSTEMROLE_PATTERN')
                              // handleGetUserTableData(tableTab,userTypeId)
                              clickTableBtnRef.current = true
                              formUserRef.current?.submit();
                            }}
                          >
                            搜索
                          </Button>
                        ]
                      }
                    }}
                    pagination={false}
                    request={async (params) => {
                      setSearchParams(params)
                      if (clickTableBtnRef.current) {
                        const tableTab = formRef.current?.getFieldValue('SYSTEMROLE_PATTERN')
                        handleGetUserTableData(tableTab, userTypeId, params)
                      }
                    }}
                    dataSource={userTableData}
                    onReset={() => {
                      actionRef.current?.reload()
                    }}
                    columns={userColumns}
                    rowSelection={{ // 可选择的表格配置
                      type: "checkbox", // 该表格为单选
                      selectedRowKeys: defaultSelectRole,
                      onChange: (selectedRowKeys, selectedRows) => {
                        console.log('selectedRowKeys', selectedRowKeys)
                        console.log('selectedRows', selectedRows)
                        setDefaultSelectRole(selectedRowKeys)
                        setSelectRowDetail(selectedRows)
                      }
                    }}
                  />
                </div>
              </div>
            </Col>
          </Row>
      }


    </ModalForm>
    {/* 角色详情抽屉 */}
    <Drawer
      width={600}
      visible={showDetail}
      onClose={() => {
        setCurrentRow(undefined);
        setRowDetail(undefined);
        setShowDetail(false);
      }}
      closable={false}
      afterOpenChange={async (open) => {
        console.log('open', open)
        if (open && bigTabSelect === '2') {
          console.log('currentRow', currentRow)
          const req: any = {
            SYSTEMROLEId: currentRow?.SYSTEMROLE_ID
          }
          const data = await handleGetSYSTEMROLEDetail(req)
          setRowDetail(data)
        }
      }}
    >
      {currentRow?.SYSTEMROLE_NAME && (
        <>
          <ProDescriptions<SystemRoleModel>
            column={2}
            title={currentRow?.SYSTEMROLE_NAME}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.SYSTEMROLE_NAME,
            }}
            columns={columns as ProDescriptionsItemProps<SystemRoleModel>[]}
          >
            {
              bigTabSelect === '2' ?
                <ProDescriptions.Item label="所选人员">
                  {rowDetail?.UserNames && rowDetail?.UserNames.length > 0 ? rowDetail?.UserNames.toString() : ''}
                </ProDescriptions.Item> :
                <ProDescriptions.Item label="角色权限">
                  <Tree
                    defaultExpandAll
                    style={{ backgroundColor: '#FDFCFC', paddingRight: 24 }}
                    treeData={bigTabSelect === '2' ? roleTree : roleMenuTree}
                    fieldNames={
                      { title: "label" }
                    }>

                  </Tree>
                </ProDescriptions.Item>
            }

          </ProDescriptions>
        </>
      )}
    </Drawer>
  </PageContainer>
  )
}

export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser,

}))(RoleList);

