package com.fs.app.controller;



import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.json.JSONUtil;
import com.baidubce.appbuilder.model.agentbuilder.AgentBuilderResult;
import com.fs.ai.service.IBaiduAIService;
import com.fs.ai.vo.BaiduAIMsgResultVO;
import com.fs.ai.vo.BaiduAIMsgVO;
import com.fs.app.utils.JwtUtils;
import com.fs.app.vo.MsgVO;

import com.fs.chat.config.QwConfig;
import com.fs.chat.config.WxConfig;
import com.fs.chat.domain.*;
import com.fs.chat.service.*;
import com.fs.common.core.redis.RedisCache;
import com.fs.company.domain.CompanyConfig;
import com.fs.company.service.ICompanyConfigService;
import com.fs.his.service.*;

import com.fs.his.utils.ConfigUtil;
import com.fs.system.service.ISysConfigService;
import com.fs.system.service.ISysDictDataService;
import com.fs.voice.utils.StringUtil;
import com.fs.wx.kf.dto.*;
import com.fs.wx.kf.service.IWeixinKfService;
import com.fs.wx.kf.vo.WeixinKfMsgItemVO;
import com.fs.wx.kf.vo.WeixinKfMsgVO;
import com.fs.wx.kf.vo.WeixinKfUserItemVO;
import com.fs.wx.kf.vo.WeixinKfUserVO;
import com.google.code.kaptcha.Producer;
import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Element;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.stream.Collectors;

import static com.fs.common.constant.FsConstants.REDIS_CHAT_NEXTCURSOR;
import static com.fs.common.constant.FsConstants.REDIS_CHAT_SESSION;


@Api("公共接口")
@RestController
@RequestMapping(value="/app/common/weixinkfAuth")
public class CommonController {

    private static Logger logger = Logger.getLogger("com.fs.app.controller.CommonController");
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    ConfigUtil configUtil;
    @Autowired
    private IFsCityService cityService;

    @Autowired
    private IFsAppVersionService appVersionService;

    @Autowired
    private IFsInquiryOrderMsgService inquiryOrderMsgService;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    // 验证码类型
    @Value("${fs.captchaType}")
    private String captchaType;
    @Autowired
    private ICompanyConfigService companyConfigService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IWeixinKfService weixinKfService;
    @Autowired
    private IBaiduAIService baiduAIService;
    @Autowired
    private IChatRoleService chatRoleService;
    @Autowired
    private IChatKeywordService chatKeywordService;
    @Autowired
    private IChatMsgService chatMsgService;
    @Autowired
    private IChatSessionService chatSessionService;
    @Autowired
    private IChatUserService chatUserService;
    @GetMapping(value = "/{companyId}",produces = "text/plain;charset=utf-8")
    public String weixinkfAuth(
            @PathVariable Long companyId,
            @RequestParam(name = "msg_signature", required = false) String msg_signature,
            @RequestParam(name = "timestamp", required = false) String timestamp,
            @RequestParam(name = "nonce", required = false) String nonce,
            @RequestParam(name = "echostr", required = false) String echostr ) throws AesException {
        logger.info("回调数据:signature:"+msg_signature);
        logger.info("回调数据:timestamp:"+timestamp);
        logger.info("回调数据:nonce:"+nonce);
        logger.info("回调数据:echostr:"+echostr);
//		final WxCpService wxCpService = WxCpConfiguration.getCpService(1000005);
//		if (wxCpService.checkSignature(msg_signature, timestamp, nonce, echostr)) {
//			return new WxCpCryptUtil(wxCpService.getWxCpConfigStorage()).decrypt(echostr);
//		}
        CompanyConfig config=companyConfigService.selectCompanyConfigByKey(companyId,"qw:config");
        QwConfig qwConfig=JSONUtil.toBean(config.getConfigValue(), QwConfig.class);
        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(qwConfig.getToken(),
                qwConfig.getEncodingAESKey(), "");

        return wxcpt.verifyUrl(msg_signature, timestamp, nonce, echostr);

    }
    @PostMapping(value = "/{companyId}",produces = "application/xml; charset=UTF-8")
    public void post(
            @PathVariable Long companyId,
            @RequestBody String requestBody,
            @RequestParam("msg_signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce
    ) throws AesException {
        logger.info("收到数据:requestBody:"+requestBody);
        logger.info("收到数据:msg_signature:"+signature);
        logger.info("收到数据:timestamp:"+timestamp);
        logger.info("收到数据:nonce:"+nonce);
        CompanyConfig config=companyConfigService.selectCompanyConfigByKey(companyId,"qw:config");
        QwConfig qwConfig=JSONUtil.toBean(config.getConfigValue(), QwConfig.class);
        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(qwConfig.getToken(),
                qwConfig.getEncodingAESKey(), "");

        String decryptMsg= wxcpt.decryptMsg(signature, timestamp, nonce, requestBody);
        logger.info("收到数据:decryptMsg:"+decryptMsg);
        Element rootElement = XmlUtil.getRootElement(XmlUtil.parseXml(decryptMsg));
        // 使用根节点下的直接 转成对象
        MsgVO dataBean = XmlUtil.xmlToBean(rootElement, MsgVO.class);
        logger.info("收到数据:msg:"+ JSONUtil.toJsonStr(dataBean));
        Boolean hasMore=true;
        while (hasMore){
            String next_cursor=redisCache.getCacheObject(REDIS_CHAT_NEXTCURSOR+dataBean.getOpenKfId());
            WeixinKfMsgDTO dto=new WeixinKfMsgDTO();
            dto.setLimit(1000);
            if(StringUtils.isNotEmpty(next_cursor)){
                logger.info("设置游标:"+ JSONUtil.toJsonStr(next_cursor));
                dto.setCursor(next_cursor);
            }
            dto.setOpen_kfid(dataBean.getOpenKfId());
            dto.setToken(dataBean.getToken());
            WeixinKfMsgVO msgVO=weixinKfService.getMsg(qwConfig.getCorpId(),qwConfig.getSecret(),dto);
            logger.info("收到数据:msgVO:"+ JSONUtil.toJsonStr(msgVO));
            if(msgVO.getMsg_list()!=null&&msgVO.getMsg_list().size()>0){
                this.opMsg(msgVO.getMsg_list(),qwConfig,companyId);
            }
            redisCache.setCacheObject(REDIS_CHAT_NEXTCURSOR+dataBean.getOpenKfId(),msgVO.getNext_cursor());
            if(msgVO.getHas_more().equals(1)){

            }
            else{
                hasMore=false;
            }
        }

    }
    public void opMsg(List<WeixinKfMsgItemVO> msg_list,QwConfig qwConfig,Long companyId){
        for(WeixinKfMsgItemVO itemVO:msg_list){
            WeixinKfMsgSendDTO dto=new WeixinKfMsgSendDTO();
            dto.setMsgid(itemVO.getMsgid());
            dto.setTouser(itemVO.getExternal_userid());
            dto.setOpen_kfid(itemVO.getOpen_kfid());
            dto.setMsgtype("text");
            WeixinKfTextMsgDTO textMsg=new WeixinKfTextMsgDTO();
            textMsg.setContent("已关闭微信客服功能，请通过销售端或APP使用AI，使用方法可咨询商务部");
            dto.setText(textMsg);
            weixinKfService.sendMsg(qwConfig.getCorpId(),qwConfig.getSecret(),dto);
            return;

//            if(chatMsgService.checkMsg(itemVO.getMsgid())>0){
//                return;
//            }
//            if(itemVO.getMsgtype().equals("text")){
//                //获取微信用户
//                WeixinKfUserDTO userDTO=new WeixinKfUserDTO();
//                List<String> userIds=new ArrayList<>();
//                userIds.add(itemVO.getExternal_userid());
//                userDTO.setExternal_userid_list(userIds);
//                WeixinKfUserVO kfUserVO=weixinKfService.getUserInfo(qwConfig.getCorpId(),qwConfig.getSecret(),userDTO);
//                if(kfUserVO.getCustomer_list()!=null&&kfUserVO.getCustomer_list().size()>0){
//                    for(WeixinKfUserItemVO userItemVO:kfUserVO.getCustomer_list()){
//                        ChatUser chatUser=chatUserService.selectChatUserByExternalUserId(userItemVO.getExternal_userid());
//                        if(chatUser==null){
//                            chatUser=new ChatUser();
//                            chatUser.setAvatar(userItemVO.getAvatar());
//                            chatUser.setExternalUserid(userItemVO.getExternal_userid());
//                            chatUser.setGender(userItemVO.getGender());
//                            chatUser.setNickname(userItemVO.getNickname());
//                            chatUser.setUnionid(userItemVO.getUnionid());
//                            chatUserService.insertChatUser(chatUser);
//                        }
//                    }
//                }
//
//
//
//                //获取SESSION
//                Long sessionId=redisCache.getCacheObject(REDIS_CHAT_SESSION+itemVO.getExternal_userid()+":"+itemVO.getOpen_kfid());
//                if(sessionId==null){
//                    ChatSession chatSession=new ChatSession();
//                    String sessionCode = IdUtil.getSnowflake(0, 0).nextIdStr();
//                    chatSession.setSessionCode(sessionCode);
//                    ChatUser chatUser=chatUserService.selectChatUserByExternalUserId(itemVO.getExternal_userid());
//                    chatSession.setAvatar(chatUser.getAvatar());
//                    chatSession.setNickName(chatUser.getNickname());
//                    chatSession.setCompanyId(companyId);
//                    chatSession.setKfId(itemVO.getOpen_kfid());
//                    chatSession.setUserId(itemVO.getExternal_userid());
//                    chatSession.setStatus(1);
//                    chatSession.setUserType(1);
//                    chatSessionService.insertChatSession(chatSession);
//                    sessionId=chatSession.getSessionId();
//                    //重新创建REDIS
//                }
//                redisCache.setCacheObject(REDIS_CHAT_SESSION+itemVO.getExternal_userid()+":"+itemVO.getOpen_kfid(),sessionId,10, TimeUnit.MINUTES);
//                ChatRole chatRole=chatRoleService.selectChatRoleByKfId(itemVO.getOpen_kfid());
//                if(chatRole!=null){
//                    ChatMsg msg=new ChatMsg();
//                    ChatUser chatUser=chatUserService.selectChatUserByExternalUserId(itemVO.getExternal_userid());
//                    msg.setAvatar(chatUser.getAvatar());
//                    msg.setNickName(chatUser.getNickname());
//                    msg.setSessionId(sessionId);
//                    msg.setExtId(itemVO.getMsgid());
//                    msg.setMsgType(1);
//                    msg.setUserType(1);
//                    msg.setUserId(itemVO.getExternal_userid());
//                    msg.setContent(itemVO.getText().getContent());
//                    msg.setCompanyId(companyId);
//                    msg.setRoleId(chatRole.getRoleId());
//                    msg.setSendType(1);
//                    chatMsgService.insertChatMsg(msg);
//                    ChatKeyword chatKeyword=chatKeywordService.selectChatKeywordByKeyword(companyId,itemVO.getText().getContent());
//                    if(chatKeyword!=null){
//                        //关键词回复
//                        if(chatKeyword.getType().equals(1)){
//                            WxConfig wxConfig=JSONUtil.toBean(chatRole.getModeConfigJson(), WxConfig.class);
//                            WeixinKfMsgSendDTO sendDTO1=new WeixinKfMsgSendDTO();
//                            sendDTO1.setMsgid(itemVO.getMsgid());
//                            sendDTO1.setTouser(itemVO.getExternal_userid());
//                            sendDTO1.setOpen_kfid(itemVO.getOpen_kfid());
//                            sendDTO1.setMsgtype("text");
//                            WeixinKfTextMsgDTO textDTO1=new WeixinKfTextMsgDTO();
//                            textDTO1.setContent(chatKeyword.getContent());
//                            sendDTO1.setText(textDTO1);
//                            weixinKfService.sendMsg(qwConfig.getCorpId(),qwConfig.getSecret(),sendDTO1);
//                            //写入记录
//                            msg.setSendType(2);
//                            msg.setExtId(sendDTO1.getMsgid());
//                            msg.setContent(textDTO1.getContent());
//                            chatMsgService.insertChatMsg(msg);
//                        }
//
//                    }
//                    else if(itemVO.getText().getContent().contains("人工")&&itemVO.getText().getContent().length()<5){
//                        WeixinKfMsgSendDTO sendDTO1=new WeixinKfMsgSendDTO();
//                        sendDTO1.setMsgid(itemVO.getMsgid());
//                        sendDTO1.setTouser(itemVO.getExternal_userid());
//                        sendDTO1.setOpen_kfid(itemVO.getOpen_kfid());
//                        sendDTO1.setMsgtype("image");
//                        WeixinKfImageMsgDTO imageMsgDTO=new WeixinKfImageMsgDTO();
//                        imageMsgDTO.setMedia_id("3Rk2OvmImBKqR5EMv9HivajCQ_gzTUQeNrb1T9ZhtqGZN6exohlb-84FnS0JW_xj8");
//                        sendDTO1.setImage(imageMsgDTO);
//                        weixinKfService.sendMsg(qwConfig.getCorpId(),qwConfig.getSecret(),sendDTO1);
//                        //写入记录
//                        msg.setSendType(2);
//                        msg.setExtId(sendDTO1.getMsgid());
//                        msg.setMsgType(2);
//                        msg.setContent(imageMsgDTO.getMedia_id());
//                        chatMsgService.insertChatMsg(msg);
//                    }
//                    else{
//                        //AI回复
//                        WxConfig wxConfig=JSONUtil.toBean(chatRole.getModeConfigJson(), WxConfig.class);
//                        ChatSession session=chatSessionService.selectChatSessionBySessionId(sessionId);
//                        BaiduAIMsgResultVO vo=baiduAIService.run(wxConfig.getAppId(),session.getBaiduSessionId(),itemVO.getText().getContent());
//                        if(StringUtils.isNotEmpty(vo.getConversationId())){
//                            ChatSession sessionMap=new ChatSession();
//                            sessionMap.setSessionId(sessionId);
//                            sessionMap.setBaiduSessionId(vo.getConversationId());
//                            chatSessionService.updateChatSession(sessionMap);
//                        }
//                        logger.info("AI回复数据:msgVO:"+ JSONUtil.toJsonStr(vo));
//                        WeixinKfMsgSendDTO sendDTO1=new WeixinKfMsgSendDTO();
//                        sendDTO1.setMsgid(itemVO.getMsgid());
//                        sendDTO1.setTouser(itemVO.getExternal_userid());
//                        sendDTO1.setOpen_kfid(itemVO.getOpen_kfid());
//                        sendDTO1.setMsgtype("text");
//                        WeixinKfTextMsgDTO textDTO1=new WeixinKfTextMsgDTO();
//                        //过滤** 特殊字符
//                        String str=vo.getResult().getAnswer();
//                        str=str.replaceAll("\\*\\*.*\\*\\*\\^\\[.*\\]\\^\n\n", "");
//                        str=str.replaceAll("\\^\\[.*\\]\\^", "");
//                        str=str.replaceAll("\\*\\*", "");
//                        str=str.replaceAll("\\*", "");
//                        textDTO1.setContent(str);
//                        sendDTO1.setText(textDTO1);
//                        weixinKfService.sendMsg(qwConfig.getCorpId(),qwConfig.getSecret(),sendDTO1);
//                        //写入记录
//                        msg.setSendType(2);
//                        msg.setExtId(sendDTO1.getMsgid());
//                        msg.setContent(textDTO1.getContent());
//                        chatMsgService.insertChatMsg(msg);
//                    }
//                }
//                else{
//                    WeixinKfMsgSendDTO sendDTO1=new WeixinKfMsgSendDTO();
//                    sendDTO1.setMsgid(itemVO.getMsgid());
//                    sendDTO1.setTouser(itemVO.getExternal_userid());
//                    sendDTO1.setOpen_kfid(itemVO.getOpen_kfid());
//                    sendDTO1.setMsgtype("text");
//                    WeixinKfTextMsgDTO textDTO1=new WeixinKfTextMsgDTO();
//                    textDTO1.setContent("未配置AI客服,请联系管理员");
//                    sendDTO1.setText(textDTO1);
//                    weixinKfService.sendMsg(qwConfig.getCorpId(),qwConfig.getSecret(),sendDTO1);
//                    //未配置客服
//                }
////				WeixinKfMsgSendDTO sendDTO=new WeixinKfMsgSendDTO();
////				sendDTO.setMsgid(itemVO.getMsgid());
////				sendDTO.setTouser(itemVO.getExternal_userid());
////				sendDTO.setOpen_kfid(itemVO.getOpen_kfid());
////				sendDTO.setMsgtype("text");
////				WeixinKfTextMsgDTO textDTO=new WeixinKfTextMsgDTO();
////				textDTO.setContent("正在回答中...");
////				sendDTO.setText(textDTO);
////				weixinKfService.sendMsg(sendDTO);
//
//            }
//            else if(itemVO.getMsgtype().equals("event")&&itemVO.getEvent().getEvent_type().equals("enter_session")){
//                //发送欢迎语
////                WeixinKfEventMsgSendDTO sendDTO=new WeixinKfEventMsgSendDTO();
////                sendDTO.setCode(itemVO.getEvent().getWelcome_code());
////                sendDTO.setMsgtype("text");
////                WeixinKfTextMsgDTO textMsgDTO=new WeixinKfTextMsgDTO();
////                textMsgDTO.setContent("我是您的智能客服，请问有什么可以帮您？？如需人工服务，请直接输入【转人工】");
////                sendDTO.setText(textMsgDTO);
////                weixinKfService.sendEventMsg(qwConfig.getCorpId(),qwConfig.getSecret(),sendDTO);
////                logger.info("收到进入事件数据:msg:"+ JSONUtil.toJsonStr(itemVO));
//            }
        }
    }


}
