/* eslint-disable array-callback-return,no-undef,prefer-destructuring */
import React, { Component } from 'react';
import { Modal, message } from 'antd-v4';
import commonConfig from '../../utils/config';
import * as commonBusiness from './commonBusiness'; /* 单据业务功能 */
import * as commonUtils from '../../utils/utils'; /* 通用方法 */
import * as commonServices from './../../services/services';
import * as commonFunc from './commonFunc'; /*   服务类   */

const { confirm } = Modal;

export default (ChildComponent) => {
  return class extends Component {
    constructor(props) {
      super(props);
      this.state = {};
      this.form = {};
      /*   表单对象   */
    }

    componentWillReceiveProps(nextProps) {
      const {
        formData, currentId, groupConfig, treeData, formRoute,
      } = nextProps;
      let { bReceived } = nextProps;
      const sId = currentId || nextProps.masterData?.sId || '';

      if (commonUtils.isEmptyObject(groupConfig) && bReceived === undefined) {
        const masterConfig = formData.filter(item => !item.bGrd)[0];
        this.handleGetChangeData({ name: 'tree' }, 'SysjurisdictionTree');
        bReceived = true;
        const group = this.initColumnConfig('group', [
          this.imitateTableColumn('序号', 'iOrder', 'iOrder', 60),
          this.imitateTableColumn('权限组', 'sName', 'sId', 350)]);


        const userGroup = this.initColumnConfig('userGroup', [
          this.imitateTableColumn('序号', 'iOrder', 'iOrder', 60),
          this.imitateTableColumn('组成员', 'sUserName', 'sUsersId', 350)]);

        const user = this.initColumnConfig('userView', [
          this.imitateTableColumn('序号', 'iOrder', 'iOrder', 60),
          this.imitateTableColumn('用户', 'sUserName', 'sId', 120),
          this.imitateTableColumn('权限组', 'sGroupName', 'sGroupName', 350)]);

        const groupUser = this.imitateTableColumnConfig('groupUser', [this.imitateTableColumn('所属分组', 'sGroupName', 'sGroupsId')]);

        const checkedNodes = this.imitateTableColumnConfig('checkedNodes', [this.imitateTableColumn('名称', 'showName', 'sId')]);

        const tree = this.imitateTableColumnConfig('tree', [this.imitateTableColumn('名称', 'showName', 'key')]);

        const search = this.imitateTableColumnConfig('search', [this.imitateTableColumn('名称', 'showName', 'sAllId', 300)]);

        let treeKeyName = 'key';
        if (formRoute === '/indexPage/systemPermission') {
          treeKeyName = 'sId';
        }
        this.props.onSaveState({
          masterConfig,
          sId,
          bReceived,
          treeKeyName,
          showLine: false,
          // pageLoading: false,
          ...tree,
          ...group,
          ...user,
          ...userGroup,
          ...groupUser,
          ...checkedNodes,
          ...search,
        });
      }
      if (commonUtils.isNotEmptyArr(treeData) && bReceived) {
        this.handleGetChangeData({ name: 'group' }, 'GroupData');
        this.handleGetChangeData({ name: 'userView' }, 'UserData');
        this.props.onSaveState({
          bReceived: false,
          pageLoading: false,
        });
      }
    }


    shouldComponentUpdate(nextProps, nextState) {
      let flag = true;
      /* 追加弹出框数值回填放行判断ppopupPane */
      if (nextProps.sTabId === nextProps.app.currentPane.key || ((nextProps.app.ppopupPane !== undefined
        && nextProps.app.ppopupPane.mainConfig !== undefined)
        ? nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key : false)) {
        if (nextState.disabled !== this.state.disabled) {
          return true;
        }
        flag = true;
      } else {
        flag = false;
      }
      return flag;
    }

    componentWillUpdate(nextProps) {
      const { masterData, sModelsType, elemachineData } = nextProps;
      if (sModelsType === 'element/teamInfo' && masterData !== undefined) {
        if (commonUtils.isNotEmptyObject(elemachineData)) {
          elemachineData.forEach((row, index) => {
            if (row.sMachineId === masterData.sMachineId) {
              elemachineData[index].bDefault = true;
            } else {
              elemachineData[index].bDefault = false;
            }
          });
        }
      }
    }


    /**   表单回带   */
    handleForm = (form) => {
      this.form = form;
    };
    /** 主表控件是否全部显示 */
    handleToggle = () => {
      const { expand } = this.props;
      this.props.onSaveState({ expand: !expand });
    };

    handleValidateSave = async () => {
      const {
        token, sModelsId, sJurisdictionClassifyId, sUserId, treeAllNodes, treeCheckedKeys = [], treeAllCheckKeys,
        app,
      } = this.props;
      const value = {};
      if ((commonUtils.isEmptyArr(sJurisdictionClassifyId) && commonUtils.isEmptyArr(sUserId))) {
        message.warn(commonFunc.showMessage(app.commonConst, 'NotEmptyJurisdictionGroup'));/*  组员，所属或权限组不能为空!   */
        this.props.onSaveState({
          loading: false,
        });
        return;
      }
      if (commonUtils.isNotEmptyArr(sJurisdictionClassifyId) && commonUtils.isEmptyArr(sUserId)) {
        value.sJurisdictionClassifyId = sJurisdictionClassifyId[0];
      } else if (commonUtils.isNotEmptyArr(sUserId) && commonUtils.isEmptyArr(sJurisdictionClassifyId)) {
        value.sUserId = sUserId[0];
      } else {
        message.warn(commonFunc.showMessage(app.commonConst, 'NotEmptyGroup'));/* 组或者组员不能为空 */
        this.props.onSaveState({
          loading: false,
        });
        return;
      }
      /*
      if (commonUtils.isNotEmptyArr(treeCheckedKeys) && treeCheckedKeys.length === treeAllCheckKeys.length) {
        message.warn('请选择不需要的权限!');
        return;
      }
      */
      const newCheckedKeys = []; /* 所有选中节点 */
      const saveData = [];

      // 取 选中数据 用-分割后的最后一个值
      const treeCheckedKeysNew = treeCheckedKeys.map((item) => {
        const list = item.split('-');
        return list[list.length - 1];
      });

      treeAllCheckKeys.forEach((key) => {
        const iIndex = treeCheckedKeysNew.indexOf(key);
        if (iIndex > -1) {
          newCheckedKeys.push(key);
        }
      });
      newCheckedKeys.forEach((key) => {
        const nodes = treeAllNodes.get(key);
        saveData.push({
          sId: nodes.sId,
          sParentId: nodes.sParentId,
          // sKey: nodes[`${skeyName}`],
          sKey: nodes.key,
          sName: commonUtils.isNotEmptyObject(nodes) && commonUtils.isNotEmptyObject(nodes.sName) ? nodes.sName : '',
          sAction: commonUtils.isNotEmptyObject(nodes) && commonUtils.isNotEmptyObject(nodes.sAction) ? nodes.sAction : '',
          showName: nodes.showName,
        });
      });

      value.data = saveData;
      value.sTreeAllKet = treeAllCheckKeys;

      const dataUrl = `${commonConfig.server_host}/sysjurisdictionNew/addSysjurisdictionNew?sModelsId=${sModelsId}`;
      const dataReturn = (await commonServices.postValueService(token, value, dataUrl)).data;
      /*   成功的话返回数据   */
      if (dataReturn.code === 1) { /*   成功   */
        message.success(dataReturn.msg);
        this.props.onSaveState({ enabled: false, loading: false });
        return dataReturn;
      } else { /*   失败   */
        this.props.getServiceError(dataReturn);
        this.props.onSaveState({
          loading: false,
        });
        return false;
      }
    }

    /**   点击修改按钮操作   */
    handleEdit = () => {
      this.props.onSaveState({ enabled: true, loading: false });
    }
    handleCancel = (obj) => {
      // const { groupUserData } = this.props;
      // const onGetChangeData = this.handleGetChangeData;
      const onSaveStateOk = this.props.onSaveState;
      confirm({
        title: obj.title,
        onOk() {
          // const sId = commonUtils.isNotEmptyArr(groupUserData) && groupUserData.length > 0 ? groupUserData[0].sId : '';
          onSaveStateOk({ enabled: false });
          // onGetChangeData({ name: 'authority', sId }, 'GroupAuthority');
        },
        onCancel() {
        },
      });
    }

    handleGetSisformulaData = (masterConfig) => {
      this.handleGetSlaveData('One', null, masterConfig);
    }

    handleGetSlaveData = (getType, sName, currConfig) => {
      const { currentId } = this.props;
      /* 当前页签数据 */
      const sId = currentId || this.props.masterData?.sId || '';
      if (getType === 'One') {
        this.props.handleGetDataOne({
          name: 'master', configData: currConfig, condition: { sId, pageSize: '', pageNum: '' },
        });
      }
      if (getType === 'Set') {
        this.props.handleGetDataSet({
          name: sName, configData: currConfig, condition: { sSqlCondition: { sParentId: sId } },
        });
      }
    }
    /*  获取分组列表
    yw_权限分配
    获取分组列表
    获取人员列表
    qx_获取权限树
    qx_根据组sId获取已选择权限
    qx_根据人sId获取已选择权限
    qx_根据组sId获取组人员
    根据人员sId获取所属分组
    保存组已选权限
    * */
    handleGetChangeData = async (params, urlKey) => {
      const { app, sModelsId } = this.props;
      const { token } = app;
      const { name, sId, treeComponentName } = params; // name,
      let dataUrl = '';
      if (urlKey === 'SysjurisdictionTree') { // 树结构
        dataUrl = `${commonConfig.server_host}sysjurisdictionNew/getSysjurisdictionTreeNew?sModelsId=${sModelsId}`;
      } else if (urlKey === 'GroupData') { // 组
        dataUrl = `${commonConfig.server_host}sysjurisdictionNew/getGroupDataNew?sModelsId=${sModelsId}`;
      } else if (urlKey === 'UserData') { // 用户
        dataUrl = `${commonConfig.server_host}sysjurisdictionNew/getUserDataNew?sModelsId=${sModelsId}`;
      } else if (urlKey === 'UserGroupId') { // 组成员
        if (commonUtils.isNotEmptyObject(sId)) {
          dataUrl = `${commonConfig.server_host}sysjurisdictionNew/getsUserGroupIdNew/${sId}?sModelsId=${sModelsId}`;
        }
      } else if (urlKey === 'GroupAuthority') { // 组权限
        if (commonUtils.isNotEmptyObject(sId)) {
          dataUrl = `${commonConfig.server_host}sysjurisdictionNew/getHaveAuthorityGroupIdNew/${sId}?sModelsId=${sModelsId}`;
        }
      } else if (urlKey === 'UserAuthority') { // 用户所有权限查询 :用户权限，组权限
        if (commonUtils.isNotEmptyObject(sId)) {
          dataUrl = `${commonConfig.server_host}sysjurisdictionNew/getHaveAuthorityUserIdNew/${sId}?sModelsId=${sModelsId}`;
        }
      }
      if (commonUtils.isNotEmptyObject(dataUrl)) {
        const dataReturn = (await commonServices.getService(token, dataUrl)).data;
        if (commonUtils.isNotEmptyObject(dataReturn) && dataReturn.code === 1) {
          const returnData = dataReturn.dataset.rows;
          let addState = {};
          if (urlKey === 'SysjurisdictionTree') { // 树结构
            const allInitArr = [];
            const allInitMap = new Map();
            this.handleAllCheckKeys(allInitArr, allInitMap, returnData);
            this.props.onSaveState({ [`${name}Data`]: returnData, treeAllCheckKeys: allInitArr, treeAllNodes: allInitMap });
          } else if (urlKey === 'GroupData') { // 获取组后默认查询组权限，以及组成员
            this.props.onSaveState({ [`${name}Data`]: returnData });
            if (commonUtils.isNotEmptyArr(returnData)) {
              this.handleTableSelectRowChange('group', [returnData[0].sId]); // 查询第一组成员
            }
          } else if (urlKey === 'UserData') { // 获取成员后默认 成员自己的权限，以及成员所属组
            this.props.onSaveState({ [`${name}Data`]: returnData });
            // if (commonUtils.isNotEmptyArr(returnData)) {
            //   this.handleGetChangeData({ name: 'groupUser', sId: returnData[0].sId }, 'GroupUserId'); // 查询第一个成员归属组
            // }
          } else if (urlKey === 'GroupAuthority' || urlKey === 'UserAuthority') {
            let groupAuth = '';
            let groupAuthData = [];
            if (commonUtils.isNotEmptyArr(returnData)) {
              if (commonUtils.isNotEmptyObject(returnData[0])) {
                groupAuth = commonUtils.isNotEmptyObject(returnData[0]) ? returnData[0].sKeys : [];
                groupAuthData = commonUtils.isNotEmptyObject(groupAuth) ? groupAuth.split(',') : [];
              }
            }
            addState = this.handleCheckedNodeForFunction(treeComponentName, groupAuthData);
            this.props.onSaveState({
              [`${name}Data`]: returnData, userAuth: undefined, sJurisdictionClassifyId: sId, sUserId: undefined, ...addState,
            });
          } else if (false && urlKey === 'UserAuthority') {
            let gAuth = '';
            let groupAuthData = [];
            let uAuth = '';
            let userAuthData = [];
            if (commonUtils.isNotEmptyArr(returnData)) {
              if (commonUtils.isNotEmptyObject(returnData[0])) {
                const { groupAuth, userAuth } = returnData[0];
                if (commonUtils.isNotEmptyObject(groupAuth)) {
                  gAuth = groupAuth.sKeys;
                  groupAuthData = gAuth.split(',');
                }

                if (commonUtils.isNotEmptyObject(userAuth)) {
                  uAuth = userAuth.sKeys;
                  userAuthData = uAuth.split(',');
                }
              }
            }
            addState = this.handleGroupForFunction(treeComponentName, groupAuthData, userAuthData);
            this.props.onSaveState({
              [`${name}Data`]: returnData, userAuthData, sJurisdictionClassifyId: undefined, sUserId: sId, ...addState,
            });
          } else {
            this.props.onSaveState({ [`${name}Data`]: returnData });
          }
        } else {
          this.props.getServiceError(dataReturn);
        }
      }
    }

    // 模拟 列
    imitateTableColumn = (title, dataIndex, key, width) => {
      return {
        title, dataIndex, key, width,
      };
    }
    // 模拟config的 gdsconfigformslave 配置
    imitateTableConfig = (title, dataIndex, width) => {
      const {userinfo} = this.props.app;
      return {
        bCanInput: false,
        bFilter: false,
        bFind: false,
        bFirstEmpty: false,
        bIsOther: false,
        bNewRecord: false,
        bNotEmpty: false,
        bNotRepeat: false,
        bReadonly: true,
        bSum: false,
        bTree: false,
        bVisible: true,
        iColValue: 1,
        iFitWidth: width,
        sBrandsId: '1111111111',
        sChinese: title,
        sChineseDropDown: '',
        sControlName: 'BtnLast',
        sId: commonUtils.createSid(),
        sParentId: '11811781131121915102156308120',
        sSubsidiaryId: '1111111111',
        showName: userinfo.sLanguage === 'sEnglish' ? dataIndex : title,
        sName: dataIndex,
      };
    }
    // 根据模拟列，模拟列配置
    imitateTableColumnConfig = (name, columns) => {
      const gdsconfigformslave = [];
      columns.forEach((itmes) => {
        gdsconfigformslave.push(this.imitateTableConfig(itmes.title, itmes.dataIndex, itmes.width));
      });
      const config = { bGrd: true, gdsconfigformslave };
      return { [`${name}Column`]: columns, [`${name}Config`]: config };
    }

    initColumnConfig = (name, columns) => {
      const gdsconfigformslave = [];
      columns.forEach((itmes) => {
        gdsconfigformslave.push(this.imitateTableConfig(itmes.title, itmes.dataIndex, itmes.width));
      });
      const config = { bGrd: true, gdsconfigformslave };
      const newColumns = commonFunc.getHeaderConfig(config);
      return { [`${name}Column`]: newColumns, [`${name}Config`]: config };
    }


    /**   处理选择行发生改变   */
    handleTableSelectRowChange = (name, selectedRowKeys) => {
      const addState = {};
      if (name === 'group') {
        this.handleGetChangeData({ name: 'userGroup', sId: selectedRowKeys }, 'UserGroupId');
        this.handleGetChangeData({ name: 'master', sId: selectedRowKeys, treeComponentName: 'tree' }, 'GroupAuthority');
        addState.groupSelectedRowKeys = selectedRowKeys;
      } else if (name === 'userView') {
        // this.handleGetChangeData({ name: 'groupUser', sId: selectedRowKeys }, 'GroupUserId');
        this.handleGetChangeData({ name: 'master', sId: selectedRowKeys, treeComponentName: 'tree' }, 'UserAuthority');
        addState.userViewSelectedRowKeys = selectedRowKeys;
      } else if (name === 'userGroup') {
        this.handleGetChangeData({ name: 'master', sId: selectedRowKeys, treeComponentName: 'tree' }, 'UserAuthority');
        addState.userGroupSelectedRowKeys = selectedRowKeys;
      } else if (name === 'groupUser') {
        this.handleGetChangeData({ name: 'master', sId: selectedRowKeys, treeComponentName: 'tree' }, 'GroupAuthority');
        addState.groupUserSelectedRowKeys = selectedRowKeys;
      }
      this.props.onSaveState({ ...addState });
    }

    handleCheckBoxCheck = (componentName, checkedKeys) => {
      this.handleCheckedForFunction(componentName, checkedKeys);
    }

    /* 选择权限同时处理保存的数据以及将要展现的已选择权限  */
    handleCheckedForFunction = (componentName, checkedKeys) => {
      const {
        treeAllNodes,
      } = this.props;
      const data = [];
      const checkedData = [];
      if (commonUtils.isNotEmptyArr(treeAllNodes) && treeAllNodes.size > 0) {
        const newCheckedKeys = [];
        if (commonUtils.isNotEmptyArr(checkedKeys) && checkedKeys[0] !== null) {
          checkedKeys.forEach((key, i) => {
            if (checkedKeys.indexOf(key) === i) {
              newCheckedKeys.push(key);
            }
          });
          newCheckedKeys.forEach((key) => {
            const nodes = treeAllNodes.get(key);
            if (commonUtils.isNotEmptyObject(nodes)) {
              checkedData.push({ sId: nodes.sId, showName: nodes.showName });
            }
          });
        }
        this.props.onSaveState({
          [`${componentName}CheckedKeys`]: newCheckedKeys,
          treeSaveParams: data,
          checkedNodesData: checkedData,
        });
      }
    }

    /* 拿接口返回的节点进行选中 */
    handleCheckedNodeForFunction = (componentName, haveCheckedKeys) => {
      // eslint-disable-next-line no-unused-vars
      const { treeAllNodes, treeAllCheckKeys } = this.props;
      const addState = {};
      const checkedData = [];
      let checkKeys = [];
      checkKeys = haveCheckedKeys;
      // if (commonUtils.isNotEmptyArr(unCheckedKeys)) {
      //   for (const checkId of unCheckedKeys) {
      //     treeAllCheckKeys.forEach((key) => {
      //       if (checkId.includes(key)) {
      //         checkKeys.forEach((item, index) => {
      //           if (item === key) {
      //             checkKeys.splice(index, 1);
      //           }
      //         });
      //       }
      //     });
      //   }
      // }
      checkKeys.forEach((key) => {
        const nodes = treeAllNodes.get(key);
        if (commonUtils.isNotEmptyObject(nodes)) {
          checkedData.push({ sId: nodes.sId, showName: nodes.showName });
        }
      });
      addState[`${componentName}CheckedKeys`] = checkKeys;
      addState.checkedNodesData = checkedData;
      addState.disabledCheckedKeys = [];
      return addState;
    }


    handleUnCheckedForFunction = (componentName, unCheckedKeys) => {
      const { treeAllNodes, treeAllCheckKeys } = this.props;
      const addState = {};
      const checkedData = [];
      let checkKeys = [];
      checkKeys = checkKeys.concat(treeAllCheckKeys);

      if (commonUtils.isNotEmptyArr(unCheckedKeys)) {
        for (const checkId of unCheckedKeys) {
          treeAllCheckKeys.forEach((key) => {
            if (checkId.includes(key)) {
              checkKeys.forEach((item, index) => {
                if (item === key) {
                  checkKeys.splice(index, 1);
                }
              });
            }
          });
        }
      }
      checkKeys.forEach((key) => {
        const nodes = treeAllNodes.get(key);
        if (commonUtils.isNotEmptyObject(nodes)) {
          checkedData.push({ sId: nodes.sId, showName: nodes.showName });
        }
      });
      addState[`${componentName}CheckedKeys`] = checkKeys;
      addState.checkedNodesData = checkedData;
      addState.disabledCheckedKeys = [];
      return addState;
    }

    handleGroupForFunction = (treeComponentName, groupAuthData, userAuthData) => {
      const { treeAllNodes, treeAllCheckKeys } = this.props;
      const addState = {};
      const checkedData = [];
      let checkKeys = [];
      let userAuthDataNew = [];
      checkKeys = checkKeys.concat(treeAllCheckKeys);
      if (commonUtils.isEmptyArr(userAuthData)) { /* 只有组权限 没有用户权限时 */
        userAuthDataNew = JSON.parse(JSON.stringify(groupAuthData)); /* 深拷贝  */
        userAuthData = userAuthDataNew;
      }
      if (commonUtils.isNotEmptyArr(userAuthData)) {
        treeAllCheckKeys.forEach((key) => {
          for (const checkId of userAuthData) {
            if (checkId.includes(key)) {
              checkKeys.forEach((item, index) => {
                if (item === key) {
                  checkKeys.splice(index, 1);
                }
              });
            }
          }
        });
        checkKeys.forEach((key) => {
          const nodes = treeAllNodes.get(key);
          if (commonUtils.isNotEmptyObject(nodes)) {
            checkedData.push({ sId: nodes.sId, showName: nodes.showName });
          }
        });
      }

      let groupCheckKeys = [];
      if (commonUtils.isNotEmptyArr(groupAuthData)) {
        groupCheckKeys = groupCheckKeys.concat(treeAllCheckKeys);
        treeAllCheckKeys.forEach((key) => {
          for (const checkId of groupAuthData) {
            if (checkId === key) {
              groupCheckKeys.splice(groupCheckKeys.indexOf(key), 1);
            }
          }
        });
      } else {
        groupCheckKeys = treeAllCheckKeys; /* 组权限没有 */
      }
      addState[`${treeComponentName}CheckedKeys`] = checkKeys.concat(groupCheckKeys);
      addState.checkedNodesData = checkedData;
      addState.disabledCheckedKeys = groupCheckKeys;
      return addState;
    };

    handleAllCheckKeys = (arrObj, mapObj, returnData) => {
      const { treeKeyName } = this.props;
      returnData.forEach((item) => {
        if (commonUtils.isNotEmptyArr(item.children) && item.children.length > 0) {
          arrObj.push(item[`${treeKeyName}`]);
          mapObj.set(item[`${treeKeyName}`], item);
          this.handleAllCheckKeys(arrObj, mapObj, item.children);
        } else {
          arrObj.push(item[`${treeKeyName}`]);
          mapObj.set(item[`${treeKeyName}`], item);
        }
      });
    };
    handleRefresh = () => {
      this.handleGetChangeData({ name: 'tree' }, 'SysjurisdictionTree');
      this.handleGetChangeData({ name: 'group' }, 'GroupData');
      this.handleGetChangeData({ name: 'user' }, 'UserData');
      this.props.onSaveState({
        treeAllCheckKeys: undefined,
        treeAllNodes: undefined,
      });
    }
    handleSearch = async (sSearchValue) => {
      const { sModelsId } = this.props;
      const url = `${commonConfig.server_host}gdsmodule/getGdsmoduleList?sModelsId=${sModelsId}&sName=${sSearchValue}`;
      const dataReturn = (await commonServices.getService(this.props.app.token, url)).data;
      if (dataReturn.code === 1) {
        /*   数据查询成功   */
        this.props.onSaveState({ searchData: dataReturn.dataset.rows });
      } else { /*   失败   */
        this.props.getServiceError(dataReturn);
      }
    }
    handleSetTreeOptionData = (name, optionName, value) => {
      this.props.onSaveState({ [`${name}${optionName}Keys`]: value });
    }

    handleSearchTable = async (searchValue, type) => {
      const { token, sModelsId } = this.props;
      let dataUrl = '';
      if (commonUtils.isNotEmptyObject(type)) {
        if (type === 'group') {
          /* 组权限 */
          dataUrl = `${commonConfig.server_host}sysjurisdictionNew/getGroupDataNew?sSearchName=${searchValue}&sModelsId=${sModelsId}`;
        } else if (type === 'userView') { /* 用户权限 */
          dataUrl = `${commonConfig.server_host}sysjurisdictionNew/getUserDataNew?sSearchName=${searchValue}&sModelsId=${sModelsId}`;
        }
        if (commonUtils.isNotEmptyObject(dataUrl)) {
          const dataReturn = (await commonServices.getService(token, dataUrl)).data;
          if (dataReturn.code === 1) {
            const returnData = dataReturn.dataset.rows;
            if (commonUtils.isNotEmptyArr(type)) {
              this.props.onSaveState({ [`${type}Data`]: returnData });
            }
          }
        }
      }
    }

    /* 查询组权限 */
    handleSearchGroup = async (searchValue) => {
      this.handleSearchTable(searchValue, 'group');
    }

    /* 查询用户权限 */
    handleSearchUser = async (searchValue) => {
      this.handleSearchTable(searchValue, 'userView');
    }
    /** 按钮操作事件 */
    handleButtonClick = (name, isFresh) => {
      const selectUserPermission = commonFunc.showLocalMessage(this.props, 'selectUserPermission', '选择用户权限');
      const selectGroupPerssion = commonFunc.showLocalMessage(this.props, 'selectGroupPerssion', '选择组权限');
      if (name.includes('BtnRepairGroup')) {
        const { sJurisdictionClassifyId } = this.props;
        if (commonUtils.isNotEmptyArr(sJurisdictionClassifyId)) {
          const filterData = this.props.masterConfig.gdsconfigformslave.filter(item => (item.sControlName === name));
          const btnConfig = commonUtils.isNotEmptyArr(filterData) ? filterData[0] : {};// sButtonEnabled  sButtonParam
          console.log(333, btnConfig);
          if (commonUtils.isNotEmptyObject(btnConfig) && commonUtils.isNotEmptyStr(btnConfig.sButtonParam)) {
            /* 找到组配置 */
            const sToGroupConfig = this.props.masterConfig.gdsconfigformslave.filter(item => item.sName === 'sCopyToGroupName');
            console.log(332, sToGroupConfig);
            if (commonUtils.isNotEmptyArr(sToGroupConfig)) {
              this.props.onSaveState({ groupModalVisible: true, sToGroupConfig, sGroupId: sJurisdictionClassifyId }); /* 打开复制从窗体sJurisdictionClassifyId */
            }
          }
        } else {
          message.error(selectGroupPerssion);
        }
      } else if (name.includes('BtnRepairUser')) {
        const { userViewSelectedRowKeys } = this.props;
        if (commonUtils.isNotEmptyArr(userViewSelectedRowKeys)) {
          const filterData = this.props.masterConfig.gdsconfigformslave.filter(item => (item.sControlName === name));
          const btnConfig = commonUtils.isNotEmptyArr(filterData) ? filterData[0] : {};// sButtonEnabled  sButtonParam
          console.log(filterData, filterData);
          if (commonUtils.isNotEmptyObject(btnConfig) && commonUtils.isNotEmptyStr(btnConfig.sButtonParam)) {
            /* 找到组配置 */
            const sToUserConfig = this.props.masterConfig.gdsconfigformslave.filter(item => item.sName === 'sCopyToUserName');
            console.log(332, sToUserConfig);
            if (commonUtils.isNotEmptyArr(sToUserConfig)) {
              this.props.onSaveState({ userModalVisible: true, sToUserConfig });
            }
          }
        } else {
          message.error(selectUserPermission);
        }
      } else if (name === 'BtnOut') {
        this.handleOut();
      } else if (name === 'BtnDesignFunction') {
        this.handleDesignFunction();
      } else if (name === 'BtnRefresh') {
        const {
          slaveConfig, slavePagination, slaveFilterCondition, slaveOrderBy,
        } = this.props;
        this.props.onSaveState({
          clearArray: [], searchText: '', slaveSelectedRowKeys: [], slaveSelectedData: [], slaveInfoSelectedRowKeys: [], slaveInfoSelectedData: [], treeSelectedKeys: [], treeFilterCondition: [], loading: false, pageLoading: true, isFresh,
        });
        if (slavePagination === undefined) return;
        this.handleGetData(slaveConfig, slaveFilterCondition, slavePagination.current, slavePagination.pageSize, slaveOrderBy, true); /*   刷新方法   */
        // if (formRoute === '/indexPage/materialRequirementsPlanning') {
        //   if (commonUtils.isNotEmptyObject(slaveInfoConfig)) {
        //     this.handleGetDataInfo(slaveInfoConfig, slaveFilterCondition, 1);
        //   }
        // }
        /* 判断是否要加载过滤树数据 */
        const filterTreeConfigArr = slaveConfig.gdsconfigformslave.filter(item => item.bTree);
        if (commonUtils.isNotEmptyArr(filterTreeConfigArr)) {
          const filterTreeConfig = filterTreeConfigArr[0];
          this.handleGetFilterTreeData(filterTreeConfig, slaveFilterCondition, 1);
        }
        const { clearArray } = this.props;
        if (!commonUtils.isEmpty(clearArray)) {
          for (const item of clearArray) {
            const { confirm, clearFilters } = item;
            confirm();
            clearFilters();
          }
        }
      } else if (name === 'BtnOutJurisdiction') {
        const { activeKey, app, sModelsId } = this.props;
        const { userinfo, token } = app;
        const { sBrandsId, sSubsidiaryId } = userinfo;
        const sType = activeKey === '3' ? 'user' : 'group';
        const url = `${commonConfig.server_host}sysjurisdictionNew/exportSysjurisdiction/${sBrandsId}/${sSubsidiaryId}/${sType}?sModelsId=${sModelsId}&token=${token}`;
        window.open(url);
      }
    };

    handleProcedureCall = async (btnConfig, proName, proInParam, other) => {
      const { app, sModelsId } = this.props;
      const value = { sProName: proName, sProInParam: proInParam };
      if (other?.iFlag === 1) {
        value.iFlag = 1;
      }
      const url = `${commonConfig.server_host}procedureCall/doGenericProcedureCall?sModelsId=${sModelsId}`;
      const returnData = (await commonServices.postValueService(app.token, value, url)).data;
      if (returnData.code === 1) {
        message.success(returnData.msg);
        // this.props.onButtonClick('BtnRefresh');
        // this.handleRefresh();
        this.handleGetChangeData({ name: 'group' }, 'GroupData');
        this.handleGetChangeData({ name: 'userView' }, 'UserData');
        this.props.onSaveState({ groupModalVisible: false, userModalVisible: false });
      } else {
        this.props.getServiceError({ ...returnData, fn: () => this.handleProcedureCall(btnConfig, proName, proInParam, { iFlag: 1 }) });
      }
      this.props.onSaveState({ loading: false });
    }

    handleCopyGroupModalOk =() => {
      const { sJurisdictionClassifyId, masterData } = this.props;
      const filterData = this.props.masterConfig.gdsconfigformslave.filter(item => (item.sControlName === 'BtnRepairGroup'));
      const btnConfig = commonUtils.isNotEmptyArr(filterData) ? filterData[0] : {};// sButtonEnabled  sButtonParam
      if (commonUtils.isNotEmptyObject(btnConfig) && commonUtils.isNotEmptyStr(btnConfig.sButtonParam)) {
        const inParams = [];
        const addState = {};
        addState.key = 'group';
        const val = [{
          sGroupId: commonUtils.isNotEmptyArr(sJurisdictionClassifyId) ? sJurisdictionClassifyId[0] : '',
          sToGroupId: commonUtils.isNotEmptyObject(masterData) && masterData.sCopyToGroupId,
        }];
        addState.value = val;
        inParams.push({ ...addState });
        this.handleProcedureCall(btnConfig, 'Sp_BtnEventCopyGroupJurisdiction', JSON.stringify({ params: inParams, changeValue: 'group' }));
      }
    };

    handleCopyUserModalOk =() => {
      const { userViewSelectedRowKeys, masterData } = this.props;
      const filterData = this.props.masterConfig.gdsconfigformslave.filter(item => (item.sControlName === 'BtnRepairUser'));
      const btnConfig = commonUtils.isNotEmptyArr(filterData) ? filterData[0] : {};// sButtonEnabled  sButtonParam
      if (commonUtils.isNotEmptyObject(btnConfig) && commonUtils.isNotEmptyStr(btnConfig.sButtonParam)) {
        const inParams = [];
        const addState = {};
        addState.key = 'user';
        const val = [{
          sUserId: commonUtils.isNotEmptyArr(userViewSelectedRowKeys) ? userViewSelectedRowKeys[0] : '',
          sToUserId: commonUtils.isNotEmptyObject(masterData) && masterData.sCopyToUserId,
        }];
        addState.value = val;
        inParams.push({ ...addState });
        this.handleProcedureCall(btnConfig, 'Sp_BtnEventCopyUserJurisdiction', JSON.stringify({ params: inParams, changeValue: 'user' }));
      }
    };

    handleModalCancel = (modelVisible) => {
      this.props.onSaveState({
        [modelVisible]: false,
      });
    };

    render() {
      const { masterData, sModelsType, app } = this.props;
      const imgSrc = commonBusiness.handleAddIcon(masterData, sModelsType, app);
      return (
        <ChildComponent
          {...this.props}
          {...this.state}
          onReturnForm={this.handleForm}
          onSubmit={this.handleValidateSave.bind(this, 'tree')}
          onEdit={this.handleEdit}
          onTableSelectRowChange={this.handleTableSelectRowChange}
          onCancel={this.handleCancel}
          imgSrc={imgSrc}
          onToggle={this.handleToggle}
          onTreeCheck={this.handleCheckBoxCheck}
          onRefresh={this.handleRefresh}
          onSearch={this.handleSearch}
          onDoubleClick={this.handleDoubleClick}
          onSetTreeOptionKeys={this.handleSetTreeOptionData}
          onSearchTable={this.handleSearchTable}
          onSearchGroup={this.handleSearchGroup}
          onSearchUser={this.handleSearchUser}
          onButtonClick={this.handleButtonClick}
          onCopyGroupModalOk={this.handleCopyGroupModalOk}
          onCopyUserModalOk={this.handleCopyUserModalOk}
          onModalCance={this.handleModalCancel}
        />
      );
    }
  };
};
