package com.gic.haoban.manage.service.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.gic.commons.util.EntityUtil;
import com.gic.haoban.common.utils.DingUtils;
import com.gic.haoban.common.utils.StringUtil;
import com.gic.haoban.manage.api.dto.WxEnterpriseDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanStaffClerkRelationMapper;
import com.gic.haoban.manage.service.dao.mapper.WxApplicationMapper;
import com.gic.haoban.manage.service.dao.mapper.WxEnterpriseMapper;
import com.gic.haoban.manage.service.dao.mapper.WxEnterpriseRelatedMapper;
import com.gic.haoban.manage.service.entity.TabHaobanWxApplication;
import com.gic.haoban.manage.service.entity.TabHaobanWxEnterprise;
import com.gic.haoban.manage.service.entity.TabHaobanWxEnterpriseRelated;
import com.gic.haoban.manage.service.service.WxEnterpriseService;

@Service
public class WxEnterpriseServiceImpl implements WxEnterpriseService {
    private static org.apache.logging.log4j.Logger logger= LogManager.getLogger(WxEnterpriseService.class);

    @Autowired
    private WxEnterpriseMapper mapper;
    @Autowired
    private WxEnterpriseRelatedMapper wxEnterpriseRelatedMapper ;
    @Autowired
    private WxApplicationMapper wxApplicationMapper ;
    @Autowired
    private TabHaobanStaffClerkRelationMapper tabHaobanStaffClerkRelationMapper ;

    @Override
    public String add(WxEnterpriseDTO wxDTO) {
        logger.info("新增wx_enterprise,dto={}",JSON.toJSONString(wxDTO));
        Date now = new Date();
        wxDTO.setWxEnterpriseId(StringUtil.randomUUID());
        wxDTO.setCreateTime(now);
        wxDTO.setUpdateTime(now);
        TabHaobanWxEnterprise tabHaobanWxEnterprise = EntityUtil.changeEntityByJSON(TabHaobanWxEnterprise.class, wxDTO);
        tabHaobanWxEnterprise.setStatusFlag(1);
        tabHaobanWxEnterprise.setBindFlag(1);
        mapper.insertSelective(tabHaobanWxEnterprise);
        return wxDTO.getWxEnterpriseId();
    }

    @Override
    public WxEnterpriseDTO selectById(String wxEnterpriseId) {
        if (StringUtils.isBlank(wxEnterpriseId)) {
            return null;
        }
        return EntityUtil.changeEntityByJSON(WxEnterpriseDTO.class, mapper.selectByPrimaryKey(wxEnterpriseId));
    }
    
    @Override
    public WxEnterpriseQwDTO getQwInfo(String wxEnterpriseId) {
        TabHaobanWxEnterprise wxEnterprise = this.mapper.selectByPrimaryKey(wxEnterpriseId) ;
        if(null == wxEnterprise) {
            return null ;
        }
        WxEnterpriseQwDTO qw = new WxEnterpriseQwDTO();
        qw.setWxEnterpriseId(wxEnterpriseId);
        if(null != wxEnterprise.getWxSecurityType()) {
            qw.setWxSecurityType(wxEnterprise.getWxSecurityType());
        }
        List<TabHaobanWxApplication> applictionList = this.wxApplicationMapper.listApplication(wxEnterpriseId) ;
        if(CollectionUtils.isNotEmpty(applictionList)) {
            applictionList.forEach(app->{
                Integer appType = app.getApplicationType() ;
                if(appType==2) {
                    qw.setThirdCorpid(app.getCorpid());
                    qw.setAgentId(app.getAgentId());
                    qw.setAgentName(app.getAgentName());
                }else if(appType.equals(3)) {
                    qw.setDkCorpid(app.getCorpid());
                }else if(appType.equals(4)) {
                    qw.setMemberCorpid(app.getCorpid());
                }
            });
        }
        if(StringUtils.isBlank(qw.getMemberCorpid())) {
            logger.info("会员小程序未配置,自建应用");
            if(qw.getWxSecurityType()==2) {
                qw.setMemberCorpid(wxEnterprise.getOpenCorpid());
            }else {
                qw.setMemberCorpid(wxEnterprise.getWxCorpid());
            }
        }
        logger.info("企微所有corpid信息={}",JSON.toJSON(qw));
        return qw;
    }
    
    @Override
    public TabHaobanWxEnterprise getEnterpriseBycorpId(String corpId) {
        if (StringUtils.isBlank(corpId)) {
            return null;
        }
        return mapper.getEnterpriseBycorpId(corpId, 1);
    }

    @Override
    public void update(WxEnterpriseDTO enterpriseDTO) {
        enterpriseDTO.setUpdateTime(new Date());
        mapper.updateByPrimaryKeySelective(EntityUtil.changeEntityByJSON(TabHaobanWxEnterprise.class, enterpriseDTO));
    }

    @Override
    public int unbind(String wxEnterpriseId) {
        TabHaobanWxEnterprise enterprise = new TabHaobanWxEnterprise();
        enterprise.setWxEnterpriseId(wxEnterpriseId);
        enterprise.setBindFlag(0);
        enterprise.setUpdateTime(new Date());
        return this.mapper.updateByPrimaryKeySelective(enterprise);
    }

    @Override
    public List<TabHaobanWxEnterprise> listAll() {
        return mapper.listAll();
    }

    @Override
    public List<WxEnterpriseDTO> listAllEnterprise() {
        return mapper.listAllEnterprise();
    }

    @Override
    public void stopHaoban(String enterpriseId) {
        List<TabHaobanWxEnterpriseRelated> list =  this.wxEnterpriseRelatedMapper.listByEnterpriseId(enterpriseId) ;
        logger.info("停用好办={},商户list={}",enterpriseId,JSON.toJSONString(list));
        if(CollectionUtils.isEmpty(list)){
            return ;
        }
        List<String> wxEnterpriseIdList = new ArrayList<>();
        for(TabHaobanWxEnterpriseRelated item : list) {
            String wxEnterpriseId = item.getWxEnterpriseId() ;
            wxEnterpriseIdList.add(wxEnterpriseId) ;
        }
        this.wxEnterpriseRelatedMapper.deleteByEnterpriseId(enterpriseId) ;
        this.tabHaobanStaffClerkRelationMapper.deleteByEnterpriseId(enterpriseId);
        Map<String,Object> enMap = new HashMap<>();
        enMap.put("enterpriseId", enterpriseId + list.get(0).getEnterpriseName()) ;
        alert("删除商户企微关联告警", enMap);
        for(String wxEnterpriseId : wxEnterpriseIdList) {
          List<TabHaobanWxEnterpriseRelated> relationList =  this.wxEnterpriseRelatedMapper.listByWxenterpriseId(wxEnterpriseId) ;
          if(CollectionUtils.isEmpty(relationList)) {
              // 停用企微
              TabHaobanWxEnterprise tab = new TabHaobanWxEnterprise() ;
              tab.setWxEnterpriseId(wxEnterpriseId);
              tab.setStatusFlag(0);
              tab.setUpdateTime(new Date());
              this.mapper.updateByPrimaryKeySelective(tab) ;
              Map<String,Object> map = new HashMap<>();
              map.put("wxEnterpriseId", wxEnterpriseId) ;
              alert("删除企微告警", map);
          }
        }
    }

    @Override
    public int updateAutoActiveFlagById(Integer autoActiveFlag, String wxEnterpriseId) {
        return mapper.updateAutoActiveFlagById(autoActiveFlag,wxEnterpriseId);
    }
    
    @Override
    public void updateWxSecurityType(String wxEnterpriseId) {
        int wxSecurityType = this.calcSecretType(wxEnterpriseId);
        if(wxSecurityType < 1 || wxSecurityType > 4) {
            return ;
        }
        com.gic.haoban.manage.service.util.DingUtils.send("更新WxSecurityType告警,wxEnterpriseId="+wxEnterpriseId, null, true);
        this.mapper.updateWxSecurityType(wxEnterpriseId, wxSecurityType); 
    }
    
    private int getType (boolean mix3th , boolean mixdk) {
        if(!mix3th && !mixdk) {
            return 1 ;
        }
        if(mix3th && mixdk) {
            return 2 ;
        }
        if(mix3th && !mixdk) {
            return 3 ;
        }
        if(!mix3th && mixdk) {
            return 4 ;
        }
        return 0 ;
    }
    
    @Override
    public int calcSecretType(String wxEnterpriseId) {
        List<TabHaobanWxApplication> applictionList = this.wxApplicationMapper.listApplication(wxEnterpriseId) ;
        String corpid3th = null , corpidDk=null;
        boolean mix3th = false ;
        boolean mixdk = false ; 
        int len = 20 ;
        if(CollectionUtils.isNotEmpty(applictionList)) {
            for(TabHaobanWxApplication app : applictionList) {
                Integer appType = app.getApplicationType() ;
                if(appType==2) {
                    corpid3th= app.getCorpid() ;
                }else if(appType.equals(3)) {
                    corpidDk = app.getCorpid() ;
                }
            };
        }
        if(StringUtils.isBlank(corpid3th) || StringUtils.isBlank(corpidDk)) {
            return 0 ;
        }
        if(corpid3th.length() > len) {
            mix3th = true ;
        }
        if(corpidDk.length() > len) {
            mixdk = true ;
        }
        int wxType = this.getType(mix3th, mixdk) ;
        logger.info("计算企微加密类型,corpid3th={},corpidDk={},wxSecurityType={}",corpid3th,corpidDk,wxType);
        return wxType ;
    }
    
    
    private void alert(String title, Map<String, Object> map) {
        String msg = title + JSON.toJSONString(map);
        String dingUrl = "https://oapi.dingtalk.com/robot/send?access_token=c38fdc53d26e9a019640755bdada1ce07ebd44a2555d1c8acc299de7a7b5b857";
        DingUtils.send(msg, dingUrl, false);
    }
}
