package com.fs.app.controller;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fs.app.params.SendSopParam;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.course.mapper.FsCourseWatchLogMapper;
import com.fs.course.mapper.FsUserCourseVideoMapper;
import com.fs.fastGpt.mapper.FastgptChatVoiceHomoMapper;
import com.fs.fastGpt.service.AiService;
import com.fs.his.domain.FsAppVersion;
import com.fs.his.service.IFsAppVersionService;
import com.fs.qw.domain.*;
import com.fs.qw.mapper.*;
import com.fs.qw.param.QwConfigSignatureParam;
import com.fs.qw.service.*;
import com.fs.qw.vo.QwHookAuthVO;
import com.fs.qwApi.param.QwExternalContactHParam;
import com.fs.qwApi.param.QwSendMsgParam;
import com.fs.qwApi.service.QwApiService;
import com.fs.qwHookApi.param.QwHookSendMsgParam;
import com.fs.qwHookApi.service.QwHookApiService;
import com.fs.qwHookApi.vo.QwHookMsgVO;
import com.fs.qwHookApi.vo.QwHookVO;
import com.fs.sop.mapper.SopUserLogsInfoMapper;
import com.fs.voice.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;

@Api("公共接口")
@RestController
@RequestMapping(value="/app/common")
@Slf4j
public class CommonController {
    @Autowired
    private QwHookApiService qwHookApiService;

    @Autowired
    private IQwUserService qwUserService;

    @Autowired
    QwApiService qwApiService;
    @Autowired
    QwCompanyMapper qwCompanyMapper;

    @Autowired
    private QwExternalContactMapper qwExternalContactMapper;

    @Autowired
    FsCourseWatchLogMapper fsCourseWatchLogMapper;
    @Autowired
    FsUserCourseVideoMapper fsUserCourseVideoMapper;
    @Autowired
    FsCourseWatchLogMapper   watchLogMapper;
    @Autowired
    IQwJsApiService qwGetJsapiTicketService;

    @Autowired
    QwUserMapper qwUserMapper;
    @Autowired
    FastgptChatVoiceHomoMapper fastgptChatVoiceHomoMapper;

    @Autowired
    QwExternalContactCrmMapper qwExternalContactCrmMapper;
    @Autowired
    private IFsAppVersionService appVersionService;
    @Autowired
    RedisCache redisCache;

    @Autowired
    private AiService aiService;

    @Autowired
    private IQwUserVideoService qwUserVideoService;

    @Autowired
    private SopUserLogsInfoMapper sopUserLogsInfoMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @PostMapping("/qwHookNotify")
    public R qwHookNotify(@RequestBody String body) {
        QwHookVO vo= JSONUtil.toBean(body,QwHookVO.class);
        QwHookMsgVO msgVo= JSONUtil.toBean(vo.getData(),QwHookMsgVO.class);
        if (StringUtil.strIsNullOrEmpty(msgVo.getKey())){
            return R.ok();
        }
        msgVo.setKey(msgVo.getKey().replaceAll("[^a-zA-Z0-9\\s]", ""));
        if(vo.getType().equals(104012)||vo.getType().equals(104014)){
            //文件消息
           return aiService.qwHookNotifyAiReply(msgVo,vo.getType());
        }
        //本地消息
        else if(vo.getType().equals(101003)){
            //文件消息
            rocketMQTemplate.syncSend("msg", JSON.toJSONString(msgVo));
            //文件消息
            return R.ok();
        }
        else if(vo.getType().equals(101007)||vo.getType().equals(101008)||vo.getType().equals(101004)||vo.getType().equals(101001)){
           //转人工
            aiService.artificial(vo);
        }
        else if(vo.getType().equals(104001)){
            //登录成功
            updateQwUserByAppKey(msgVo.getKey(),1L,msgVo.getVersion());
            //成功后 清除redis中的二维码
            redisCache.deleteObject("QwLoginCode:"+msgVo.getKey());

        }else if (vo.getType().equals(103006)){
            //弹出二维码了-那就是掉线了，改状态
            updateQwUserByAppKey(msgVo.getKey(),0L,msgVo.getVersion());
            //还是存redis，二维码一分钟过期
            redisCache.setCacheObject("QwLoginCode:"+msgVo.getKey().trim(),msgVo.getQr_code(),1, TimeUnit.MINUTES);

            String msg="<font color=\"warning\">您的云主机，企业微信登录需要【重新扫描二维码】！请扫描二维码登录</font>";
            sendQwMsg(msgVo.getKey(),msg);

        }else if (vo.getType().equals(104002)){
            //退出登录
            updateQwUserByAppKey(msgVo.getKey(),0L,msgVo.getVersion());
            redisCache.deleteObject("QwLoginCode:"+msgVo.getKey());

            String msg="<font color=\"warning\">您的云主机，企业微信【已退出登录】！！望悉知~</font>";
            sendQwMsg(msgVo.getKey(),msg);

        }else if (vo.getType().equals(104000)){

            //客户端关闭
            updateQwUserByAppKey(msgVo.getKey(),0L,msgVo.getVersion());

            redisCache.deleteObject("QwLoginCode:"+msgVo.getKey());

        }
        //重新登录
        else if (vo.getType().equals(108022)){
            SendSopParam sopParam=new SendSopParam();
            sopParam.setCmd("login");
            sopParam.setKey(msgVo.getKey());
            qwUserMapper.updateQwUserRemarkByAppKey(msgVo.getKey());
        }else if (vo.getType().equals(108024)){

            //企微崩溃
            qwUserMapper.updateQwUserDelRemarkByAppKey(msgVo.getKey());

            String msg="<font color=\"warning\">您的云主机，企业微信【崩溃】啦！！请联系管理员处理~~望悉知~</font>";
            sendQwMsg(msgVo.getKey(),msg);
        }
        //接收到视频号
        else if (vo.getType().equals(104017)){
            QwUserVideo userVideo=new QwUserVideo();
            userVideo.setAppKey(msgVo.getKey());
            userVideo.setSenderName(msgVo.getSender_name());
            userVideo.setNickName(msgVo.getNickname());
            userVideo.setObjectId(msgVo.getObjectId());
            userVideo.setCoverUrl(msgVo.getCover_url());
            userVideo.setThumbUrl(msgVo.getThumb_url());
            userVideo.setAvatar(msgVo.getAvatar());
            userVideo.setDesc(msgVo.getDesc());
            userVideo.setUrl(msgVo.getUrl());
            userVideo.setExtras(msgVo.getExtras());
            qwUserVideoService.insertQwUserVideo(userVideo);
        }
        else if (vo.getType().equals(102019)){

            handleSopBlockOrDel(msgVo,5);
        }
        else if (vo.getType().equals(102018)){

            handleSopBlockOrDel(msgVo,6);
        }
        return R.ok();
    }

    /**
    * 处理拉黑或删除的客户的营期
    */
    private void handleSopBlockOrDel(QwHookMsgVO msgVo,Integer status){
        //处理拉黑的
        String appKey = msgVo.getKey();
        //客户编号
        String receiverOpenid = msgVo.getReceiver_openid();

        if (StringUtil.strIsNullOrEmpty(appKey) || StringUtil.strIsNullOrEmpty(receiverOpenid)){
            log.error("删除或拉黑-处理营期失败数据不对："+appKey+"|"+receiverOpenid);
            return;
        }

        try {
            QwUser qwUser = qwUserMapper.selectQwUserByAppKey(appKey);
            if (qwUser!=null){

                //修改客户状态
                QwExternalContact contact=new QwExternalContact();
                contact.setStatus(status);
                contact.setUserId(qwUser.getQwUserId());
                contact.setCorpId(qwUser.getCorpId());
                contact.setExternalUserId(receiverOpenid);
                qwExternalContactMapper.updateQwExternalContactByUseridBlock(contact);


                log.info("删除或拉黑-处理营期-"+qwUser.getQwUserId()+"|"+qwUser.getCorpId()+"|"+receiverOpenid);

                //删除营期
                sopUserLogsInfoMapper.deleteByQwUserIdAndCorpIdToContactId(qwUser.getQwUserId(),qwUser.getCorpId(),receiverOpenid);

            }

        }catch (Exception e){
            log.error("删除或拉黑-处理营期失败："+appKey+"|"+receiverOpenid+"|"+e.getMessage());
        }

    }

    /**
    * 给企业微信的应用发送消息
    */
    private void sendQwMsg(String appKey,String msg){
        QwUser qwUserByAppKey = qwUserMapper.selectQwUserByAppKey(appKey);

        QwSendMsgParam sendMsgParam = new QwSendMsgParam();
        QwCompany qwCompany = qwCompanyMapper.selectQwCompanyByCorpId(qwUserByAppKey.getCorpId());
        sendMsgParam.setAgentid(Integer.parseInt(qwCompany.getServerAgentId().trim()));
        sendMsgParam.setTouser(qwUserByAppKey.getQwUserId());

        QwSendMsgParam.Markdown markdown = new QwSendMsgParam.Markdown();
        markdown.setContent(msg);

        sendMsgParam.setMarkdown(markdown);
        sendMsgParam.setMsgtype("markdown");
        qwApiService.sendMsg(sendMsgParam, qwCompany.getCorpId());

    }
    /**
    * 修改企业微信登录状态
    */
    private void  updateQwUserByAppKey(String appKey,Long status,String version){
        QwUser qwUser=new QwUser();
        qwUser.setAppKey(appKey);
        qwUser.setLoginStatus(status);
        qwUser.setVersion(version);
        qwUserMapper.updateQwUserByAppKey(qwUser);
    }

    @PostMapping("/qwHookSendMsg")
    public R qwHookSendMsg(@RequestBody QwHookSendMsgParam param ) {
        param.setClientId(2);
        return qwHookApiService.sendMsg(param);
    }

    @GetMapping("/qwHookAuth")
    public R qwHookAuth(@RequestParam(value = "key", required = false) String key) {
        QwHookAuthVO qwHookAuthVO = qwUserService.selectQwUserByAppKeyAuth(key);
        if(qwHookAuthVO!=null){
            return R.ok().put("data",qwHookAuthVO);
        }
        else {
            return R.error("未查询到相关成员信息,请检查授权码是否正确");
        }
    }

    @GetMapping("/qwHookCheck")
    public R qwHookCheckCorpId(@RequestParam(value = "key", required = false) String key,@RequestParam(value = "qwHookId", required = false) String qwHookId,@RequestParam(value = "corpId", required = false) String corpId) {
        QwUser user=qwUserService.selectQwUserByAppKey(key);
        if(user.getCorpId().equals(corpId)){
            if(user.getQwHookId().equals(qwHookId)){
                return R.ok();
            }
            else{
                return R.error("此帐号绑定的企业微信未授权");
            }
        }
        else{
           return R.error("此帐号绑定的企业微信未授权");
        }
    }
    //获取企业微信签名
    @PostMapping("/getConfigSignature")
    public R getConfigSignature(@RequestBody QwConfigSignatureParam qwConfigSignatureParam) throws Exception {
        return qwGetJsapiTicketService.getQwJsapiTicket(qwConfigSignatureParam);
    }

    //根据userid和外部联系人id获取到客户详情
    @PostMapping("/getQwExternalContactDetails")
    public R getQwExternalContactDetails(@RequestBody QwExternalContactHParam param){
        return qwGetJsapiTicketService.getQwExternalContactDetails(param);
    }



    @ApiOperation("获取最新版本")
    @GetMapping("/getNewAppVersion")
    public R getNewAppVersion(@RequestParam("appType")Integer appType)
    {
//        System.out.println("111");
        FsAppVersion version=appVersionService.getNewVersion(appType,3);
        return R.ok().put("data",version);
    }

}
