package com.tzld.piaoquan.api.service.wecom.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tzld.piaoquan.api.dao.mapper.AutoReplyMsgSendRecordMapper;
import com.tzld.piaoquan.api.dao.mapper.ReplyStaffMapper;
import com.tzld.piaoquan.api.model.bo.MsgData;
import com.tzld.piaoquan.api.model.po.AutoReplyMsgSendRecord;
import com.tzld.piaoquan.api.model.po.ReplyStaff;
import com.tzld.piaoquan.api.model.po.ReplyStaffExample;
import com.tzld.piaoquan.api.model.vo.WeComPushMessageVo;
import com.tzld.piaoquan.api.service.wecom.WeComAutoReply;
import com.tzld.piaoquan.api.service.wecom.WeComService;
import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
import com.tzld.piaoquan.growth.common.dao.mapper.CorpMapper;
import com.tzld.piaoquan.growth.common.model.bo.MsgResult;
import com.tzld.piaoquan.growth.common.model.po.Corp;
import com.tzld.piaoquan.growth.common.service.MessageAttachmentService;
import com.tzld.piaoquan.growth.common.service.MessageService;
import com.tzld.piaoquan.growth.common.service.WeComUserService;
import com.tzld.piaoquan.growth.common.utils.LarkRobotUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Slf4j
@Service
public class WeComAutoReplyImpl implements WeComAutoReply {

    @Autowired
    private WeComService weComService;

    @Autowired
    private MessageAttachmentService messageAttachmentService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private CorpMapper corpMapper;

    @Autowired
    private WeComUserService weComUserService;

    @Autowired
    private HttpPoolClient httpPoolClient;

    @Autowired
    private AutoReplyMsgSendRecordMapper autoReplyMsgSendRecordMapper;

    @Autowired
    private ReplyStaffMapper replyStaffMapper;

    @Override
    public void AutoReplyMessage(String welcomeCode, String externalUserId, String userId, Long corpId) {
        Corp corp = corpMapper.selectByPrimaryKey(corpId);
        String corpCorpId = corp.getCorpId();
        // 判断是否需要自动回复
        ReplyStaffExample example = new ReplyStaffExample();
        example.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(0);
        List<ReplyStaff> replyStaffs = replyStaffMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(replyStaffs)) {
            return;
        }
        List<WeComPushMessageVo> weComPushMessageVoList = weComService.getPushMessageByUserId(replyStaffs);
        WeComPushMessageVo weComPushMessageVo = getRandomElement(weComPushMessageVoList);
        if (weComPushMessageVo == null) {
            LarkRobotUtil.sendMessage("自动回复消息获取失败，userId=" + userId);
            log.error("自动回复消息获取失败，userId=" + userId);
            return;
        }
        List<MsgData> msgDataList = weComPushMessageVo.getMsgDataList();
        if (CollectionUtils.isEmpty(msgDataList)) {
            LarkRobotUtil.sendMessage("自动回复分组内容为空，userId=" + userId);
            log.error("自动回复分组内容为空，userId=" + userId);
            return;
        }

        List<AutoReplyMsgSendRecord> autoReplyMsgSendRecords = new ArrayList<>();
        JSONObject param = new JSONObject();
        param.put("welcome_code", welcomeCode);
        JSONArray attachments = new JSONArray();
        for (MsgData msgData : msgDataList) {
            //小程序
            if (msgData.getMsgType() == 1) {
                JSONObject attachment = new JSONObject();
                attachment.put("msgtype", "miniprogram");
                JSONObject miniprogram = new JSONObject();
                String picMediaId = messageAttachmentService.getPicMediaId(msgData.getCoverUrl(), corpId, msgData.getMiniVideoId());
                miniprogram.put("title", msgData.getTitle());
                miniprogram.put("pic_media_id", picMediaId);
                miniprogram.put("appid", msgData.getMiniAppId());
                miniprogram.put("page", msgData.getMiniPagePath());
                attachment.put("miniprogram", miniprogram);
                attachments.add(attachment);
            }
            if (msgData.getMsgType() == 2) {
                JSONObject attachment = new JSONObject();
                attachment.put("msgtype", "link");
                JSONObject link = new JSONObject();
                link.put("title", msgData.getTitle());
                link.put("picurl", msgData.getCoverUrl());
                link.put("desc", msgData.getNewsDescription());
                link.put("url", msgData.getNewsUrl());
                attachment.put("link", link);
                attachments.add(attachment);
            }
            if (msgData.getMsgType() == 3) {
                JSONObject text = new JSONObject();
                text.put("content", msgData.getTitle());
                param.put("text", text);
            }
            AutoReplyMsgSendRecord autoReplyMsgSendRecord = new AutoReplyMsgSendRecord();
            autoReplyMsgSendRecord.setMsgType(msgData.getMsgType());
            autoReplyMsgSendRecord.setCorpId(corpCorpId);
            autoReplyMsgSendRecord.setUserId(userId);
            autoReplyMsgSendRecord.setGroupId(String.valueOf(weComPushMessageVo.getGroupIndex()));
            autoReplyMsgSendRecord.setExternalUserId(externalUserId);
            autoReplyMsgSendRecord.setMiniVideoId(msgData.getMiniVideoId());
            autoReplyMsgSendRecord.setNewsPublishContentId(msgData.getNewsPublishContentId());
            autoReplyMsgSendRecords.add(autoReplyMsgSendRecord);
        }
        if (!CollectionUtils.isEmpty(attachments)) {
            param.put("attachments", attachments);
        }
        MsgResult msgResult = messageService.sendAutoReplyMessage(param, corpId);
        long resultTime = System.currentTimeMillis();
        for (AutoReplyMsgSendRecord autoReplyMsgSendRecord : autoReplyMsgSendRecords) {
            try {
                autoReplyMsgSendRecord.setMsgId(0L);
                if (msgResult.getErrcode() == 0) {
                    autoReplyMsgSendRecord.setStatus(1);
                } else {
                    autoReplyMsgSendRecord.setStatus(2);
                    autoReplyMsgSendRecord.setErrorMsg(msgResult.getErrmsg());
                }
                autoReplyMsgSendRecord.setSendTimestamp(resultTime);
                autoReplyMsgSendRecordMapper.insertSelective(autoReplyMsgSendRecord);
                sendResult(autoReplyMsgSendRecord);
            } catch (Exception e) {
                log.error("saveAutoReplyMsgSendRecord error", e);
            }
        }
    }


    private WeComPushMessageVo getRandomElement(List<WeComPushMessageVo> weComPushMessageVoList) {
        if (CollectionUtils.isEmpty(weComPushMessageVoList)) {
            return null;
        }
        Random random = new Random();
        int randomIndex = random.nextInt(weComPushMessageVoList.size());
        return weComPushMessageVoList.get(randomIndex);
    }

    private String getName(String externalUserId, Long cropId) {
        try {
            JSONObject userDetail = weComUserService.getUserDetail(externalUserId, cropId);
            return userDetail.getJSONObject("external_contact").getString("name");
        } catch (Exception e) {
            log.error("WeComAutoReplyImpl getName error", e);
        }
        return null;
    }

    private void sendResult(AutoReplyMsgSendRecord autoReplyMsgSendRecord) {
        try {
            String url = "http://aigc-api.cybertogether.net//aigc/publish/api/saveWorkWxAutoReplyMsgSendRecords";
            String res = httpPoolClient.post(url, JSONObject.toJSONString(autoReplyMsgSendRecord));
            log.info("WeComAutoReplyImpl sendResult res={}", res);
        } catch (Exception e) {
            log.error("sendResult error", e);
        }
    }
}
