package com.fufan.mtsaas.modules.sysmgr.sygroup.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fufan.mtsaas.modules.base.log.bo.request.LogSaveRequest;
import com.fufan.mtsaas.modules.base.log.service.TSysLogSvc;
import com.fufan.mtsaas.modules.common.bo.response.RequestPojo;
import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.request.*;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.response.SYGroupMenuInfo;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.response.SYGroupQueryResponse;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.response.SYgroupHResponse;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.response.SysNewMenuResponse;
import com.fufan.mtsaas.modules.sysmgr.sygroup.service.SYgroupMenuSvc;
import com.fufan.mtsaas.modules.sysmgr.symenu.dao.SYmenuDao;
import com.fufan.mtsaas.modules.sysmgr.symenu.dao.SYmenubuttonDao;
import com.fufan.mtsaas.modules.sysmgr.symenu.dao.SysButtonDao;
import com.fufan.mtsaas.modules.sysmgr.symenu.dao.SysMenuDao;
import com.fufan.mtsaas.modules.sysmgr.symenu.model.SysMenu;
import com.fufan.mtsaas.modules.sysmgr.syuser.dao.SYuserDao;
import com.fufan.mtsaas.modules.sysmgr.syuser.model.SYuser;
import com.fufan.mtsaas.modules.base.company.dao.TCompanyDao;
import com.fufan.mtsaas.modules.base.company.model.TCompany;
import com.github.pagehelper.ISelect;
import com.fufan.mtsaas.constant.RedisKeyConstant;
import com.fufan.mtsaas.modules.sysmgr.sygroup.dao.SYgroupHDao;
import com.fufan.mtsaas.modules.sysmgr.sygroup.dao.SYgroupMenuDao;
import com.fufan.mtsaas.modules.sysmgr.sygroup.model.SYgroupH;
import com.fufan.mtsaas.modules.sysmgr.sygroup.model.SYgroupMenu;
import com.fufan.mtsaas.modules.sysmgr.sygroup.service.SYgroupHSvc;
import com.fufan.mtsaas.util.DateFormatTool;
import com.fufan.mtsaas.util.JSonUtil;
import com.fufan.mtsaas.util.ParamUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

import static com.fufan.mtsaas.cache.Cache.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Liby
 * @since 2019-08-18
 */
@Service("SYgroupHSvcImpl")
@Slf4j
@Primary
public class SYgroupHSvcImpl extends ServiceImpl<SYgroupHDao, SYgroupH> implements SYgroupHSvc {
    @Autowired
    private SYgroupHDao entitymDao;

    @Autowired
    private SYgroupMenuDao groupMenuDao;

    @Autowired
    private SYgroupMenuSvc groupMenuSvc;

    @Autowired
    private SYmenuDao menuDao;

    @Autowired
    private SYmenubuttonDao menubuttonDao;

    @Value("${COMPANY_CD}")
    private String COMPANY_CD;
    @Autowired
    private TCompanyDao tCompanyDao;
    @Autowired
    private SYuserDao sYuserDao;


    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private SysButtonDao sysButtonDao;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private TSysLogSvc tSysLogSvc;

    /**
     * 查询
     *
     * @param map
     * @return Result.class
     * */
    @Override
    public Result doQueryPage(GroupHQueryRequest map, RequestPojo requestPojo) {
        Result result = new Result();
        //分页查询
        Page page = new Page();
        page.setCurrent(map.getCurrentPage());
        page.setSize(map.getPageSize());
        log.debug("SYgroupHSvcImpl.doQueryPage parameter: {}", map);
        Map<String, String> mapData = new HashMap<>();

        Long GroupID = map.getId();
        String GroupName = map.getGroupName();
//        String GroupType = map.getGroupType();

        //赋值默认
//        if(StringUtils.isEmpty(CompanyID)){
//            CompanyID = COMPANY_CD;
//        }
        String CompanyID = requestPojo.getCustId();
        //测试注释
        mapData.put("CompanyID", CompanyID);
        if(Objects.nonNull(GroupID) && GroupID != 0) {
            mapData.put("ID", String.valueOf(GroupID));
        }
        mapData.put("GroupName", GroupName);
        mapData.put("companyName", map.getCompanyName());

        List<SYgroupH> entitys;

        //分页处理 -- 20192021 Liby
        long total = com.github.pagehelper.PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                entitymDao.selectListLike(page, mapData);
            }
        });
        ParamUtil.setPage(map.getPageSize(), map.getCurrentPage(), page);
        entitys = entitymDao.selectListLike(page, mapData);
        List<SYGroupQueryResponse> syGroupQueryResponseList = new ArrayList<>();
        for (SYgroupH sYgroupH: entitys){
            SYGroupQueryResponse syGroupQueryResponse = new SYGroupQueryResponse();
            BeanUtils.copyProperties(sYgroupH,syGroupQueryResponse);
            syGroupQueryResponse.setId(Long.valueOf(sYgroupH.getId()));
            syGroupQueryResponse.setUpdatedDT(sYgroupH.getUpdatedDT());
            syGroupQueryResponse.setCompanyName(COMPANY_MAP.get(sYgroupH.getCompanyID()));
//            syGroupQueryResponse.setSysNewMenuResponse(handleMenuRole(sYgroupH.getGroupID()));
            syGroupQueryResponseList.add(syGroupQueryResponse);
        }
        log.debug("SYgroupHSvcImpl.doQueryPage entitys: {}", entitys);
        page.setTotal((int) total);
        page.setRecords(syGroupQueryResponseList);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);
        return result;
    }
    private List<SysNewMenuResponse> handleMenuRole(String groupId){
        List<SysNewMenuResponse> result = new ArrayList<>();
        Page page = new Page<>();
        Map<String,String> map = new HashMap<>();
        map.put("GroupID",groupId);
        List<SYGroupMenuInfo> sYgroupMenuList = groupMenuDao.selectList(page,map);
        if(sYgroupMenuList.size() > 0){
            if(org.apache.commons.lang3.StringUtils.isNotEmpty(sYgroupMenuList.get(0).getRW())){
                JSONObject data = JSONObject.parseObject(sYgroupMenuList.get(0).getRW());
                JSONArray roles = data.getJSONArray("roles");
                JSONArray permissions = data.getJSONArray("permissions");
                List<SysMenu>  menuOneList = new ArrayList<>();
                List<SysMenu>  menuTwoList = new ArrayList<>();
                for (Object role : roles){
                    String roleString = (String)role;
                    if(MENU_MAP.containsKey(roleString)){
                        if(MENU_MAP.get(roleString).getMenuLevel() ==1){
                            menuOneList.add(MENU_MAP.get(roleString));
                        }
                        if(MENU_MAP.get(roleString).getMenuLevel() ==2){
                            menuTwoList.add(MENU_MAP.get(roleString));
                        }
                    }


                }
                Map<String,List<SysNewMenuResponse>> companyButtonMap = new HashMap<>();
                for (Object p : permissions){
                    String pString = (String)p;
                    if(!companyButtonMap.containsKey(pString.split(":")[1])){
                        List<SysNewMenuResponse> sysNewMenuResponseList = new ArrayList<>();
                        companyButtonMap.put(pString.split(":")[1],sysNewMenuResponseList);
                    }
                    SysNewMenuResponse sysNewMenuResponse = new SysNewMenuResponse();
                    sysNewMenuResponse.setCode(pString);
                    sysNewMenuResponse.setLabel(BUTTON_MAP.get(pString.split(":")[0]));
                    companyButtonMap.get(pString.split(":")[1]).add(sysNewMenuResponse);
                }

                //组合数据
                if(menuOneList.size() > 0 ){
                    for(SysMenu sysMenuOne : menuOneList){
                        SysNewMenuResponse sysNewMenuResponseOne = new SysNewMenuResponse();
                        sysNewMenuResponseOne.setLabel(sysMenuOne.getLabel());
                        sysNewMenuResponseOne.setCode(sysMenuOne.getMenuCode());
                        sysNewMenuResponseOne.setChildren(new ArrayList<>());
                        for(SysMenu sysMenuTwo : menuTwoList){
                          if(sysMenuOne.getMenuGroup().equals(sysMenuTwo.getMenuGroup())){
                              SysNewMenuResponse sysNewMenuResponseTwo = new SysNewMenuResponse();
                              sysNewMenuResponseTwo.setLabel(sysMenuTwo.getLabel());
                              sysNewMenuResponseTwo.setCode(sysMenuTwo.getMenuCode());
                              sysNewMenuResponseTwo.setChildren(companyButtonMap.get(sysMenuTwo.getMenuCode()));
                              sysNewMenuResponseOne.getChildren().add(sysNewMenuResponseTwo);
                          }
                        }
                        result.add(sysNewMenuResponseOne);
                    }
                }
            }
        }
       return result;
    }

//    public static void main(String[] args) {
//        String rw = "{\n" +
//                "    \"roles\": [\n" +
//                "        \"Sysconfig\",\n" +
//                "        \"Company\",\n" +
//                "        \"注册证\"\n" +
//                "    ],\n" +
//                "    \"permissions\": [\n" +
//                "        \"query:Company\",\n" +
//                "        \"detail:Company\",\n" +
//                "        \"add:Company\",\n" +
//                "        \"edit:Company\",\n" +
//                "        \"delete:Company\",\n" +
//                "        \"import:Company\",\n" +
//                "        \"export:Company\",\n" +
//                "        \"print:Company\",\n" +
//                "        \"preview:Company\",\n" +
//                "        \"query:注册证\",\n" +
//                "        \"detail:注册证\"\n" +
//                "    ]\n" +
//                "}";
//        JSONObject test =   JSONObject.parseObject(rw);
//        test.getJSONArray("roles").get(0)
//    }
    /**
     * 新增
     *
     * @param entitym
     * @param requestPojo
     * @return Result.class
     */
    @Override
    // @Transactional
    public Result doSave(SYgroupH entitym, RequestPojo requestPojo) {
        log.debug("SYgroupHSvcImpl.doSave parameter: {}", entitym);
        Result result = new Result();
        //非空验证
        if(StringUtils.isEmpty(entitym.getGroupName())){
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        //名称重复验证
        HashMap mapData = new HashMap();
        Page page = new Page();
        mapData.put("CompanyID", entitym.getCompanyID());
        mapData.put("GroupName", entitym.getGroupName());

        List<SYgroupH> entity = entitymDao.selectList(page, mapData);
        if(entity != null && entity.size() > 0){
            result.setResStatus(ResStatus.STATUS_EXISTENCE);
            result.setResMsg(ResStatus.STATUS_EXISTENCE_MSG);
            return result;
        }

        if (Objects.isNull(entitym.getVldFG())) {
            entitym.setVldFG("0");
        }

        entitym.setRegisteredPerson(requestPojo.getUserName());
        entitym.setRegisteredDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        entitym.setUpdatedPerson(requestPojo.getUserName());
        entitym.setUpdatedDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        try{
            int rec = entitymDao.insertRecords(entitym);
            entitym.setGroupID(String.valueOf(entitym.getId()));
            entitymDao.updateRecords(entitym);
            log.debug("新增数据返回 {}",rec);
            ROLE_MAP.put(Long.valueOf(entitym.getId()),entitym.getGroupName());
            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);

            result.setResData(page.setRecords(Arrays.asList(entitym)));
        }catch (Exception e){
            log.error("新增数据出错",e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("新增数据出错：" + e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus()().setRollbackOnly();
        }
        return result;

    }

    /**
     * 修改
     *
     * @param entitym
     * @param requestPojo
     * @return Result.class
     */
    @Override
    // @Transactional
    public Result doUpdate(SYgroupH entitym, RequestPojo requestPojo) {
        log.debug("SYgroupHSvcImpl.doUpdate parameter: {}", entitym);
        Result result = new Result();
        //非空验证
        if(StringUtils.isEmpty(String.valueOf(entitym.getId()))){
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        if (Objects.isNull(entitym.getVldFG())) {
            entitym.setVldFG("0");
        }

        entitym.setUpdatedPerson(requestPojo.getUserName());
        entitym.setUpdatedDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        try{
            int rec = entitymDao.updateRecords(entitym);
            log.debug("更新数据返回 {}",rec);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        }catch (Exception e){
            log.error("修改数据出错",e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("修改数据出错：" + e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus()().setRollbackOnly();
        }
        return result;

    }

    /**
     * 删除
     *
     * @param map
     * @return Result.class
     * */
    @Override
     @Transactional
    public Result doDelete(GroupHQueryRequest map, RequestPojo requestPojo) {
        Result result = new Result();
        log.debug("SYgroupHSvcImpl.doDelete parameter: {}", map);
        //非空验证
        String CompanyID = map.getCompanyID();
        String GroupID = String.valueOf(map.getId());

        if(StringUtils.isEmpty(GroupID)){
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        Page page = new Page();
        Map<String, String> mapData = new HashMap<>();
        mapData.put("CompanyID", CompanyID);
        mapData.put("ID", GroupID);
        List<SYgroupH> entitym = entitymDao.selectList(page, mapData);
        if(entitym == null || entitym.size() == 0){
            result.setResStatus(ResStatus.STATUS_UNAVAILABLE);
            result.setResMsg("数据不存在");
            return result;
        }

        if(map.getId() == null || map.getId() == 0){
            result.setResStatus(ResStatus.STATUS_USER_NOT_NULL);
            result.setResMsg(ResStatus.STATUS_USER_NOT_NULL_MSG);
            return result;
        }else {
            //为空读取token默认角色id
            Map<String,String> userMap = new HashMap<>();
            String userRedisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" +  requestPojo.getStaffId());

            userMap.put("id",userRedisId);
            List<SYuser> sYuserList = sYuserDao.selectList(new Page<>(), userMap);
            //不能删除自己的角色
            if(org.apache.commons.lang3.StringUtils.isEmpty(sYuserList.get(0).getUserGroupID())){
                result.setResStatus(ResStatus.STATUS_ROLE_IS_EMPTY);
                result.setResMsg(ResStatus.STATUS_ROLE_IS_EMPTY_MSG);
                return result;
            }else if(sYuserList.get(0).getUserGroupID().equals(map.getId() + "")){
                result.setResStatus(ResStatus.STATUS_NOT_MODIFY_SELF_ROLE);
                result.setResMsg(ResStatus.STATUS_NOT_MODIFY_SELF_ROLE_MSG);
                return result;
            }
            TCompany tCompany = new TCompany();
            tCompany.setId(Integer.valueOf(requestPojo.getCustId()));
            TCompany companyData = tCompanyDao.selectOne(tCompany);
            if(org.apache.commons.lang3.StringUtils.isEmpty(companyData.getMainMobile())){
                result.setResMsg(ResStatus.STATUS_ON_ADMIN_NULL_MSG);
                result.setResStatus(ResStatus.STATUS_ON_ADMIN_NULL);
                return result;
            }
            String mainId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" +  companyData.getMainMobile());
            userMap.put("id",mainId);
            List<SYuser> mainUserList = sYuserDao.selectList(new Page<>(), userMap);
            if(mainUserList.size() > 0){
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(mainUserList.get(0).getUserGroupID())){
                    if(mainUserList.get(0).getUserGroupID().equals(String.valueOf(map.getId()))){
                    result.setResMsg(ResStatus.STATUS_ADMIN_ROLE_NO_DELETE_MSG);
                    result.setResStatus(ResStatus.STATUS_ADMIN_ROLE_NO_DELETE);
                    return result;
                    }
                }else {
                    result.setResMsg(ResStatus.STATUS_ADMIN_ROLE_IS_EMPTY_MSG);
                    result.setResStatus(ResStatus.STATUS_ADMIN_ROLE_IS_EMPTY);
                    return result;
                }
            }
//            Map<String,String> userDataMap = new HashMap<>();
//            userMap.put("id",redisId);
//            List<SYuser> sYuserList = sYuserDao.selectList(new Page<>(),userMap);
//            if(sYuserList.size() > 0){
//                if(org.apache.commons.lang3.StringUtils.isNotEmpty(sYuserList.get(0).getUserGroupID()) && sYuserList.get(0).getUserGroupID().equals(map.getId() + "")){
//                    result.setResMsg(ResStatus.STATUS_ADMIN_ROLE_NO_DELETE);
//                    result.setResStatus(ResStatus.STATUS_ADMIN_ROLE_NO_DELETE_MSG);
//                    return result;
//                }
//            }
        }
        try{
            int rec = entitymDao.deleteByPk(mapData);
            log.debug("删除数据返回 {}",rec);

            GroupMenuQueryRequest groupMenuQueryRequest = new GroupMenuQueryRequest();
            groupMenuQueryRequest.setCompanyID(map.getCompanyID());
            groupMenuQueryRequest.setGroupID(String.valueOf(map.getId()));
            result = groupMenuSvc.doDelete(groupMenuQueryRequest, requestPojo);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
            try {
                LogSaveRequest logSaveRequest = new LogSaveRequest();
                logSaveRequest.setRelatedId(map.getId());
                logSaveRequest.setRelatedType("sys");
                logSaveRequest.setLogTitle("删除角色");
                logSaveRequest.setLogContent("角色名称："+ entitym.get(0).getGroupName());
                logSaveRequest.setOperateTime(new Date());
                logSaveRequest.setOperateType("删除");
                logSaveRequest.setOperateStatus("成功");
                tSysLogSvc.doSave(logSaveRequest,requestPojo);
            }catch (Exception e){
                log.error(e.getMessage());
            }
        }catch (Exception e){
            log.error("删除数据出错",e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("删除出错：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return result;

    }

    @Override
    @Transactional
    public Result doSaveMap(GroupHSaveRequest map, RequestPojo requestPojo) {

        Result result = new Result<>();
        String companyID = requestPojo.getCustId();
        String currentUserId = requestPojo.getStaffId();

        String mainAccount = "";
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(companyID)){
            TCompany tCompany = new TCompany();
            tCompany.setId(Integer.valueOf(companyID));
            TCompany companyData = tCompanyDao.selectOne(tCompany);
            if(org.apache.commons.lang3.StringUtils.isEmpty(companyData.getMainMobile())){
                result.setResMsg(ResStatus.STATUS_ON_ADMIN_NULL_MSG);
                result.setResStatus(ResStatus.STATUS_ON_ADMIN_NULL);
                return result;
            }else {
                mainAccount = companyData.getMainMobile();
                String redisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" + mainAccount);
                if(StringUtils.isEmpty(redisId)){
                    result.setResMsg(ResStatus.STATUS_ON_ADMIN_NULL_MSG);
                    result.setResStatus(ResStatus.STATUS_ON_ADMIN_NULL);
                    return result;
                }

            }
        }else {
            result.setResStatus(ResStatus.STATUS_ON_COMPANY_NOT_EXIST);
            result.setResMsg(ResStatus.STATUS_ON_COMPANY_NOT_EXIST_MSG);
            return result;
        }

        log.info("doSaveMap {}", map);
        SYgroupH entitym = new SYgroupH();
        BeanUtils.copyProperties(map, entitym);
        entitym.setCompanyID(companyID);
        result = this.doSave(entitym, requestPojo);
        if(!result.getResStatus().equalsIgnoreCase(ResStatus.STATUS_SUCCESS)){
            return result;
        }
        map.setId(Long.valueOf(entitym.getId()));

        processDetailData(map, requestPojo,mainAccount);
        try {
            LogSaveRequest logSaveRequest = new LogSaveRequest();
            logSaveRequest.setRelatedId(Long.valueOf(entitym.getId()));
            logSaveRequest.setRelatedType("sys");
            logSaveRequest.setLogTitle("新增角色");
            logSaveRequest.setLogContent("角色名称："+ entitym.getGroupName());
            logSaveRequest.setOperateTime(new Date());
            logSaveRequest.setOperateType("新增");
            logSaveRequest.setOperateStatus("成功");
            tSysLogSvc.doSave(logSaveRequest,requestPojo);
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return result;
    }

    @Override
    @Transactional
    public Result doUpdateMap(GroupHSaveRequest map, RequestPojo requestPojo) {
        Result result = new Result<>();
        String companyID = requestPojo.getCustId();

        String mainAccount = "";
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(companyID)){
            //判断是否为管理员
            TCompany tCompany = new TCompany();
            tCompany.setId(Integer.valueOf(companyID));
            TCompany companyData = tCompanyDao.selectOne(tCompany);
            if(org.apache.commons.lang3.StringUtils.isEmpty(companyData.getMainMobile())){
                result.setResMsg(ResStatus.STATUS_ON_ADMIN_NULL_MSG);
                result.setResStatus(ResStatus.STATUS_ON_ADMIN_NULL);
                return result;
            }else {
                mainAccount = companyData.getMainMobile();
            }
//            if(!currentUserId.equals(companyData.getMainMobile())){
//                result.setResMsg(ResStatus.STATUS_ON_NOT_ADMIN);
//                result.setResStatus(ResStatus.STATUS_ON_NOT_ADMIN_MSG);
//                return result;
//            }

        }else {
            result.setResStatus(ResStatus.STATUS_ON_COMPANY_NOT_EXIST);
            result.setResMsg(ResStatus.STATUS_ON_COMPANY_NOT_EXIST_MSG);
            return result;
        }
        //不能修改自己的角色
        if(map.getId() == null || map.getId() == 0){
            result.setResStatus(ResStatus.STATUS_USER_NOT_NULL);
            result.setResMsg(ResStatus.STATUS_USER_NOT_NULL_MSG);
            return result;
        }else {
            //为空读取token默认角色id
            Map<String,String> userMap = new HashMap<>();
            String userRedisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" +requestPojo.getStaffId());
            userMap.put("id",userRedisId);
            List<SYuser> sYuserList = sYuserDao.selectList(new Page<>(), userMap);
            if(org.apache.commons.lang3.StringUtils.isEmpty(sYuserList.get(0).getUserGroupID())){
                result.setResStatus(ResStatus.STATUS_ROLE_IS_EMPTY);
                result.setResMsg(ResStatus.STATUS_ROLE_IS_EMPTY_MSG);
                return result;
            }else if(sYuserList.get(0).getUserGroupID().equals(map.getId() + "")){
                result.setResStatus(ResStatus.STATUS_NOT_MODIFY_SELF_ROLE);
                result.setResMsg(ResStatus.STATUS_NOT_MODIFY_SELF_ROLE_MSG);
                return result;
            }
        }
        log.info("doUpdateMap {}", map);
        SYgroupH entitym = new SYgroupH();
        BeanUtils.copyProperties(map, entitym);
        entitym.setId(Integer.valueOf(map.getId() + ""));
        entitym.setCompanyID(companyID);
         result = this.doUpdate(entitym, requestPojo);
        if(!result.getResStatus().equalsIgnoreCase(ResStatus.STATUS_SUCCESS)){
            return result;
        }

        processDetailData(map, requestPojo,mainAccount);
        try {
            LogSaveRequest logSaveRequest = new LogSaveRequest();
            logSaveRequest.setRelatedId(Long.valueOf(entitym.getId()));
            logSaveRequest.setRelatedType("sys");
            logSaveRequest.setLogTitle("修改角色");
            logSaveRequest.setLogContent("角色名称："+ entitym.getGroupName());
            logSaveRequest.setOperateTime(new Date());
            logSaveRequest.setOperateType("修改");
            logSaveRequest.setOperateStatus("成功");
            tSysLogSvc.doSave(logSaveRequest,requestPojo);
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * 处理权限明细数据
     * @param map
     * @param requestPojo
     * @return
     */
    public Result processDetailData(GroupHSaveRequest map, RequestPojo requestPojo,String mainAccount) {
        JSONObject rw = new JSONObject();
        rw.put("roles",JSONObject.toJSONString(map.getRoles()));
        rw.put("permissions",JSONObject.toJSONString(map.getPermissions()));
        log.info("doUpdateMap {}", map);
        Result result= new Result();

        GroupMenuQueryRequest groupMenuQueryRequest = new GroupMenuQueryRequest();
        groupMenuQueryRequest.setCompanyID(requestPojo.getCustId());
        groupMenuQueryRequest.setGroupID(String.valueOf(map.getId()));
        groupMenuSvc.doDelete(groupMenuQueryRequest, requestPojo);
//        Page pageUser = new Page<>();
//        Map<String,String> userMap = new HashMap<>();
//        userMap.put("UserID",mainAccount);
//        List<SYuser> sYuserList = sYuserDao.selectList(pageUser, userMap);
//        List<String> menuIdList = new ArrayList<>();
//        if(sYuserList.size() > 0){
//            SYuser sYuserData = sYuserList.get(0);
//            menuIdList = groupMenuDao.selectIdByRole(sYuserData.getUserGroupID());
//        }
//        Map<String,String> idMap = new HashMap<>();
//        if(menuIdList.size() > 0){
//            for (String integer : menuIdList){
//                idMap.put(integer,integer);
//            }
//        }
        SYgroupMenu sYgroupMenu = new SYgroupMenu();
        sYgroupMenu.setRegisteredPerson(requestPojo.getUserName());
        sYgroupMenu.setRegisteredDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        sYgroupMenu.setUpdatedPerson(requestPojo.getUserName());
        sYgroupMenu.setUpdatedDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        sYgroupMenu.setExclusiveFG("0");
        sYgroupMenu.setCompanyID(requestPojo.getCustId());
        sYgroupMenu.setGroupID(String.valueOf(map.getId()));
        sYgroupMenu.setMenuID(String.valueOf(rw.getJSONArray("roles")));
        sYgroupMenu.setRw(JSonUtil.toJSONString(rw));
        groupMenuDao.insertRecords(sYgroupMenu);
        return result;
    }

    /**
     * 查询明细数据
     *
     * @param map
     * @return Result.class
     * */
    @Override
    public Result doQueryDetail(GroupDetailQueryRequest map, RequestPojo requestPojo) {
        log.debug("SYgroupHSvcImpl.doQueryDetail parameter: {}", map);
        Result result = new Result();
        String companyID = requestPojo.getCustId();
        String custId = requestPojo.getCustId();
        //分页查询
        Page page = new Page();
        Map<String, String> mapData = new HashMap<>();
        Long GroupID = map.getId();


        if(org.apache.commons.lang3.StringUtils.isNotEmpty(custId)){
            if(GroupID == null || GroupID == 0){
                //为空读取token默认角色id
                Map<String,String> userMap = new HashMap<>();
                String userRedisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" +requestPojo.getStaffId());

                userMap.put("id",userRedisId);

                List<SYuser> sYuserList = sYuserDao.selectList(new Page<>(), userMap);
                if(org.apache.commons.lang3.StringUtils.isEmpty(sYuserList.get(0).getUserGroupID())){
                    result.setResStatus(ResStatus.STATUS_ROLE_IS_EMPTY);
                    result.setResMsg(ResStatus.STATUS_ROLE_IS_EMPTY_MSG);
                    return result;
                }
                GroupID = Long.valueOf(sYuserList.get(0).getUserGroupID());
            }
        }
        Page pageData = new Page<>();
        Map<String,String> mapGroup = new HashMap<>();
        mapGroup.put("GroupID",String.valueOf(GroupID));
        List<SYGroupMenuInfo> sYgroupMenuList = groupMenuDao.selectList(pageData,mapGroup);
        JSONObject resultJs = new JSONObject();
        if (CollectionUtils.isNotEmpty(sYgroupMenuList) && org.apache.commons.lang3.StringUtils.isNotEmpty(sYgroupMenuList.get(0).getRW())) {
            resultJs = JSONObject.parseObject(sYgroupMenuList.get(0).getRW());
            page.setTotal(1);
            resultJs.put("roles",JSON.parse(resultJs.get("roles").toString()));
            resultJs.put("permissions",JSON.parse(resultJs.get("permissions").toString()));
        }else {
            result.setResStatus(ResStatus.STATUS_ON_AUTH_NULL);
            result.setResMsg(ResStatus.STATUS_ON_AUTH_NULL_MSG);
        }

        page.setRecords(Arrays.asList(resultJs));
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);
        return result;
    }

    @Override
    public Result doQueryMenuData(GroupDetailQueryRequest map, RequestPojo requestPojo) {
        Result result = new Result();
        log.debug("SYgroupHSvcImpl.doQueryDetail parameter: {}", map);
        String companyID = requestPojo.getCustId();
        String custId = requestPojo.getCustId();
//        companyID = testCompanyId;
//        custId = testUserId;
        //分页查询
        Page page = new Page();
        Map<String, String> mapData = new HashMap<>();
        Long GroupID = map.getId();
        SYgroupHResponse response = new SYgroupHResponse();
        List<RoleDetailRequest> roleDetailList = new ArrayList<>();


        if(org.apache.commons.lang3.StringUtils.isNotEmpty(custId)){
            TCompany tCompany = new TCompany();
            tCompany.setId(Integer.valueOf(companyID));
            TCompany companyData = tCompanyDao.selectOne(tCompany);
            //判断主账号是否为空
//            if(org.apache.commons.lang3.StringUtils.isEmpty(companyData.getMainMobile())){
//                result.setResMsg(ResStatus.STATUS_ON_NOT_ADMIN);
//                result.setResStatus(ResStatus.STATUS_ON_NOT_ADMIN_MSG);
//                return result;
//            }
            if(GroupID == null || GroupID == 0){
                //为空读取token默认角色id
                Map<String,String> userMap = new HashMap<>();
                String userRedisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" +requestPojo.getStaffId());
                userMap.put("id",userRedisId);
                List<SYuser> sYuserList = sYuserDao.selectList(new Page<>(), userMap);
                if(org.apache.commons.lang3.StringUtils.isEmpty(sYuserList.get(0).getUserGroupID())){
                    result.setResStatus(ResStatus.STATUS_ROLE_IS_EMPTY);
                    result.setResMsg(ResStatus.STATUS_ROLE_IS_EMPTY_MSG);
                    return result;
                }
                GroupID = Long.valueOf(sYuserList.get(0).getUserGroupID());
            }
            //判断公司名称是否是VJ
//            if(COMPANY_MAP.get(companyID).equals(COMPANY_CD)){
//
//            }else {
//                if(GroupID == null || GroupID == 0){
//                    Page pageUser = new Page<>();
//                    Map<String,String> userMap = new HashMap<>();
//                    userMap.put("UserID",companyData.getMainMobile());
//                    List<SYuser> sYuserList = sYuserDao.selectList(pageUser, userMap);
//                    if(sYuserList.size() > 0){
//                        SYuser sYuserData = sYuserList.get(0);
//                        GroupID = Long.valueOf(sYuserData.getUserGroupID());
//                    }
//                }
//            }
        }

        List<SysNewMenuResponse> sysNewMenuResponseList = handleMenuRole(String.valueOf(GroupID));
        page.setTotal(sysNewMenuResponseList.size());
        page.setRecords(sysNewMenuResponseList);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);
        return result;
    }
//    public Result doQueryDetail(GroupDetailQueryRequest map,RequestPojo requestPojo) {
//        log.debug("SYgroupHSvcImpl.doQueryDetail parameter: {}", map);
//        Result result = new Result();
//        String companyID = requestPojo.getCustId();
//        String custId = requestPojo.getCustId();
//        companyID = testCompanyId;
//        custId = testUserId;
//        //分页查询
//        Page page = new Page();
//        Map<String, String> mapData = new HashMap<>();
//        Long GroupID = map.getId();
//        SYgroupHResponse response = new SYgroupHResponse();
//        List<RoleDetailRequest> roleDetailList = new ArrayList<>();
//        List<SYmenu> menuList = new ArrayList<>();
//        List<SYGroupMenuInfo> entitysList =  new ArrayList<>();
//
//
//        if(org.apache.commons.lang3.StringUtils.isNotEmpty(custId)){
//
//            TCompany tCompany = new TCompany();
//            tCompany.setId(Integer.valueOf(companyID));
//            TCompany companyData = tCompanyDao.selectOne(tCompany);
//            if(org.apache.commons.lang3.StringUtils.isEmpty(companyData.getMainMobile())){
//                result.setResMsg(ResStatus.STATUS_ON_NOT_ADMIN);
//                result.setResStatus(ResStatus.STATUS_ON_NOT_ADMIN_MSG);
//                return result;
//            }
//            if(COMPANY_MAP.get(companyID).equals(COMPANY_CD)){
//                menuList = menuDao.selectList(page, mapData);
//                if(GroupID == null){
//                    entitysList = new ArrayList<>();
//                }else {
//                    mapData.put("GroupID", String.valueOf(GroupID));
//                    entitysList = groupMenuDao.selectList(page, mapData);
//                }
//            }else {
//                Page pageUser = new Page<>();
//                Map<String,String> userMap = new HashMap<>();
//                userMap.put("UserID",companyData.getMainMobile());
//                List<SYuser> sYuserList = sYuserDao.selectList(pageUser, userMap);
//                if(sYuserList.size() > 0){
//                    SYuser sYuserData = sYuserList.get(0);
//                    List<String> integerList = groupMenuDao.selectIdByRole(sYuserData.getUserGroupID());
//                    if(integerList.size() > 0){
//                        menuList = menuDao.selectInList(page, mapData,integerList);
//                        if(GroupID == null){
//                            entitysList = new ArrayList<>();
//                        }else {
//                            mapData.put("GroupID", String.valueOf(GroupID));
//                            entitysList = groupMenuDao.selectListIn(page, mapData,integerList);
//                        }
//                    }else {
//                        result.setResMsg(ResStatus.STATUS_ON_AUTH_NULL);
//                        result.setResStatus(ResStatus.STATUS_ON_AUTH_NULL_MSG);
//                        return result;
////                        menuList = new ArrayList<>();
////                        entitysList = new ArrayList<>();
//                    }
//                }
//            }
//        }
//
//
//        for(SYGroupMenuInfo model : entitysList){
//            RoleDetailRequest roleDetail = new RoleDetailRequest();
//            roleDetail.setMenuID(Long.valueOf(model.getMenuID()));
//            roleDetail.setMenuDisp(model.getMenuDisp());
//            ButtonDetailRequest buttonJson = JSonUtil.toBean(model.getRW(), ButtonDetailRequest.class);
//            roleDetail.setButtonList(buttonJson);
//            roleDetail.setMenuAuth(1);
//            roleDetailList.add(roleDetail);
//            List<SYmenu> menu = menuList.stream().filter(c -> (c.getId() == Long.valueOf(model.getMenuID()))).collect(Collectors.toList());
//            if(Objects.nonNull(menu) && menu.size() > 0){
//                roleDetail.setParentMenuID(Long.valueOf(menu.get(0).getParentMenuID()));
//                roleDetail.setMenuType(menu.get(0).getMenuType());
//            }
//            menuList.removeIf(menureq -> menureq.getId() == Long.valueOf(model.getMenuID()));
//        }
//
//        for(SYmenu menu : menuList){
//            RoleDetailRequest roleDetail = new RoleDetailRequest();
//            roleDetail.setMenuID(Long.valueOf(menu.getId()));
//            roleDetail.setMenuDisp(menu.getMenuDisp());
//            ButtonDetailRequest buttonJson = new ButtonDetailRequest();
//            mapData.clear();
//            mapData.put("MenuID", String.valueOf(menu.getId()));
//            List<ButtonDetailRequest> buttonDetailRequestList = menubuttonDao.selectList(page, mapData);
//            if(Objects.nonNull(buttonDetailRequestList) && buttonDetailRequestList.size() > 0){
//                ButtonDetailRequest buttonJson1 = buttonDetailRequestList.get(0);
//                roleDetail.setButtonList(buttonJson1);
//            }else {
//                roleDetail.setButtonList(buttonJson);
//            }
//            roleDetail.setMenuAuth(0);
//            roleDetail.setParentMenuID(Long.valueOf(menu.getParentMenuID()));
//            roleDetail.setMenuType(menu.getMenuType());
//            roleDetailList.add(roleDetail);
//        }
//
//        response.setRoleFuncList(roleDetailList);
//
//        log.debug("SYgroupHSvcImpl.doQueryDetail entitys: {}", roleDetailList);
//
//        page.setTotal(roleDetailList.size());
//        page.setRecords(roleDetailList);
//        result.setResStatus(ResStatus.STATUS_SUCCESS);
//        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
//        result.setResData(page);
//
//        return result;
//    }
}
