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

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

import com.alibaba.fastjson.JSONArray;
import com.gic.haoban.manage.api.dto.CommonDataMQDTO;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanExternalClerkRelatedMapper;
import com.gic.haoban.manage.service.service.StaffClerkRelationService;
import com.gic.commons.util.StringUtil;
import com.gic.haoban.manage.api.dto.MemberUnionidWechatAccountQDTO;
import com.gic.haoban.manage.api.service.ExternalClerkRelatedApiService;
import com.gic.haoban.manage.service.service.chat.GroupChatPlanService;
import com.gic.haoban.manage.service.service.role.HaobanMenuService;
import com.gic.haoban.manage.service.util.EventUtils;
import com.gic.member.api.dto.MemberInfoChangeNotifyDTO;
import com.gic.member.api.dto.event.wechat.WeChatOfficialAccountEventParam;
import com.alibaba.fastjson.JSONArray;
import com.gic.haoban.manage.service.service.StaffClerkRelationService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.GICMQClientUtil;
import com.gic.haoban.manage.api.dto.CommonMQDTO;
import com.gic.haoban.manage.api.service.HaobanCommonMQApiService;
import com.gic.haoban.manage.service.service.StaffDepartmentRelatedService;
import com.gic.haoban.manage.service.service.WelcomeSendService;
import com.gic.member.api.service.MemberOpenCardBusinessService;
import com.gic.mq.sdk.GicMQClient;
import com.gic.quartz.api.dto.QuartzTaskDTO;
import com.gic.quartz.api.service.QuartzService;

@Service("haobanCommonMQApiService")
public class HaobanCommonMQApiServiceImpl implements HaobanCommonMQApiService {

    private final Logger log = LogManager.getLogger(HaobanCommonMQApiService.class);

    private static GicMQClient mqClient = GICMQClientUtil.getClientInstance();

    @Autowired
    private QuartzService quartzService;
    @Autowired
    private StaffDepartmentRelatedService staffDepartmentRelatedService;
    @Autowired
    private WelcomeSendService welcomeSendService;
    @Autowired
    private MemberOpenCardBusinessService memberOpenCardBusinessService ;
    @Autowired
    private ExternalClerkRelatedApiService externalClerkRelatedApiService ;
    @Autowired
    private StaffClerkRelationService staffClerkRelationService ;
    @Autowired
    private HaobanMenuService haobanMenuService ;
    @Autowired
    private TabHaobanExternalClerkRelatedMapper externalClerkRelatedMapper ;
    @Autowired
    private GroupChatPlanService groupChatPlanService ;

    @Override
    public void putCommonMessage(CommonMQDTO dto) {
        String message = JSONObject.toJSONString(dto);
        log.info("加入好办通用队列params={}", message);
        try {
            mqClient.sendCommonMessage("haobanCommonRouter", message,
                    "com.gic.haoban.manage.api.service.HaobanCommonMQApiService", "commonHandler");
        } catch (Exception e) {
            log.error("发送MQ异常",e);
        }
    }

    @Override
    public void putDataMessage(CommonDataMQDTO dto) {
        String message = JSONObject.toJSONString(dto);
        log.info("加入好办通用队列params={}", message);
        try {
            mqClient.sendCommonMessage("haobanDataCommonRouter", message,
                    "com.gic.haoban.manage.api.service.HaobanCommonMQApiService", "commonDataHandler");
        } catch (Exception e) {
            log.error("发送MQ异常",e);
        }
    }

    @Override
    public void commonDataHandler(String message) {
        CommonDataMQDTO dto = JSON.parseObject(message, CommonDataMQDTO.class);
        switch (dto.getType()) {
            case 1:
                String listStr = dto.getParams().toString() ;
                JSONArray list = JSONArray.parseArray(listStr) ;
                for(int i=0;i<list.size();i++) {
                    JSONObject json  = list.getJSONObject(i) ;
                    String id = json.getString("id") ;
                    Date delTime = json.getDate("delTime") ;
                    this.externalClerkRelatedMapper.updateHalfTime(id,delTime);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void putCommonDelayMessage(CommonMQDTO dto, int delay) {
        String message = JSONObject.toJSONString(dto);
        log.info("加入好办延时通用队列params={}", message);
        try {
            mqClient.sendMessage("haobanDelayMQ", message, delay);
        } catch (Exception e) {
            log.error("发送MQ异常",e);
        }
    }


    @Override
    public void commonHandler(String message) {
        log.info("接收好办通用队列params={}", message);
        CommonMQDTO dto = JSON.parseObject(message, CommonMQDTO.class);
        // 好办停用,删除定时
        Map<String, String> map = (Map<String, String>) dto.getParams();
        switch (dto.getType()) {
        case 1:
            String enterpriseId = map.get("enterpriseId");
            this.deleteQuartz(enterpriseId);
            break;
        case 2:
            String staffId = map.get("staffId");
            if (StringUtils.isNotBlank(staffId)) {
                this.staffDepartmentRelatedService.repairStaffDepart(staffId);
            }
            break ;
        case 3:
            String memberId = map.get("memberId") ;
            enterpriseId = map.get("enterpriseId") ;
            String clerkId = map.get("clerkId") ;
            this.memberOpenCardBusinessService.memberClerkByQywx(enterpriseId, memberId, clerkId);
            break ;
        case 4:
            Long planId = Long.valueOf(map.get("planId")) ;
            this.groupChatPlanService.stopByMsgid(planId);
            break ;
        default:
            break;
        }
    }

    private void deleteQuartz(String enterpriseId) {
        if (StringUtils.isBlank(enterpriseId)) {
            return;
        }
        log.info("删除好办定时eid={}", enterpriseId);
        // 日报
        QuartzTaskDTO task = new QuartzTaskDTO();
        task.setTaskService("com.gic.haoban.app.daily.api.service.DailyReportTaskApiService");
        task.setTaskMethod("run");
        task.setReferId(enterpriseId);
        this.quartzService.delQuartzTask(task);
    }

    @Override
    public void welcomeMQ(String params) {
        this.welcomeSendService.sendWelcome(params);
    }

    @Override
    public void noticeMemberMQ(String params) {
        log.info("通知会员企微标识={}",params);
        JSONObject json = JSONObject.parseObject(params) ;
        String enterpriseId = json.getString("enterpriseId") ;
        List<String> memberIdList = JSONArray.parseArray(json.getString("memberIdList"),String.class) ;
        this.staffClerkRelationService.delMemberQywxFlag(enterpriseId,memberIdList) ;
    }

    @Override
    public void putToNoticeMemberMQ(String enterpriseId, List<String> memberIdList) {
        JSONObject json = new JSONObject() ;
        json.put("enterpriseId",enterpriseId) ;
        json.put("memberIdList",memberIdList) ;
        try {
            mqClient.sendMessage("haobanNoticeMemberMQ", json.toJSONString());
        } catch (Exception e) {
            log.error("发送MQ异常");
        }
    }

    @Override
    public void memberEventChange(String params) {
        if(!EventUtils.isOpenEvent()) {
            return ;
        }
        log.info("会员换绑事件={}",params);
        JSONObject json = JSONObject.parseObject(params) ;
        String memberId = json.getString("memberId") ;
        String enterpriseId = json.getString("enterpriseId") ;
        String changeBindMemberId = json.getString("changeBindMemberId") ;
        this.externalClerkRelatedApiService.delByMemberIdAndEnterpriseIdEvent(memberId,enterpriseId,changeBindMemberId,2);
    }

    @Override
    public void memberEventMerge(String params) {
        if(!EventUtils.isOpenEvent()) {
            return ;
        }
        log.info("会员合并事件={}",params);
        JSONObject json = JSONObject.parseObject(params) ;
        String memberId = json.getString("memberId") ;
        String enterpriseId = json.getString("enterpriseId") ;
        JSONObject delMemberObj = json.getJSONObject("delMember") ;
        if(null == delMemberObj) {
            log.info("删除会员为空,不处理");
            return ;
        }
        String delMemberId = delMemberObj.getString("memberId") ;
        this.externalClerkRelatedApiService.delByMemberIdAndEnterpriseIdEvent(delMemberId, enterpriseId, memberId, 1);

        // 内容中台
        MemberInfoChangeNotifyDTO dto = new MemberInfoChangeNotifyDTO();
        dto.setMemberId(delMemberId);
        dto.setMergeMemberId(memberId);
        dto.setEnterpriseId(enterpriseId);
        dto.setOpt(2);
        JSONObject msg = JSONObject.parseObject(JSON.toJSONString(dto)) ;
        msg.put("eventFlag",1) ;
        try {
            GICMQClientUtil.getClientInstance().sendMessage("memberIdChangeNotify", msg.toJSONString());
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

    }

    @Override
    public void memberEventDel(String params) {
        if(!EventUtils.isOpenEvent()) {
            return ;
        }
        log.info("会员注销事件={}",params);
        JSONObject json = JSONObject.parseObject(params) ;
        String memberId = json.getString("memberId") ;
        String enterpriseId = json.getString("enterpriseId") ;
        boolean mergeDel = json.getBooleanValue("mergeDel") ;
        if(!mergeDel) {
            this.externalClerkRelatedApiService.delByMemberIdAndEnterpriseIdEvent(memberId, enterpriseId, null, 0);
        }
    }

    @Override
    public void memberEventWechat(String params) {
        if(!EventUtils.isOpenEvent()) {
            return ;
        }
        log.info("会员扫码关注事件={}",params);
        WeChatOfficialAccountEventParam json = JSONObject.parseObject(params,WeChatOfficialAccountEventParam.class) ;
        String memberId = json.getMemberId() ;
        String unionid = json.getUnionId() ;
        if (StringUtil.isBlankVerifyMinusOne(memberId) || StringUtil.isBlankVerifyMinusOne(unionid)) {
            log.warn("memberId、unionid为空，不通知");
            return;
        }
        String enterpriseId = json.getEnterpriseId() ;
        String openId = json.getOpenId() ;
        String qrcodeParam = json.getQrCode() ;
        try {
            MemberUnionidWechatAccountQDTO dto = new MemberUnionidWechatAccountQDTO();
            dto.setEnterpriseId(enterpriseId);
            dto.setUnionid(unionid);
            dto.setOpenId(openId);
            dto.setSceneStr(qrcodeParam);
            dto.setMemberId(memberId);
            dto.setEventFlag(true);
            if (qrcodeParam != null && qrcodeParam.startsWith("QWHY")) {
                GICMQClientUtil.getClientInstance().sendMessage("addMemberUnionidWechatAccountByClerkMq", JSON.toJSONString(dto));
            } else {
                GICMQClientUtil.getClientInstance().sendMessage("addMemberUnionidWechatAccountMq", JSON.toJSONString(dto));
            }
        } catch (Exception e) {
            log.error("通知好办失败", e);
        }
    }

    @Override
    public void serviceOpenOffEvent(String params) {
        this.haobanMenuService.saveMenuFromGicEvent(params);
    }
}
