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

import java.util.Map;

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.util.EventUtils;
import com.gic.member.api.dto.MemberInfoChangeNotifyDTO;
import com.gic.member.api.dto.event.wechat.WeChatOfficialAccountEventParam;
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 ;

    @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.printStackTrace();
        }
    }

    @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.printStackTrace();
        }
    }

    @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 ;
        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 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);
        try {
            GICMQClientUtil.getClientInstance().sendMessage("memberIdChangeNotify", JSON.toJSONString(dto));
        } 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") ;
        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 = null ;
        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);
        }
    }
}
