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

import java.util.ArrayList;
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.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.JSONResponse;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.EntityUtil;
import com.gic.haoban.manage.api.dto.ContentMaterialDTO;
import com.gic.haoban.manage.api.dto.MaterialDTO;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.service.config.Config;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanStaffClerkRelationMapper;
import com.gic.haoban.manage.service.entity.TabHaobanStaff;
import com.gic.haoban.manage.service.service.MaterialService;
import com.gic.haoban.manage.service.service.QywxSendService;
import com.gic.haoban.manage.service.service.StaffService;
import com.gic.haoban.manage.service.service.WxEnterpriseService;
import com.gic.wechat.api.dto.qywx.QywxExternalMessageDTO;
import com.gic.wechat.api.dto.qywx.QywxImageMaterialDTO;
import com.gic.wechat.api.dto.qywx.QywxLinkMaterialDTO;
import com.gic.wechat.api.dto.qywx.QywxMessageMaterialDTO;
import com.gic.wechat.api.dto.qywx.QywxMiniprogramMaterialDTO;
import com.gic.wechat.api.dto.qywx.QywxVideoMaterialDTO;
import com.gic.wechat.api.dto.qywx.moment.MomentTaskDTO;
import com.gic.wechat.api.dto.qywx.moment.SenderList;
import com.gic.wechat.api.dto.qywx.moment.Text;
import com.gic.wechat.api.dto.qywx.moment.VisibleRange;
import com.gic.wechat.api.enums.QywxMediaTypeEnum;
import com.gic.wechat.api.service.qywx.QywxExternalUserService;
import com.gic.wechat.api.service.qywx.QywxSuiteApiService;

/**
 * 
* @ClassName: QywxSendApiServiceImpl
* @Description: 企业微信消息发送(群发、朋友圈)
* @author xugh
* @date 2022年11月8日 下午2:39:10
*
 */
@Service
public class QywxSendServiceImpl implements QywxSendService {

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

    @Autowired
    private WxEnterpriseService wxEnterpriseService;
    @Autowired
    private MaterialService materialService;
    @Autowired
    private Config config;
    @Autowired
    private StaffService staffService;
    @Autowired
    private QywxSuiteApiService qywxSuiteApiService;
    @Autowired
    private QywxExternalUserService qywxExternalUserService;
    @Autowired
    private TabHaobanStaffClerkRelationMapper tabHaobanStaffClerkRelationMapper;
    
    private static final String single = "single" ;
    private static final String group = "group" ;

    @Override
    public ServiceResponse<String> sendMessage(String wxEnterpriseId, String staffId, List<String> extendUserList,
            List<String> materialIdList,String planId) {
        return this.send(wxEnterpriseId, staffId, extendUserList, materialIdList, null, 1 , single , planId , 1);
    }

    @Override
    public ServiceResponse<String> sendMessageShare(String wxEnterpriseId, String staffId, List<String> extendUserList,
            List<ContentMaterialDTO> imageList, String message) {
        List<String> materialIdList = this.materialService.getImageMediaId(wxEnterpriseId, imageList, 1);
        return this.send(wxEnterpriseId, staffId, extendUserList, materialIdList, message, 2,null,null,null);
    }

    // 群发发送
    private ServiceResponse<String> send(String wxEnterpriseId, String staffId, List<String> extendUserList,
            List<String> materialIdList, String message, int from , String chatType ,String planId , Integer planType) {
        TabHaobanStaff tabHaobanStaff = staffService.selectById(staffId);
        if (null == tabHaobanStaff) {
            log.info("staff不存在,staffId={}", staffId);
            return ServiceResponse.failure("9999", "群发失败,成员不存在");
        }
        // 群发请求参数
        QywxExternalMessageDTO messageDTO = this.getMessage(from, message, materialIdList,chatType,planId,planType);
        log.info("群发信息={}",JSON.toJSONString(messageDTO));
        if (messageDTO.getAttachments().isEmpty() && StringUtils.isBlank(messageDTO.getContent())) {
            log.info("群发素材不存在, 群发创建失败");
            return ServiceResponse.failure("9999", "群发素材不存在, 群发创建失败");
        }
        messageDTO.setExternalUserid(extendUserList);
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId);
        if (qwDTO.needOpenUserId3th()) {
            messageDTO.setSenderUserId(tabHaobanStaff.getWxOpenUseId());
        } else {
            messageDTO.setSenderUserId(tabHaobanStaff.getWxUserId());
        }
        // 调接口执行创建群发
        JSONResponse respon = null ;
        if(qwDTO.isSelf()) {
            respon = qywxSuiteApiService.sendExternalMessageSelf(qwDTO.getThirdCorpid(), qwDTO.getSelfSecret(),
                    messageDTO , qwDTO.getUrlHost());
        }else {
            respon = qywxSuiteApiService.sendExternalMessage(qwDTO.getThirdCorpid(), config.getWxSuiteid(),
                    messageDTO);
        }
        log.info("群发返回={}",  JSON.toJSONString(respon));
        Map<String, Object> returnMap = respon.getReturnMap();
        String msgIdKey = "msgid";
        String msgId = returnMap.get(msgIdKey) == null ? "" : returnMap.get(msgIdKey).toString();
        if (StringUtils.isNotEmpty(msgId)) {
            return ServiceResponse.success(msgId);
        }
        String error = respon.getErrorMessage();
        return ServiceResponse.failure(respon.getErrorCode()+"", error);
    }

    // 分享朋友圈
    @Override
    public ServiceResponse<String> share(String wxEnterpriseId, List<String> clerkIdList, String message,
            List<ContentMaterialDTO> imageList) {
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId);
        List<String> materialIdList = this.materialService.getImageMediaId(wxEnterpriseId, imageList, 2);
        QywxExternalMessageDTO dto = this.getMessage(2, message, materialIdList,null,null,null);
        MomentTaskDTO moment = EntityUtil.changeEntity(MomentTaskDTO.class, dto);
        Text text = new Text();
        text.setContent(dto.getContent());
        moment.setText(text);
        List<String> sendUser = new ArrayList<>();
        if (CollectionUtils.isEmpty(clerkIdList)) {
            return ServiceResponse.failure("9999", "无导购");
        }
        List<StaffClerkRelationDTO> clerkList = this.tabHaobanStaffClerkRelationMapper.listByClerkIds(clerkIdList,
                wxEnterpriseId);
        if (CollectionUtils.isEmpty(clerkList)) {
            log.info("无发送成员");
            return ServiceResponse.failure("9999", "无发送成员");
        }
        for (StaffClerkRelationDTO item : clerkList) {
            if (qwDTO.needOpenUserId3th()) {
                sendUser.add(item.getOpenUserId());
            } else {
                sendUser.add(item.getQwUserId());
            }
        }
        SenderList senderList = new SenderList();
        senderList.setUser_list(sendUser);
        VisibleRange range = new VisibleRange();
        range.setSender_list(senderList);
        moment.setVisible_range(range);
        ServiceResponse<String> resp = this.qywxExternalUserService.addMomentTask(qwDTO.getThirdCorpid(),
                qwDTO.getSelf3thSecret(), moment,qwDTO.isSelf(),qwDTO.getUrlHost());
        log.info("朋友圈消息={},返回={}", JSON.toJSONString(moment), JSON.toJSONString(resp));
        return resp;
    }

    // from 1好办素材 2内容中台
    private QywxExternalMessageDTO getMessage(int from, String message, List<String> materialIdList , String chatType , String planId , Integer planType) {
        QywxExternalMessageDTO messageDTO = new QywxExternalMessageDTO();
        messageDTO.setChatType(chatType);
        List<QywxMessageMaterialDTO> attachList = new ArrayList<>();
        if (from == 2) {
            if (StringUtils.isNotBlank(message)) {
                messageDTO.setContent(message);
            }
        }
        if (CollectionUtils.isNotEmpty(materialIdList)) {
            materialIdList.forEach(materialId -> {
                MaterialDTO material = materialService.getHasChangeMadieMaterialById(materialId, from);
                log.info("JSON={}", JSON.toJSONString(material));
                if (material == null) {
                    return;
                }
                if (material.getMaterialType() == 1) {
                    messageDTO.setContent(material.getMaterialContent());
                } else {
                    attachList.add(this.getMessageMaterial(material,planId,planType));
                }
            });
        }
        messageDTO.setAttachments(attachList);
        return messageDTO;
    }

    /**
     * 素材发送对象构造
     */
    private QywxMessageMaterialDTO getMessageMaterial(MaterialDTO material,String planId , Integer planType) {
        // 素材类型
        Integer materialType = material.getMaterialType();
        // 企微对应的id
        String maerialId = material.getMediaId();
        // 素材对象
        QywxMessageMaterialDTO dto = new QywxMessageMaterialDTO();
        if (materialType == 2) {
            QywxImageMaterialDTO imageMaterialDTO = new QywxImageMaterialDTO();
            imageMaterialDTO.setMediaId(maerialId);
            dto.setMsgType(QywxMediaTypeEnum.IMAGE.getName());
            dto.setImage(imageMaterialDTO);
        } else if (materialType == 3) {
            QywxLinkMaterialDTO linkMaterialDTO = new QywxLinkMaterialDTO();
            linkMaterialDTO.setTitle(material.getMaterialTitle());
            linkMaterialDTO.setPicUrl(material.getWxImgUrl());
            linkMaterialDTO.setDesc(material.getMaterialDesc());
            linkMaterialDTO.setUrl(material.getLink());
            dto.setMsgType(QywxMediaTypeEnum.LINK.getName());
            dto.setLink(linkMaterialDTO);
        } else if (materialType == 4) {
            QywxVideoMaterialDTO videoMaterialDTO = new QywxVideoMaterialDTO();
            videoMaterialDTO.setMediaId(maerialId);
            dto.setMsgType(QywxMediaTypeEnum.VIDEO.getName());
            dto.setVideo(videoMaterialDTO);
        } else if (materialType == 6) {
            QywxMiniprogramMaterialDTO miniprogramMaterialDTO = new QywxMiniprogramMaterialDTO();
            miniprogramMaterialDTO.setTitle(material.getMaterialTitle());
            miniprogramMaterialDTO.setPicMediaId(maerialId);
            miniprogramMaterialDTO.setAppid(material.getAppId());
            miniprogramMaterialDTO.setPage(material.getLink());
            if(null != planType && StringUtils.isNotBlank(planId)) {
                String url = "qtActivityType="+planType+"&qtActivityId="+planId ;
                if(material.getLink().contains("?")) {
                    url = "&" + url ;
                }else {
                    url = "?" +url ;
                }
                miniprogramMaterialDTO.setPage(material.getLink()+url);
            }
            log.info("群发链接={}",material.getLink(),miniprogramMaterialDTO.getPage());
            dto.setMsgType(QywxMediaTypeEnum.MINIPROGRAM.getName());
            dto.setMiniprogram(miniprogramMaterialDTO);
        }
        return dto;
    }
    
    @Override
    public ServiceResponse<String> sendChatMessage(String wxEnterpriseId, String staffId, List<String> materialIdList,int planType ,String planId) {
        return this.send(wxEnterpriseId, staffId, null, materialIdList, null, 1 , group,planId,planType);
    }

    @Override
    public ServiceResponse<String> sendChatMessage(String wxEnterpriseId, String staffId, List<ContentMaterialDTO> imageList, String message) {
        List<String> materialIdList = this.materialService.getImageMediaId(wxEnterpriseId, imageList, 1);
        return this.send(wxEnterpriseId, staffId, null, materialIdList, message, 2 , group,null,null);
    }
}
