package com.yunfeiyun.agmp.common.framework.web.service;

import com.alibaba.fastjson2.JSON;
import com.yunfeiyun.agmp.common.constant.AmqpConstant;
import com.yunfeiyun.agmp.common.constant.Constants;
import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.constant.UserConstants;
import com.yunfeiyun.agmp.common.exception.BizException;
import com.yunfeiyun.agmp.common.framework.mq.MqMsg;
import com.yunfeiyun.agmp.common.framework.mq.MqService;
import com.yunfeiyun.agmp.common.core.domain.entity.PtsUserBind;
import com.yunfeiyun.agmp.common.core.domain.entity.SysDept;
import com.yunfeiyun.agmp.common.core.domain.entity.SysUser;
import com.yunfeiyun.agmp.common.core.domain.model.IBaseUser;
import com.yunfeiyun.agmp.common.core.domain.model.IBaseUserBind;
import com.yunfeiyun.agmp.common.core.domain.model.PortalInfo;
import com.yunfeiyun.agmp.common.utils.StringUtils;
import com.yunfeiyun.agmp.common.utils.spring.SpringUtils;
import com.yunfeiyun.agmp.common.web.system.service.ISysDeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class SysSyncService  implements  ISysSyncService{

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserService userService;


    private static final Logger log = LoggerFactory.getLogger(SysSyncService.class);
    PortalInfo portalInfo = SpringUtils.getBean(PortalService.class).getSsoInfo();
    @Override
    public void syncDept(SysDept dept , String cmd) {
        if(portalInfo.isPts() && portalInfo.isSync()){
            try {
                String msgSrc  = portalInfo.getAppName() != null ? portalInfo.getAppName() : AmqpConstant.msgSrcPTS;
                MqMsg mqMsg = new MqMsg(AmqpConstant.msgDept, cmd, msgSrc   );
                mqMsg.setData(dept);
                MqService mqService = (MqService) SpringUtils.getBean(MqService.class);
                mqService.sendMsg(mqMsg);
                log.info("业务方 {} 广播消息  sgSeq={}} mqType={}  mqCmd={}  mqBody={}", portalInfo.getAppName(), mqMsg.getSeqId() ,mqMsg.getMsgType(),mqMsg.getCmd(),mqMsg.getData());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void syncDept(String deptId , String cmd) {
        if(portalInfo.isPts() && portalInfo.isSync()){
            try {
                String msgSrc  = portalInfo.getAppName() != null ? portalInfo.getAppName() : AmqpConstant.msgSrcPTS;
                MqMsg mqMsg = new MqMsg(AmqpConstant.msgDept, cmd, msgSrc);
                mqMsg.setData(deptId);
                MqService mqService = (MqService) SpringUtils.getBean(MqService.class);
                mqService.sendMsg(mqMsg);
                log.info("业务方 {} 广播消息  sgSeq={}} mqType={}  mqCmd={}  mqBody={}", portalInfo.getAppName(), mqMsg.getSeqId() ,mqMsg.getMsgType(),mqMsg.getCmd(),mqMsg.getData());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void syncUser(SysUser user,String cmd) {
        try {
            String msgSrc  = portalInfo.getAppName() != null ? portalInfo.getAppName() : AmqpConstant.msgSrcPTS;
            MqMsg mqMsg = new MqMsg(AmqpConstant.msgUser, cmd , msgSrc);
            mqMsg.setData(user);
            MqService mqService = (MqService) SpringUtils.getBean(MqService.class);
            mqService.sendMsg(mqMsg);
            log.info("业务方 {} 广播消息  sgSeq={}} mqType={}  mqCmd={}  mqBody={}", portalInfo.getAppName(), mqMsg.getSeqId() ,mqMsg.getMsgType(),mqMsg.getCmd(),mqMsg.getData());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void syncUser(String userId,String cmd) {
        try {
            String msgSrc  = portalInfo.getAppName() != null ? portalInfo.getAppName() : AmqpConstant.msgSrcPTS;
            MqMsg mqMsg = new MqMsg(AmqpConstant.msgUser, cmd , msgSrc);
            mqMsg.setData(userId);
            MqService mqService = (MqService) SpringUtils.getBean(MqService.class);
            mqService.sendMsg(mqMsg);
            log.info("业务方 {} 广播消息  sgSeq={}} mqType={}  mqCmd={}  mqBody={}", portalInfo.getAppName(), mqMsg.getSeqId() ,mqMsg.getMsgType(),mqMsg.getCmd(),mqMsg.getData());
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public MqMsg parseDept(MqMsg mqMsg) {
        PortalInfo portalInfo = SpringUtils.getBean(PortalService.class).getSsoInfo();
        if(portalInfo.isSys() ){
            if(AmqpConstant.cmdAdd.equals(mqMsg.getCmd())){
                Object deptData = mqMsg.getData();
                SysDept sysDept =  (SysDept) JSON.parseObject(JSON.toJSONString(deptData), SysDept.class);
                log.info("解析部门 sysDept={}  新增",sysDept);
                if (!deptService.checkDeptNameUnique(sysDept)) {
                    throw new BizException(ErrorCode.ADD_DUPLICATE_ERROR.getCode(),ErrorCode.ADD_DUPLICATE_ERROR.getMessage());
                }
                sysDept.setDeptCreator("");
                deptService.insertDept(sysDept);
                mqMsg.setData(sysDept); //重新塞回
                return mqMsg;
            }else if(AmqpConstant.cmdUpdate.equals(mqMsg.getCmd())){
                Object deptData = mqMsg.getData();
                SysDept sysDept =  (SysDept) JSON.parseObject(JSON.toJSONString(deptData), SysDept.class);
                log.info("解析部门 sysDept={}  修改",sysDept);
                String deptId = sysDept.getDeptId();
                if (!deptService.checkDeptNameUnique(sysDept))
                {
                    throw new BizException(ErrorCode.ADD_DUPLICATE_ERROR.getCode(),ErrorCode.ADD_DUPLICATE_ERROR.getMessage());
                }
                else if (sysDept.getDeptParentid().equals(deptId))
                {
                    throw new BizException(ErrorCode.ADD_PARENT_ERROR.getCode(),ErrorCode.ADD_PARENT_ERROR.getMessage());
                }
                else if (StringUtils.equals(UserConstants.DEPT_DISABLE, sysDept.getDeptDelstatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0)
                {
                    throw new BizException( ErrorCode.ADD_DEACTIVATED_ERROR.getCode(),ErrorCode.ADD_DEACTIVATED_ERROR.getMessage());
                }
                sysDept.setDeptModifier("");
                deptService.updateDept(sysDept);
                mqMsg.setData(sysDept); //重新塞回
                return mqMsg;
            }else if(AmqpConstant.cmdDelete.equals(mqMsg.getCmd())){
                String deptId = (String)mqMsg.getData();
                String[] deptIds = deptId.split(" ");
                log.info("解析部门 deptId={} 删除 不能删除顶级部门",deptId);
                if (deptService.hasChildByDeptId(deptId))
                {
                    throw new BizException(ErrorCode.ADD_EXISTCHILD_ERROR.getCode(),ErrorCode.ADD_EXISTCHILD_ERROR.getMessage());
                }
                if (deptService.checkDeptExistUser(deptId))
                {
                    throw new BizException( ErrorCode.ADD_EXISTRELNODE_ERROR.getCode(),ErrorCode.ADD_EXISTRELNODE_ERROR.getMessage());

                }
                if (deptService.isTopDept(deptId))
                {
                    throw new BizException(ErrorCode.DEL_TOPNODE_ERROR.getCode(),ErrorCode.DEL_TOPNODE_ERROR.getMessage());
                }
                deptService.deleteDeptById(deptId);
                mqMsg.setData(deptId); //重新塞回
                return mqMsg;
            }
        }
        return null;
    }

    public MqMsg parseUser(MqMsg mqMsg) {
        PortalInfo portalInfo = SpringUtils.getBean(PortalService.class).getSsoInfo();
        if(portalInfo.isSys() ){
            if(AmqpConstant.cmdAdd.equals(mqMsg.getCmd())){
                Object userData = mqMsg.getData();
                SysUser sysUser =  (SysUser) JSON.parseObject(JSON.toJSONString(userData), SysUser.class);
                log.info("解析用户 sysUser={}  新增",sysUser);
                if (!userService.checkUserNameUnique(sysUser))
                {
                    throw new BizException(ErrorCode.ADD_DUPLICATE_ERROR.getCode(),ErrorCode.ADD_DUPLICATE_ERROR.getMessage());
                }
                else if (StringUtils.isNotEmpty(sysUser.getUserMobile()) && !userService.checkPhoneUnique(sysUser))
                {
                    throw new BizException(ErrorCode.ADD_DUPLICATE_ERROR.getCode(),ErrorCode.ADD_DUPLICATE_ERROR.getMessage());
                }
                else if (StringUtils.isNotEmpty(sysUser.getUserEmail()) && !userService.checkEmailUnique(sysUser))
                {
                    throw new BizException(ErrorCode.ADD_DUPLICATE_ERROR.getCode(),ErrorCode.ADD_DUPLICATE_ERROR.getMessage());
                }
                sysUser.setUserCreator("");
                userService.insertUser(sysUser);
                mqMsg.setData(sysUser); //重新塞回
                return mqMsg;
            }else if(AmqpConstant.cmdUpdate.equals(mqMsg.getCmd())){
                Object userData = mqMsg.getData();
                SysUser sysUser =  (SysUser) JSON.parseObject(JSON.toJSONString(userData), SysUser.class);
                log.info("解析用户 sysUser={}  新增加",sysUser);
                //有用户直接更新就行
                if (!userService.checkUserNameUnique(sysUser))
                {
                    sysUser.setUserLoginname(null);
                    userService.updateUser(sysUser);
                }
                else if (StringUtils.isNotEmpty(sysUser.getUserMobile()) && !userService.checkPhoneUnique(sysUser))
                {
                    sysUser.setUserMobile(null);
                    userService.updateUser(sysUser);
                }
                else if (StringUtils.isNotEmpty(sysUser.getUserEmail()) && !userService.checkEmailUnique(sysUser))
                {
                    sysUser.setUserEmail(null);
                    userService.updateUser(sysUser);
                }
                sysUser.setUserModifier("");
                userService.insertUser(sysUser);
                sysUser.setSysId( portalInfo.getAppName() );
                sysUser.setPtsUserid( sysUser.getUserId() );
                mqMsg.setData(sysUser); //重新塞回
                return mqMsg;
            }else if(AmqpConstant.cmdUpdate.equals(mqMsg.getCmd())){
                Object userData = mqMsg.getData();
                SysUser sysUser =  (SysUser) JSON.parseObject(JSON.toJSONString(userData), SysUser.class);
                log.info("解析用户 sysUser={}  更新",sysUser);
                String userId = sysUser.getUserId();
                String userNewId = userId;
                if (!userService.checkUserNameUnique(sysUser))
                {
                    IBaseUser sysUserNew = userService.selectUserByUserName( sysUser.getUserLoginname() );
                    userNewId = sysUserNew.getUserId();
                    sysUser.setUserLoginname(null);
                    userService.updateUser(sysUser);

                }
                else if (StringUtils.isNotEmpty(sysUser.getUserMobile()) && !userService.checkPhoneUnique(sysUser))
                {
                    sysUser.setUserMobile(null);
                    userService.updateUser(sysUser);
                }
                else if (StringUtils.isNotEmpty(sysUser.getUserEmail()) && !userService.checkEmailUnique(sysUser))
                {
                    sysUser.setUserEmail(null);
                    userService.updateUser(sysUser);
                }
                sysUser.setUserModifier("");
                sysUser.setSysId( portalInfo.getAppName() );
                sysUser.setPtsUserid( sysUser.getUserId() );
                sysUser.setUserId( userNewId );
                userService.updateUser(sysUser);
                mqMsg.setData(sysUser); //重新塞回
                return mqMsg;
            }else if(AmqpConstant.cmdDelete.equals(mqMsg.getCmd())){
                String userId = (String)mqMsg.getData();
                log.info("解析用户 userId={} 删除 不能删除管理员",userId);
                if (userId.indexOf(Constants.ADMIN_KEY) >-1)
                {
                    throw new BizException(ErrorCode.DEL_ADMINNODE_ERROR.getCode(),ErrorCode.DEL_ADMINNODE_ERROR.getMessage());
                }
                //直接禁用
                String[] userIds = userId.split(",");
                SysUser sysUser = new SysUser();
                userService.deleteUserByIds(userIds);
                sysUser.setSysId( portalInfo.getAppName() );
                sysUser.setUserId(userId);
                mqMsg.setData(sysUser); //重新塞回
                return mqMsg;
            }
        }
        return null;
    }

    @Override
    public MqMsg parseMsg(MqMsg mqMsg){
        MqMsg mqAck = null;
        if( portalInfo.getAppName().toUpperCase().contains(Constants.PTS) ){
            if(AmqpConstant.msgDept.equalsIgnoreCase(mqMsg.getMsgType())) {
                log.info("返回子系统={} 的处理结果 ", mqMsg.getSrc());
            }else if(AmqpConstant.msgUser.equalsIgnoreCase(mqMsg.getMsgType())){
                parseUserAck(mqMsg);
            }
        }else{
            if(AmqpConstant.msgDept.equalsIgnoreCase(mqMsg.getMsgType())){
                mqAck = parseDept(mqMsg);
            }else if(AmqpConstant.msgUser.equalsIgnoreCase(mqMsg.getMsgType())){
                mqAck = parseUser(mqMsg);
            }
        }
        return mqAck;
    }



    @Override
    public void parseUserAck(MqMsg mqMsg) {
        if(AmqpConstant.cmdAdd.equals(mqMsg.getCmd()) || AmqpConstant.cmdUpdate.equals(mqMsg.getCmd())) {
            Object userData = mqMsg.getData();
            SysUser sysUser = (SysUser) JSON.parseObject(JSON.toJSONString(userData), SysUser.class);
            int count = userService.hasPtsSysUserId( sysUser.getPtsUserid() ,sysUser.getSysId() , sysUser.getUserId());
            int nResult = 0;
            if(count == 0){
                nResult = userService.insertPtsUserBind( sysUser.getPtsUserid() ,sysUser.getSysId() , sysUser.getUserId() );
            }
            log.info("返回子系统={} count={} 用户={} 结果={} 增加更新  增加绑定处理结果", mqMsg.getSrc(), count , sysUser.toString(),nResult);
        }else if(AmqpConstant.cmdAdd.equals(mqMsg.getCmd())){
            String userIds = (String)mqMsg.getData();
            Object userData = mqMsg.getData();
            SysUser sysUser = (SysUser) JSON.parseObject(JSON.toJSONString(userData), SysUser.class);
            String[] userIdss = sysUser.getUserId().split(",");

            List<IBaseUserBind> list = new ArrayList<>();
            Arrays.stream(userIdss).forEach(v->{
                IBaseUserBind ptsSysuser = new PtsUserBind();
                ptsSysuser.setUserId( v );
                ptsSysuser.setUserBindSys( sysUser.getSysId() );
                ptsSysuser.setUserBindSysUser( v );
                list.add(ptsSysuser);
            });
            log.info("返回子系统={} 用户Ids={} 删除用户 禁用 批量解绑处理结果", mqMsg.getSrc(), userIds);  //啥也不管直接解绑列表
            int nResult = userService.deletePtsUserBind( list );

        }

    }
}
