
import ProForm, { ProFormRadio, ProFormSelect, ProFormText, ProFormTreeSelect } from "@ant-design/pro-form"
import { FooterToolbar, PageContainer } from "@ant-design/pro-layout"
import useRequest from "@ahooksjs/use-request";
import { Card, Col, Form, Row, Tree, message, Switch, Button, TreeSelect, Radio, Drawer, Popconfirm } from "antd";
import { useEffect, useRef, useState } from "react";
import { history } from "umi";

import type { ProFormInstance } from "@ant-design/pro-form";
import type { CurrentUser } from '@/models/user';

import { getMerchantTree, getMerchantTreeNosessoin, getOnwer } from "@/services/options";
import { getUserDetail, getUserTypeTree, getServerpartTree, updataUser, modifyUserPassword, getMerchantShopTree, getWeiChatPush, handleGetServiceList, handleDeleteUSER, handleSynchroBEHAVIORRECORD } from "../service";
import { getRoleList, getSystemMenuTree, handleAnalysisPermission, handleSupplierList } from "../../Roles/service";
import session from "@/utils/session";
import moment from 'moment'
import BusinessManDrawer from "@/pages/basicManage/businessMan/components/businessManDrawer";
import { handeGetMERCHANTSList } from "@/pages/travelMember/service";

// 提交账号数据
const handleAddUpdate = async (item: any, type: boolean) => {
  console.log('handleAddUpdate', item);
  const loading = message.loading("正在提交...")
  const result = await updataUser(item)

  loading()
  if (result.Result_Code !== 100) {
    message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`)
    return false
  }
  if (type) {
    message.success(item.USER_ID ? "更新成功！" : "新建成功！")
  }
  return result.Result_Data.USER_ID
}

// 重置账号密码请求
const handelResetPassWord = async (item: { UserId: number, Password: string }) => {
  const loading = message.loading("正在提交...")
  const result = await modifyUserPassword(item)
  loading()
  if (result.Result_Code !== 100) {
    message.error(`${result.Result_Desc}` || `${result.Result_Code}:账户密码重置失败`)
  } else {
    message.success("账户密码重置成功！")
  }

}
/**
 * @description: 主体编辑函数
 * @param {function} reloadTable 是否已经更新数据
 * @param {UserModel} detail 编辑账户数据时的数据对象 
 * @param {CurrentUser} user 当前用户的用户信息
 * @return {ReactDOM} 返回页面节点
 */
const Edit = ({ tableTab, openType, detail, reloadTable, currentUser, selectTab, pageType, BUSINESSMAN_ID, onShow }: { onShow?: boolean, BUSINESSMAN_ID?: any, pageType?: string, selectTab?: any, tableTab?: any, openType?: string, detail?: UserModel, reloadTable: any, currentUser: CurrentUser | undefined }) => {
  const detailForm = useRef<ProFormInstance>() // 表单对象
  const [checkedRole, setCheckedRole] = useState<React.Key[]>(); // 当前选中的行 角色 id
  const [checkedServerpart, setCheckedServerpart] = useState<React.Key[]>(); // 当前选中的行 服务区id
  const [checkedShop, setCheckedShop] = useState<React.Key[]>(); // 当前选中的行 服务区门店id
  const [initialDetail, setInitialDetail] = useState<any>(detail || {}); // 当前编辑页面的账户数据
  const [copyData, setCopyData] = useState<any>()// 拷贝一份一开始接口返回的表单数据 与 最后提交可以进行对比
  const [companyList, setCompanyList] = useState<any>()// 用户下面的公司列表
  const [selectDetail, setSelectDetail] = useState<any>()// 选中的业主单位的省份
  const [serviceList, setServiceList] = useState<any>()// 服务区列表
  const [showServiceList, setShowServiceList] = useState<any>()// 展示要选择的服务区
  // const selectType = useRef()
  const [showWeChatFlag, setShowWeChatFlag] = useState<any>()// 微信推送权限是选择了false 还是 true
  const [SPRegionList, setSPRegionList] = useState<any>()// 片区的数组
  // type为1 的
  const [serverPartType1, setServerPartType1] = useState<any>()
  // 添加商户的抽屉
  const [showAddDrawer, setShowAddDrawer] = useState<boolean>(false)
  // const [supplierList,setSupplierList] = useState<any>()// 供应商列表
  // 查询角色树
  const [roleTree, setRoleTree] = useState<any>() // 角色树列表
  // const { data: roleTree } = useRequest(async () => {
  //   if (currentUser?.UserPattern===9000){
  //     const req = {
  //       SystemRolePattern:currentUser?.UserPattern
  //     }
  //     return await getRoleList(req)
  //   }
  // })
  const handleRoleList = async (value: number) => {
    if (currentUser?.UserPattern === 9000) {
      const req = {
        ShowStatus: true
      }
      const data = await getRoleList(req)
      setRoleTree(data)

    } else if (currentUser?.UserPattern === 1000 && value !== 3000) {
      let req
      if (currentUser?.SystemRolePID) {
        req = {
          SystemRolePID: currentUser?.SystemRolePID,
          ShowStatus: true,
          SystemRolePattern: value
        }
      } else {
        req = {
          ShowStatus: true,
          SystemRolePattern: value
        }
      }
      const data = await getRoleList(req)
      setRoleTree(data)
    } else if (currentUser?.UserPattern !== 3000) {
      const req = {
        ShowStatus: true,
        SystemRolePattern: value
      }
      const data = await getRoleList(req)
      console.log('reqreqreq', data);

      setRoleTree(data)
    }
  }

  // 查询可配置的服务区
  const { data: serverpartTree } = useRequest(async () => {
    const data = await getServerpartTree({ ProvinceCode: '530000' })
    return data.map(n => n.children ? n : { ...n, children: [] })
  })
  // 查询可选商家
  // const { run: getMerchantTree, data: merchantTree } = useRequest(async () => {
  //   return await getMerchantTree()
  // })

  // 查询可选商家
  const { run: handleGetMerchantTree, data: merchantTree } = useRequest(async () => {
    const data = await getMerchantTreeNosessoin()
    return data
  }, { manual: true })


  const { data: supplierList } = useRequest(async () => {
    const req = {
      searchParameter: {
        OWNERUNIT_ID: 911,
        PROVINCE_CODE: 530000,
        MERCHANTS_TYPE: ""
      },
      PageIndex: 1,
      PageSize: 999999,
    }
    const data = await handeGetMERCHANTSList(req);
    let list: any = []
    if (data.List && data.List.length > 0) {
      data.List.forEach((item: any) => {
        list.push({ label: item.MERCHANTS_NAME, value: item.MERCHANTS_ID })
      })
    }
    return list
  })

  // 根据角色id查询权限树
  const { run: getRoleMenu, data: roleMenuTree } = useRequest(async (SystemRoleId?: number) => {
    const data = await getSystemMenuTree(SystemRoleId ? `${SystemRoleId}` : '')
    return data
  }, { manual: true })

  // 根据商家id查询门店列表
  const { run: getShopTree, data: shopTree } = useRequest(async (businessManId?: number) => {
    const data = await getMerchantShopTree({ BusinessManId: businessManId ? `${businessManId}` : detail?.BUSINESSMAN_ID })
    return data
  }, { manual: !detail?.BUSINESSMAN_ID })

  const companyType = {
    1000: "业主本部",
    1010: "服务区",
    1020: "区域",
    2000: "商户"
  }

  const getServiceList = async (PROVINCEID: any, id: any) => {
    const typeId = id || showServiceList
    const req = {
      ProvinceCode: PROVINCEID,
      ServerpartType: typeId === 1020 ? 1010 : 1000,
      ShowWholePower: true
    }
    const res = await handleGetServiceList(req)
    // const service: any = []
    // const SPRegion: any = []
    // if (res.List && res.List.length>0){
    //   res.List.forEach((item: any)=>{
    //     SPRegion.push({label:item.label,value:item.value})
    //     service.push({label:item.label,value:item.value})
    //     // if (item.children && item.children.length>0){
    //     //   item.children.forEach((subItem: any)=>{
    //     //     service.push({label:subItem.label,value:subItem.value})
    //     //   })
    //     // }
    //   })
    // }
    if (res.List && res.List.length > 0) {
      const list = JSON.parse(JSON.stringify(res.List))
      // for (let i=0;i<=list.length-1;i++){
      //   for (let j=0;j<=list.length - i - 1;j++){
      //     if (list[j] && list[j + 1] && list[j].value && list[j+1].value){
      //       if (list[j].value > list[j+1].value){
      //         const temp = list[j]
      //         list[j] = list[j + 1]
      //         list[j + 1] = temp
      //       }
      //     }
      //   }
      // }
      list.forEach((item: any) => {
        if (item.type === 1) {
          item.selectable = true
        } else {
          item.selectable = false
        }
      })

      // setServiceList(list)
      setSPRegionList(list)
    }
  }

  // 商戶管理拿到角色权限
  const handleRoleListShop = async () => {
    const req = {
      ShowStatus: true,
      SystemRolePattern: 2000
    }
    const data = await getRoleList(req)
    setRoleTree(data)
  }


  useEffect(() => {
    // detailForm.current?.setFieldsValue({USER_PATTERN: Number(selectTab) })
    console.log('selectTab', Number(selectTab))
    if (pageType === 'merchantManagement') {
      handleRoleListShop()
    } else {
      handleRoleList(Number(selectTab))
    }
    handleGetMerchantTree()
    setInitialDetail({
      ...initialDetail,
      USER_PATTERN: Number(selectTab)
    })
  }, [selectTab]);


  // 删除角色
  const handleDeleteUser = async () => {
    console.log('initialDetail', initialDetail);

    const req: any = {
      USERId: initialDetail?.USER_ID
    }
    const data = await handleDeleteUSER(req)
    if (data.Result_Code === 100) {
      message.success(data.Result_Desc)
      reloadTable(true, 'delete')
    } else {
      message.error(data.Result_Desc)
    }
    const baseInfo = session.get('basicInfo')
    const browser = session.get('browserVersion')
    const systemInfo = session.get('systemBasin')

    handleGetSynchroBEHAVIORRECORD(1002)
  }

  const handleGetSynchroBEHAVIORRECORD = async (type: number) => {
    const baseInfo = session.get('basicInfo')
    const browser = session.get('browserVersion')
    const systemInfo = session.get('systemBasin')

    const req: any = {
      USER_ID: initialDetail?.USER_ID,
      USER_NAME: initialDetail?.USER_NAME,
      USER_PASSPORT: initialDetail?.USER_PASSPORT,
      USER_MOBILEPHONE: initialDetail?.USER_MOBILEPHONE,
      BEHAVIORRECORD_TYPE: type,
      BEHAVIORRECORD_EXPLAIN: type === 1001 ? '更新用户' : '删除用户',
      BEHAVIORRECORD_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
      BEHAVIORRECORD_ROUT: pageType ? '/setting/merchantManagement' : '/setting/users',
      BEHAVIORRECORD_ROUTNAME: pageType ? '商户管理' : '账号管理',
      SOURCE_PLATFORM: '驿商云平台',
      USER_LOGINIP: baseInfo?.ip ? baseInfo?.ip : '',
      USER_LOGINPLACE: `${baseInfo?.prov ? baseInfo?.prov : ''}${baseInfo?.prov && baseInfo?.city ? '-' : ''}${baseInfo?.city ? baseInfo?.city : ''}${baseInfo?.prov && baseInfo?.city && baseInfo?.district ? '-' : ''}${baseInfo?.district ? baseInfo?.district : ''}`,
      BROWSER_VERSION: browser || '',
      OPERATING_SYSTEM: systemInfo || '',
    }
    handleSynchroBEHAVIORRECORD(req)
  }




  return (
    <PageContainer header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProForm
        wrapperCol={{ span: 20 }}
        labelCol={{ span: 20 }}
        formRef={detailForm}
        initialValues={initialDetail || {}}
        request={async () => {
          if (detail) {
            const initDetail = await getUserDetail(detail.USER_ID, true)
            // 格式转化
            // let haveList = initDetail.ServerpartList ? initDetail.ServerpartList.map(Number) : [] // 业主账号有服务区   有权限的全部服务区
            const haveList = initDetail.ServerpartList || [] // 业主账号有服务区   有权限的全部服务区

            const firstType: any = []
            const serverpartTree = await getServerpartTree()

            if (serverpartTree && serverpartTree.length > 0) {
              serverpartTree.forEach((item: any) => {
                if (item.type === 1) {
                  firstType.push(item.value)
                  if (item.children && item.children.length > 0) {
                    item.children.forEach((subItem: any) => {
                      if (subItem.type === 1) {
                        firstType.push(subItem.value)
                      }
                    })
                  }
                }
              })
            }


            const serverpartList: any = []
            if (haveList && haveList.length > 0) {
              if (firstType && firstType.length > 0) {
                haveList.forEach((item: any) => {
                  if (firstType.indexOf(Number(item)) === -1) {
                    serverpartList.push(Number(item))
                  }
                })
              }
            }



            const serverpartShopList = initDetail.ServerpartShopList ? initDetail.ServerpartShopList.map(Number) : [] // 商户账号有门店
            const systemRoleList = initDetail.SystemRoleList ? initDetail.SystemRoleList.map(Number) : []
            initDetail.USERTYPE_ID = initDetail.USERTYPE_ID || ''
            setCheckedRole(initDetail.SystemRoleList)
            setCheckedServerpart(serverpartList)

            setCheckedShop(serverpartShopList)
            if (tableTab === '1000') {
              // getServiceList(initDetail.USER_PROVINCE, initDetail.PushList && initDetail.PushList.length > 0 && initDetail.PushList[0] ? initDetail.PushList[0].type : null)
              getServiceList('530000', initDetail.PushList && initDetail.PushList.length > 0 && initDetail.PushList[0] ? initDetail.PushList[0].type : null)
            }
            const res = JSON.parse(JSON.stringify(initDetail))
            // setSelectDetail(initDetail.USER_PROVINCE)
            setSelectDetail('530000')

            if (initDetail.PushList && initDetail.PushList.length > 0) {
              if (initDetail.PushList[0].key) {
                const keyList: any = []
                const list = initDetail.PushList[0].key.split(',')
                list.forEach((item: any) => {
                  keyList.push(item)
                })
                res.ServerpartIds = keyList
              }

              // res.ServerpartIds = initDetail.PushList[0].key?Number(initDetail.PushList[0].key):null
              res.UserTypeIds = initDetail.PushList[0].type
              setShowServiceList(initDetail.PushList[0].type)
              setInitialDetail(res)
            } else {
              setInitialDetail(res)
            }
            setCompanyList(initDetail.PushList)
            // setShowServiceList(initDetail.PushList[0].type)
            setShowWeChatFlag(initDetail.PushPermission)

            // 请求获取该账户绑定的角色拥有的模块权限
            if (initDetail.SystemRoleList.length > 0) {
              getRoleMenu(initDetail.SystemRoleList.toString())
            }
            setCopyData(res)
            return { ...initDetail, ServerpartIds: res?.ServerpartIds || [], ServerpartList: serverpartList, SystemRoleList: systemRoleList, ServerpartShopList: serverpartShopList, USER_PROVINCE: 911 }
          }

          handleGetMerchantTree()

          setSelectDetail('530000')
          // , USER_PATTERN: currentUser?.UserPattern
          setInitialDetail({ USER_STATUS: 1, USER_REPEATLOGON: 1, SUPER_ADMIN: 0 })
          // , USER_PATTERN: currentUser?.UserPattern
          setCopyData(JSON.parse(JSON.stringify({ USER_STATUS: 1, USER_REPEATLOGON: 1, SUPER_ADMIN: 0 })))
          // , USER_PATTERN: currentUser?.UserPattern

          if (pageType === 'merchantManagement') {
            detailForm.current?.setFieldsValue({ USERTYPE_ID: '' })
            setInitialDetail({ ...initialDetail, BUSINESSMAN_NAME: BUSINESSMAN_ID?.label, BUSINESSMAN_ID: Number(BUSINESSMAN_ID?.value) })
            console.log('{ ...initialDetail, BUSINESSMAN_NAME: BUSINESSMAN_ID?.label }', { ...initialDetail, BUSINESSMAN_NAME: BUSINESSMAN_ID?.label || '' });
            setCheckedServerpart([]) // 清空选择的服务区/门店
            getShopTree(BUSINESSMAN_ID?.value)
          }
          console.log('没有');


          return { USER_STATUS: 1, USER_REPEATLOGON: 1, SUPER_ADMIN: 0, USER_PROVINCE: 911 }
        }}
        onFinish={async (value) => {
          let newValue: any = { ...value }

          if (initialDetail) { // 编辑数据
            newValue = { ...initialDetail, ...value }
          }
          newValue.USER_STATUS = newValue.USER_STATUS ? 1 : 0
          newValue.USER_REPEATLOGON = newValue.USER_REPEATLOGON ? 1 : 0
          newValue.SUPER_ADMIN = newValue.SUPER_ADMIN ? 1 : 0
          newValue.USER_CITYAUTHORITY = checkedServerpart ? checkedServerpart.join(" ") : ''
          newValue.ServerpartList = checkedServerpart && checkedServerpart.length > 0 ? checkedServerpart : []
          newValue.ServerpartShopList = checkedShop || []
          newValue.SystemRoleList = checkedRole && checkedRole.length > 0 ? checkedRole : []
          newValue.OperateUser = currentUser?.Name
          newValue.ServerpartIds = newValue.ServerpartIds && newValue.ServerpartIds.length > 0 ? newValue.ServerpartIds.toString() : ''
          newValue.USER_PROVINCE = '530000'

          // 拿到新修改的数据
          const newData = detailForm.current?.getFieldsValue()
          // 比较开始数据 如果和开始数据不一样 就调用接口
          // 调用接口传入的是当前新的值
          if (newData.AnalysisPermission !== copyData.AnalysisPermission) {
            handleAnalysisPermission({
              userId: copyData.USER_ID,
              AuthorType: (selectDetail === 530000 && tableTab === '1000' ||
                selectDetail === 530000 && copyData?.AnalysisPermission === true && tableTab === '1000' ||
                selectDetail === 530000 && copyData?.AnalysisPermission === false && tableTab === '1000') && newData.AnalysisPermission,
              OperateUser: currentUser?.Name
            })
          }

          const success = await handleAddUpdate(newValue, false);

          if (success) {
            // 比较开始数据 如果和开始数据不一样 就调用接口
            // 调用接口传入的是当前新的值
            // 因为如果没权限的时候要把错误提示弹出来显示 所以要做判断
            // 一个是没有微信授权  一个有微信授权的情况下
            // 微信没有授权的时候 就不会调用更新数据的接口 只会报未绑定
            // 微信有授权的时候就掉更新数据的接口
            if (newData.PushPermission !== copyData.PushPermission ||
              newData.UserTypeIds !== copyData.UserTypeIds ||
              newData.ServerpartIds !== copyData.ServerpartIds) {
              let serverpartId = ''
              if (newData.ServerpartIds && newData.ServerpartIds.length > 0) {
                newData.ServerpartIds.forEach((item: any) => {
                  if (serverpartId === '') {
                    serverpartId = item.split('-')[1].toString()
                  } else {
                    serverpartId += `,${item.split('-')[1].toString()}`
                  }
                })
              }
              let req = {}
              if (tableTab === '1000' || tableTab === '4000') {
                req = {
                  userId: openType === 'add' ? success : copyData.USER_ID,
                  AuthorType: newData.PushPermission || false,
                  OperateUser: currentUser?.Name,
                  GroupType: newData.UserTypeIds || null,
                  ServerpartIds: serverpartId
                }
              } else if (tableTab === '2000') {
                req = {
                  userId: openType === 'add' ? success : copyData.USER_ID,
                  AuthorType: newData.PushPermission || false,
                  OperateUser: currentUser?.Name,
                }
              }
              // getWeiChatPush(req).then(async res => {
              //   if (res.Result_Code === 200) {
              //     message.error(res.Result_Desc)
              //   } else {
              //     message.success(newValue.USER_ID ? "更新成功！" : "新建成功！")
              //   }
              // })
              message.success(newValue.USER_ID ? "更新成功！" : "新建成功！")
            } else {
              message.success(newValue.USER_ID ? "更新成功！" : "新建成功！")
            }
          }

          handleGetSynchroBEHAVIORRECORD(1001)
          reloadTable(success)
        }}
        submitter={{
          render: (_, dom) => (
            <FooterToolbar
              style={{
                // left: 208,
                width: "73%",
              }}
            >
              {
                initialDetail?.USER_ID ?
                  <Popconfirm title="确认删除？" onConfirm={() => {
                    handleDeleteUser()
                  }}>
                    <Button type="primary" danger>删除</Button>
                  </Popconfirm> : ''
              }

              {detail?.USER_ID &&
                <Button type="primary" danger onClick={() => {
                  handelResetPassWord({ UserId: initialDetail.USER_ID, Password: initialDetail.USER_PASSPORT })
                }}>重置账号密码</Button>
              }
              {dom[0]}
              <Button type="primary" onClick={() => {
                detailForm.current?.setFieldsValue({ UserTypeIds: showServiceList })
                detailForm.current?.submit()
              }}>提交</Button>
            </FooterToolbar>
          ),
        }}
      >
        <Card bordered={false} bodyStyle={{ paddingBottom: 0 }}>
          <Row>
            {currentUser?.UserPattern === 9000 || currentUser?.UserPattern === 1000 ?
              <Col span={6}>
                <ProFormSelect
                  name="USER_PATTERN"
                  label="账号类型"
                  placeholder="请选择账号类型"
                  rules={[
                    {
                      required: true,
                      message: '请选择业主单位',
                    },
                  ]}
                  initialValue={Number(selectTab) || null}
                  disabled={pageType === 'merchantManagement'}
                  options={
                    currentUser?.UserPattern === 9000 || pageType === 'merchantManagement' ? [
                      { label: '业主', value: 1000 },
                      { label: '供应商', value: 4000 },
                      { label: '商户', value: 2000 },
                      { label: '游客', value: 3000 },
                      { label: '内部人员', value: 9000 }
                    ] : [{ label: '业主', value: 1000 }, { label: '供应商', value: 4000 }]}
                  fieldProps={{

                    onChange: async (value: any) => {
                      if (value === 1000) {
                        setSelectDetail(null)
                      }
                      detailForm.current?.setFieldsValue({ USERTYPE_ID: '', USER_PROVINCE: '', ServerpartList: [], PROVINCE_UNIT: '' })
                      setInitialDetail({ ...initialDetail, USER_PATTERN: Number(value), PROVINCE_UNIT: '' })
                      setCheckedServerpart([]) // 清空选择的服务区/门店
                      handleRoleList(value)
                    }
                  }}
                />
              </Col> : ''}
            <Col span={6}>
              <ProFormText
                label="账号名称"
                name="USER_PASSPORT"
                placeholder="请输入账号名称"
                disabled={!!detail?.USER_PASSPORT}
                rules={[
                  {
                    required: true,
                    message: '请输入账号名称,',
                  }
                ]}
              />
            </Col>
            <Col span={6}>
              <ProFormText
                label="用户名称"
                name="USER_NAME"
                placeholder="请输入用户名称"
                rules={[
                  {
                    required: true,
                    message: '请输入用户名称,',
                  }
                ]}
              />
            </Col>
            <Col span={6}>

              <ProFormText
                label="手机号码"
                name="USER_MOBILEPHONE"
                placeholder="请输入手机号码"


                rules={[
                  {
                    required: true,
                    message: '请输入手机号码',
                  },
                ]}
              />
            </Col>

            <Col span={12}>
              <ProFormSelect
                name="USER_PROVINCE"
                label="业主单位"
                initialValue={pageType === 'merchantManagement' ? Number(currentUser?.ProvinceCode) : ''}
                disabled={pageType === 'merchantManagement'}
                rules={[
                  {
                    required: initialDetail.USER_PATTERN === 1000,
                    message: '请选择业主单位',
                  },
                ]}
                request={async () => {
                  const options = await getOnwer({ DataType: 1, ProvinceCode: "530000" })
                  console.log('optionsoptionsoptionsoptions', options);

                  return options;
                }}
                fieldProps={{
                  showSearch: true,
                  placeholder: '请选择业主单位',
                  fieldNames: {
                    title: 'label',
                    // key: "value"
                  },
                  onSelect: (_: any, options: any) => {
                    console.log("optionsoptions", options);

                    detailForm.current?.setFieldsValue({ ServerpartIds: [] })
                    setSelectDetail(options.value)
                    getServiceList(options.value, showServiceList || null)
                    detailForm.current?.setFieldsValue({ USERTYPE_ID: '' })
                    // setInitialDetail({ ...initialDetail, PROVINCE_UNIT: options.label, })
                    setInitialDetail({ ...initialDetail, PROVINCE_UNIT: options.value, OWNERUNIT_NAME: options.label })
                    // if (initialDetail.USER_PATTERN === 4000){ 
                    //   const req = {
                    //     ProvinceCode:currentUser?.ProvinceCode,
                    //     // OwnerUnitId:e
                    //   }
                    //   const data = await handleSupplierList(req)
                    //   setSupplierList(data.List)
                    // }
                  },
                  onChange: async (e) => {
                    if (!e) {
                      setSelectDetail(undefined)
                    }
                  }
                }}

              />
            </Col>


            {/* {currentUser?.UserPattern === 9000 ||initialDetail.USER_PATTERN === 4000?
              <Col span={12}>
                <ProFormSelect
                  name="USER_PROVINCE"
                  label="业主单位"

                  rules={[
                    {
                      required: initialDetail.USER_PATTERN === 1000,
                      message: '请选择业主单位',
                    },
                  ]}
                  request={async () => {
                    const options = await getOnwer()
                    return options;
                  }}
                  fieldProps={{
                    showSearch: true,
                    placeholder: '请选择业主单位',
                    fieldNames: {
                      title: 'label',
                      // key: "value"
                    },
                    onSelect: (_: any, options: any) => {
                      detailForm.current?.setFieldsValue({ ServerpartIds: [] })
                      setSelectDetail(options.value)
                      getServiceList(options.value, showServiceList || null)
                      detailForm.current?.setFieldsValue({ USERTYPE_ID: '' })
                      setInitialDetail({ ...initialDetail, PROVINCE_UNIT: options.label, })
                      // if (initialDetail.USER_PATTERN === 4000){
                      //   const req = {
                      //     ProvinceCode:currentUser?.ProvinceCode,
                      //     // OwnerUnitId:e
                      //   }
                      //   const data = await handleSupplierList(req)
                      //   setSupplierList(data.List)
                      // }
                    },
                    onChange: async (e) => {
                      if (!e) {
                        setSelectDetail(undefined)
                      }
                    }
                  }}

                />
              </Col>:''
            } */}

            <Col span={6}>

              <ProFormTreeSelect
                label="账号部门"
                name="USERTYPE_ID"
                dependencies={['USER_PROVINCE', 'USER_PATTERN', '']}
                // rules={[
                //   {
                //     required: initialDetail.USER_PATTERN === 1000 || initialDetail.USER_PATTERN === 4000,
                //     message: '请选择账号部门',
                //   },
                // ]}

                request={async (params) => {
                  console.log('params', params);
                  if (pageType === 'merchantManagement') {
                    const req: any = {
                      // ProvinceCode: '530000',
                      UserTypePattern: 2000
                    }
                    const data = await getUserTypeTree(req)
                    console.log('data2', data)
                    if (data && data.length > 0) {
                      data.forEach((item: any) => {
                        item.disabled = true
                      })
                    }
                    return data
                  } if (params.USER_PROVINCE || params.USER_PATTERN) {
                    const req: any = {
                      // ProvinceCode: '530000',
                      UserTypePattern: tableTab === 9000 ? 1000 : tableTab
                    }
                    const data = await getUserTypeTree(req)
                    console.log('data2', data)
                    if (data && data.length > 0) {
                      data.forEach((item: any) => {
                        item.disabled = true
                      })
                    }
                    return data
                    // return await getUserTypeTree({ ProvinceCode: params.USER_PATTERN === 1000 ? params.USER_PROVINCE : params.BUSINESSMAN_ID,UserTypePattern:tableTab==='4000'?tableTab:'' })
                  }
                  return []
                }}
                fieldProps={{
                  fieldNames: {
                    key: "value",
                    title: 'label',
                  },
                  treeDefaultExpandAll: true
                }}
              // addonAfter={<Button type="primary"

              //     onClick={() => {
              //         window.open(`/setting/userstype`)
              //         // history.push('/setting/userstype')

              //     }}>去添加</Button>}
              />

            </Col>

            <Col span={6}>
              <ProFormText
                label="显示顺序"
                name="USER_INDEX"
                placeholder="请输入显示顺序"

              />
            </Col>
            {(currentUser?.UserPattern === 9000 && initialDetail.USER_PATTERN === 2000) || pageType === 'merchantManagement' ?
              <Col span={12}>

                <Row gutter={8} style={{ alignItems: 'center' }}>
                  <Col span={16}>
                    <Form.Item
                      name="BUSINESSMAN_ID"
                      label="所属商家"

                      rules={[
                        {
                          required: true,
                          message: '请选择所属商家',
                        },
                      ]}
                      initialValue={pageType === 'merchantManagement' ? BUSINESSMAN_ID?.value ? Number(BUSINESSMAN_ID?.value) : '' : ''}
                    >
                      <TreeSelect
                        treeData={merchantTree}
                        treeDefaultExpandAll
                        showSearch
                        treeNodeFilterProp="label"
                        onSelect={(value: any, options: any) => {
                          detailForm.current?.setFieldsValue({ USERTYPE_ID: '' })
                          setInitialDetail({ ...initialDetail, BUSINESSMAN_NAME: options.label, })
                          setCheckedServerpart([]) // 清空选择的服务区/门店
                          getShopTree(value)
                        }}
                        placeholder="请选择所属商家,以便给商户授权门店"
                        allowClear
                      />
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    {
                      pageType === 'merchantManagement' ?
                        <Button style={{ marginLeft: '8px' }} type="primary" onClick={() => {
                          setShowAddDrawer(true)
                        }}>添加商户</Button> : ''
                    }
                  </Col>
                </Row>
              </Col> : initialDetail.USER_PATTERN === 4000 && selectDetail ?
                <Col span={12}>
                  <Form.Item
                    name="BUSINESSMAN_ID"
                    label="所属供应商"
                    rules={[
                      {
                        required: true,
                        message: '所属供应商',
                      },
                    ]}
                  >
                    <TreeSelect
                      treeData={supplierList}
                      treeDefaultExpandAll
                      showSearch
                      treeNodeFilterProp="label"
                      onSelect={(value: any, options: any) => {
                        detailForm.current?.setFieldsValue({ USERTYPE_ID: '' })
                        setInitialDetail({ ...initialDetail, BUSINESSMAN_NAME: options.label })
                        setCheckedServerpart([]) // 清空选择的服务区/门店
                        getShopTree(value)
                      }}
                      placeholder="请选择所属供应商"
                      allowClear
                    />
                  </Form.Item>
                </Col> : ''
            }
            <Col span={6} style={{ display: 'none' }}>
              <ProFormText
                label="所属供应商"
                name="BUSINESSMAN_NAME"
              />
            </Col>
            <Col span={16}>
              <ProFormText
                label="备注"
                name="USER_DESC"
              // placeholder="请输入显示顺序"
              />
            </Col>

            {/* {currentUser?.UserPattern===9000 && <Col span={4}>

                            <Form.Item
                                name="SUPER_ADMIN"
                                label="是否为内部账号"
                            >
                                <Switch
                                    checkedChildren="是"
                                    unCheckedChildren="否"
                                    defaultChecked={detail ? !!detail.SUPER_ADMIN : false}
                                />
                            </Form.Item>
                        </Col>
                        } */}
          </Row>
          <Row>
            <Col span={4}>
              <Form.Item
                name="USER_STATUS"
                label="有效状态"
              >
                <Switch
                  checkedChildren="有效"
                  unCheckedChildren="无效"
                  defaultChecked={detail ? !!detail.USER_STATUS : true}
                />
              </Form.Item>
            </Col>

            <Col span={4}>

              <Form.Item
                name="USER_REPEATLOGON"
                label="可重复登录"
              >
                <Switch
                  checkedChildren="是"
                  unCheckedChildren="否"
                  defaultChecked={detail ? !!detail.USER_REPEATLOGON : true}
                />
              </Form.Item>
            </Col>
            {
              selectDetail === 530000 && tableTab === '1000' ||
                selectDetail === 530000 && copyData?.AnalysisPermission === true && tableTab === '1000' ||
                selectDetail === 530000 && copyData?.AnalysisPermission === false && tableTab === '1000'
                ?
                <Col span={4}>
                  <Form.Item
                    name="AnalysisPermission"
                    label="业主看板权限"
                  >
                    <Switch
                      checkedChildren="是"
                      unCheckedChildren="否"
                      defaultChecked={copyData?.AnalysisPermission}
                    // defaultChecked={detail ? !!copyData.AnalysisPermission : true}
                    />
                  </Form.Item>
                </Col> : ''
            }
            {
              tableTab === '2000' || tableTab === 2000 ?
                <Col span={4}>
                  <Form.Item
                    name="PushPermission"
                    label="微信推送权限"
                  >
                    <Switch
                      checkedChildren="是"
                      unCheckedChildren="否"
                      defaultChecked={copyData?.PushPermission}
                      // defaultChecked={detail ? !!copyData.PushPermission : true}
                      onChange={(e) => {
                        setShowWeChatFlag(e)
                      }}
                    />
                  </Form.Item>
                </Col>
                : ''
            }
          </Row>
          {
            tableTab === '1000' ?
              <Row>
                <Col span={4}>
                  <Form.Item
                    name="PushPermission"
                    label="微信推送权限"
                  >
                    <Switch
                      checkedChildren="是"
                      unCheckedChildren="否"
                      defaultChecked={copyData?.PushPermission}
                      // defaultChecked={detail ? !!copyData.PushPermission : true}
                      onChange={(e) => {
                        setShowWeChatFlag(e)
                      }}
                    />
                  </Form.Item>
                </Col>
                {/* { */}
                {/*   <span onClick={()=>{ */}
                {/*     showFormdetail() */}
                {/*   }}> 111</span> */}
                {/* } */}
                {
                  showWeChatFlag && initialDetail?.USER_PATTERN !== 2000 ?
                    <Col span={6}>
                      <ProForm.Item
                        label="推送类型"
                        name="UserTypeIds"
                        rules={[
                          {
                            required: showWeChatFlag,
                            message: '请选择推送类型',
                          }
                        ]}
                      >
                        <Radio.Group onChange={(e: any) => {
                          setShowServiceList(e.target.value)
                          setServiceList([])
                          setSPRegionList([])
                          detailForm.current?.setFieldsValue({ ServerpartIds: [] })
                          getServiceList(selectDetail || null, e.target.value)
                        }} value={showServiceList}>
                          <Radio value={1000}>业主本部</Radio>
                          <Radio value={1010}>服务区</Radio>
                          <Radio value={1020}>区域</Radio>
                        </Radio.Group>
                      </ProForm.Item>
                    </Col> : ''
                }
                {
                  showWeChatFlag && showServiceList && showServiceList !== 1000 ?
                    <Col span={14}>
                      <ProForm.Item
                        label={showServiceList === 1010 ? "服务区" : "区域"}
                        name="ServerpartIds"
                        rules={[
                          {
                            required: showWeChatFlag && showServiceList !== 1000,
                            message: showServiceList === 1010 ? "请选择推送服务区" : "请选择推送区域",
                          }
                        ]}
                      >
                        <TreeSelect
                          showSearch
                          allowClear
                          style={{ width: '100%' }}
                          // 拿数组里面的指定字段给树形选择器当对应字段
                          fieldNames={{ label: 'label', value: 'key', children: 'children' }}
                          multiple={true}
                          treeCheckable={true}
                          treeDefaultExpandAll
                          onChange={(e) => {
                          }}
                          treeData={SPRegionList}
                        />
                      </ProForm.Item>
                    </Col> : ''
                }
              </Row>
              : ''
          }
        </Card>
        <Card title="授予账号权限" style={{ marginTop: 24 }} bordered={false} size="default">
          <Row gutter={24}>
            {
              tableTab === '1000' || tableTab === '4000' || tableTab === '9000' ?
                <Col span={8}>
                  {serverpartTree &&
                    <Card
                      style={{ borderColor: "#97D6FE", height: 424 }}
                      size="small"
                      title="服务区权限" headStyle={{ backgroundColor: '#E7F7FF' }}
                      extra={<a onClick={() => {
                        setCheckedServerpart([])
                        detailForm.current?.setFieldsValue({ ServerpartList: [] })
                      }}>取消选择</a>}>
                      <Form.Item name="ServerpartList" style={{ marginBottom: 0 }}>
                        <Tree
                          checkedKeys={checkedServerpart}
                          defaultCheckedKeys={checkedServerpart}
                          // defaultExpandedKeys={checkedServerpart}
                          treeData={serverpartTree}
                          height={360}
                          checkable
                          fieldNames={{
                            title: 'label',
                            key: 'value'
                          }}
                          onCheck={(checkedKeys: React.Key[] | any) => {

                            setCheckedServerpart(checkedKeys)
                            return checkedKeys
                          }}
                        ></Tree>
                      </Form.Item>
                    </Card>}
                </Col>
                : ''
            }

            {/* {(currentUser?.UserPattern === 9000 ? initialDetail.USER_PATTERN === 1000 : currentUser?.UserPattern === 1000) && } */}

            {
              (initialDetail.USER_PATTERN === 2000 && initialDetail.BUSINESSMAN_NAME) || (pageType === 'merchantManagement' && BUSINESSMAN_ID?.label) ?
                <Col span={8}>
                  {
                    shopTree && shopTree.length > 0 ?
                      < Card
                        style={{ borderColor: "#97D6FE", height: 424 }}
                        size="small"
                        title="门店权限" headStyle={{ backgroundColor: '#E7F7FF' }}
                        extra={<a onClick={() => {
                          setCheckedServerpart([])
                          setCheckedShop([])
                          detailForm.current?.setFieldsValue({ ServerpartList: [], ServerpartShopList: [] })
                        }}>取消选择</a>}>
                        <Form.Item name="ServerpartList" style={{ marginBottom: 0 }}>
                          <Tree
                            // checkedKeys={checkedServerpart}
                            defaultCheckedKeys={checkedShop}
                            defaultExpandedKeys={checkedShop}
                            treeData={shopTree}
                            height={360}
                            checkable
                            fieldNames={{
                              title: 'label',
                              key: 'value'
                            }}
                            onCheck={(checkedKeys: React.Key[] | any, info: any) => {

                              if (info.checkedNodes.length > 0) {

                                const checkedPart = info.checkedNodes.reduce((accumulator, current) => {
                                  accumulator[current.type].push(current.value)
                                  return accumulator
                                }, { 1: [], 2: [] })
                                setCheckedServerpart(checkedPart[1])
                                setCheckedShop(checkedPart[2])
                                // setInitialDetail({ ...initialDetail, ServerpartShopList: checkedPart[2] })
                              } else {
                                setCheckedServerpart([])
                                setCheckedShop([])
                                // setInitialDetail({ ...initialDetail, ServerpartShopList: [] })
                              }
                              return checkedKeys
                            }}
                          ></Tree>
                        </Form.Item>
                      </Card> : ''
                  }
                </Col>
                : ''
            }
            <Col span={8} >
              {roleTree && <Card
                style={{ borderColor: "#97D6FE", height: 424 }}
                size="small"
                title="角色权限"
                headStyle={{ backgroundColor: '#E7F7FF' }}
                extra={<a onClick={() => {
                  setCheckedRole([])
                  detailForm.current?.setFieldsValue({ SystemRoleList: [] })
                }}>取消选择</a>}>
                <Form.Item name="SystemRoleList" style={{ marginBottom: 0 }}>
                  <Tree
                    checkedKeys={checkedRole}
                    defaultCheckedKeys={checkedRole}
                    defaultExpandedKeys={checkedRole}
                    treeData={roleTree}
                    height={330}
                    checkable
                    fieldNames={{
                      title: 'SYSTEMROLE_NAME',
                      key: 'SYSTEMROLE_ID'
                    }}
                    onCheck={(checkedKeys: React.Key[] | any) => {
                      setCheckedRole(checkedKeys)
                      if (checkedKeys.length > 0) {
                        getRoleMenu(checkedKeys.toString())
                      }
                      return checkedKeys
                    }}
                  ></Tree>
                </Form.Item>
              </Card>
              }
            </Col>
            {checkedRole && checkedRole.length > 0 && <Col span={8}>
              <Card
                style={{ borderColor: "#97D6FE", height: 424 }}
                size="small"
                title="已选角色的模块权限"
                headStyle={{ backgroundColor: '#E7F7FF' }}
              >
                <Tree
                  defaultExpandAll
                  treeData={roleMenuTree || []}
                  height={330}
                  fieldNames={{
                    title: 'label',
                  }}
                ></Tree>
              </Card>
            </Col>}
          </Row>
        </Card>
        {
          companyList && companyList.length > 0 ?
            <Card title="推送权限" style={{ marginTop: 24 }}>
              <div style={{ display: 'flex' }}>
                {/* 遍历公众号列表  展示item */}
                {
                  companyList.map((item: any) => {
                    return <div style={{ marginRight: '5%' }}>
                      {/* <span>{companyType[item.type]}</span> */}
                      <span>{`${item.label}公众号: ${companyType[item.type]}的每日营收汇总通知`}</span>
                    </div>
                  })
                }
              </div>
            </Card> : ''
        }
      </ProForm>

      <BusinessManDrawer showDrawer={showAddDrawer} setShowDrawer={setShowAddDrawer} pageType={'edit'} afterOk={handleGetMerchantTree} />


    </PageContainer >
  )
}
export default Edit;
