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

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

import com.gic.haoban.manage.api.service.DealSyncOperationApiService;
import com.gic.haoban.manage.service.util.CustomSwitcher;
import com.gic.wechat.api.service.qywx.QywxDepartmentApiService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.GICMQClientUtil;
import com.gic.haoban.base.api.common.Constant;
import com.gic.haoban.manage.api.dto.DealParamMqDTO;
import com.gic.haoban.manage.api.dto.DepartmentDTO;
import com.gic.haoban.manage.api.dto.SecretSettingDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.api.enums.PreDealStatusEnum;
import com.gic.haoban.manage.api.enums.PreDealTypeEnum;
import com.gic.haoban.manage.api.enums.SecretTypeEnum;
import com.gic.haoban.manage.api.enums.SyncTaskStatusEnum;
import com.gic.haoban.manage.service.config.Config;
import com.gic.haoban.manage.service.entity.TabHaobanDepartment;
import com.gic.haoban.manage.service.entity.TabHaobanPreDealLog;
import com.gic.haoban.manage.service.entity.TabHaobanSyncTask;
import com.gic.haoban.manage.service.service.DepartmentService;
import com.gic.haoban.manage.service.service.PreDealService;
import com.gic.haoban.manage.service.service.SecretSettingService;
import com.gic.haoban.manage.service.service.SyncTaskService;
import com.gic.haoban.manage.service.service.WxEnterpriseService;
import com.gic.haoban.manage.service.util.EmojiFilterUtil;
import com.gic.mq.sdk.GicMQClient;
import com.gic.redis.data.util.RedisUtil;
import com.gic.wechat.api.dto.qywx.UserDTO;
import com.gic.wechat.api.service.qywx.QywxUserApiService;

/**
 * 同步通讯录部门
 * Created 2020/4/13.
 *
 * @author hua
 */
@Service
public class QywxDeptSyncOperation implements BaseSyncOperation {
    private static final Logger logger = LoggerFactory.getLogger(QywxDeptSyncOperation.class);

    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private PreDealService preDealService;
    @Autowired
    private SyncTaskService syncTaskService;
    @Autowired
    private QywxUserApiService qywxUserApiService;
    @Autowired
    private WxEnterpriseService wxEnterpriseService;
    @Autowired
    private SecretSettingService secretSettingService;
    @Autowired
    private Config config;
    @Autowired
    private QywxDepartmentApiService qywxDepartmentApiService;
    @Autowired
    private DealSyncOperationApiService dealSyncOperationApiService;

    @Override
    public void dealSingleByMq(DealParamMqDTO dealParamMqDTO, TabHaobanPreDealLog dataPre) {
        logger.info("处理企业微信部门：{}", JSONObject.toJSONString(dealParamMqDTO));
        String reason = "";
        TabHaobanDepartment parent = this.departmentService.getByWxId(dataPre.getpDataId(), dataPre.getWxEnterpriseId());
        if (parent == null && dataPre.getpDataId().equals("0")) {
            parent = new TabHaobanDepartment();
            parent.setLevel(0);
            parent.setDepartmentId("0");
            parent.setChainId("0");
            parent.setChainName("");
        }
        if (parent == null) {
            logger.info("不存在该父部门：c:{},p:{}", dataPre.getDataId(), dataPre.getpDataId());
            dealException(dealParamMqDTO.getTaskId(), dealParamMqDTO.getData(), dataPre.getEnterpriseId(), "父部门不存在");
            return;
        }
        TabHaobanDepartment department = departmentService.getByWxId(dealParamMqDTO.getData(), dataPre.getWxEnterpriseId());
        DepartmentDTO dto = new DepartmentDTO();
        if (department != null) {
            logger.info("部门记录存在,qwid={},hbid={}", dataPre.getDataId(),department.getDepartmentId());
            dto = EntityUtil.changeEntityByJSON(DepartmentDTO.class, department);
        }

        logger.info("分组是否存在：{}", JSON.toJSONString(department));
        String wxEnterpriseId = dataPre.getWxEnterpriseId() ;
        String enterpriseId = dataPre.getEnterpriseId() ;
        String dataId = dataPre.getDataId() ;
        String taskId = dataPre.getTaskId() ;
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId) ;
        SecretSettingDTO secretSetting = secretSettingService.getSecretSetting(wxEnterpriseId, SecretTypeEnum.CUSTOMIZED_APP.getVal());
        String dataContent = dataPre.getDataContent();
        com.gic.wechat.api.dto.qywx.DepartmentDTO qywxDepart = JSONObject.parseObject(dataContent, com.gic.wechat.api.dto.qywx.DepartmentDTO.class);
        // com.gic.wechat.api.dto.qywx.DepartmentDTO qywxDepart = this.qywxDepartmentApiService.getSelfDepartmentById(qwDTO.getDkCorpid(), secretSetting.getSecretVal(), Integer.valueOf(dataId),qwDTO.getUrlHost()) ;
        if(null == qywxDepart) {
            dealException(dealParamMqDTO.getTaskId(), dealParamMqDTO.getData(), dataPre.getEnterpriseId(), "查询企微部门异常");
            return;
        }
        boolean resultFlag = true;
        try {
            dto.setDepartmentName(qywxDepart.getName());
            dto.setLevel(parent.getLevel() + 1);
            dto.setWxEnterpriseId(dataPre.getWxEnterpriseId());
            dto.setWxDepartmentId(qywxDepart.getId() + "");
            dto.setParentDepartmentId(parent.getDepartmentId());
            if (dataPre.getpDataId().equals("0")) {
                dto.setChainId(parent.getChainId());
                dto.setChainName(parent.getChainName());
            } else {
                dto.setChainId(parent.getChainId() + Constant.ID_SEPARATOR + parent.getDepartmentId());
                dto.setChainName(parent.getChainName() + Constant.NAME_SEPARATOR + parent.getDepartmentName());
            }

            dto.setSort(qywxDepart.getOrder());
            dto.setIsStore(0);
            if (dto.getDepartmentId() == null) {
                this.departmentService.add(dto);
            } else {
                this.departmentService.edit(dto);
            }
            this.preDealService.addTaskDepartStatusCache(taskId,0);
            reason = this.getStaff(taskId,dataId,enterpriseId,wxEnterpriseId,secretSetting,qwDTO);
            if(StringUtils.isNotBlank(reason)) {
                resultFlag = false ;
            }
        } catch (Exception e) {
            resultFlag = false;
            reason = "处理异常";
            logger.info("处理异常:{}", e);
        } finally {
            if (!resultFlag) {
                dealException(dealParamMqDTO.getTaskId(), dealParamMqDTO.getData(), dataPre.getEnterpriseId(), reason);
                this.dealSyncOperationApiService.unlockTask(wxEnterpriseId) ;
            } else {
                dealSuccess(dealParamMqDTO.getTaskId(), dealParamMqDTO.getData(), dataPre.getEnterpriseId(), dataPre.getWxEnterpriseId());
            }
        }
    }

    @Override
    public void dealException(String taskId, String dataId, String enterpriseId, String reason) {
        logger.info("部门同步异常：{},{}", taskId, dataId);
        this.preDealService.updateStatusByDataId(taskId, dataId, PreDealTypeEnum.dept.getVal(), PreDealStatusEnum.exception.getVal(), reason);
    }

    @Override
    public void dealSuccess(String taskId, String dataId, String enterpriseId, String wxEnterpriseId) {
        boolean b = preDealService.updateStatusByDataId(taskId, dataId, PreDealTypeEnum.dept.getVal(), PreDealStatusEnum.computed.getVal(), "成功");
        if (!b) {
            logger.info("成功修改错误！{}", dataId);
            return;
        }
        List<TabHaobanPreDealLog> preList = preDealService.listByPDataId(taskId, dataId,0);
        if (CollectionUtils.isNotEmpty(preList)) {
            Set<String> mid = preList.stream().map(tab -> tab.getDataId()).collect(Collectors.toSet());
            this.dealSyncOperationApiService.sendToMq(taskId,mid,SyncTaskStatusEnum.group_sync,"departmentSyncDealMq2");
        }
    }

    private void update(String taskId, String dataId, String enterpriseId, String reason) {

    }


    private String getStaff(String taskId, String dataId, String enterpriseId, String wxEnterpriseId,SecretSettingDTO secretSetting,WxEnterpriseQwDTO qwDTO) {
        logger.info("getstaff={}",dataId);
        String id = "1" ;
        Map<String,String> map = CustomSwitcher.haoban_department_id ;
        if(null != map && null != map.get(wxEnterpriseId)) {
            id = map.get(wxEnterpriseId) ;
        }
        List<String> ids = Arrays.stream(id.split(",")).collect(Collectors.toList());
        if(ids.contains(dataId)) {
            List<UserDTO> list = null ;
            if(qwDTO.getWxSecurityType()==4) {
                list = this.qywxUserApiService.listDepartmentUser(qwDTO.getThirdCorpid(), config.getWxSuiteid(),  dataId, 1) ;
                logger.info("从(第三方)获取通讯录={}",JSON.toJSONString(list)) ;
            }else {
                list = this.qywxUserApiService.listSelfDepartmentUser(qwDTO.getDkCorpid(), secretSetting.getSecretVal(), dataId, 1,qwDTO.getUrlHost());
                logger.info("从(代开)获取通讯录={}",JSON.toJSONString(list)) ;
            }
            if (null == list) {
                logger.info("微信获取部门成员异常：{},{}", taskId, dataId);
                dealSyncOperationApiService.unlockTask(wxEnterpriseId) ;
                return "获取企微成员异常";
            }
            logger.info("拉取成员数={},taskId={}",list.size(),taskId);
            List<TabHaobanPreDealLog> preDealLogList = list.stream().map(userDTO -> {
                TabHaobanPreDealLog dealLog = new TabHaobanPreDealLog();
                dealLog.setDataId(userDTO.getUserid());
                dealLog.setpDataId(dataId);
                dealLog.setDataType(PreDealTypeEnum.clerk.getVal());
                dealLog.setStatusFlag(0);
                dealLog.setDataContent(EmojiFilterUtil.removeAllEmoji(userDTO.getName()));
                dealLog.setTaskId(taskId);
                dealLog.setWxEnterpriseId(wxEnterpriseId);
                dealLog.setEnterpriseId(enterpriseId);
                return dealLog;
            }).collect(Collectors.toList());
            this.preDealService.insert(preDealLogList);
        }
        return null ;
    }

    @Override
    public void checkDepartmentTask(String taskId) {
    }
}
