package com.fs.app.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fs.app.params.SendAIParam;
import com.fs.app.websocket.service.WebSocketServer;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.company.service.ICompanyConfigService;
import com.fs.course.mapper.FsCourseSopLogsMapper;
import com.fs.course.mapper.FsCourseSopMapper;
import com.fs.course.mapper.FsCourseWatchLogMapper;
import com.fs.course.param.FsCourseLinkCreateParam;
import com.fs.course.service.IFsCourseLinkService;
import com.fs.crm.mapper.CrmCustomerMapper;
import com.fs.store.mapper.FsUserMapper;
import com.fs.qw.domain.QwUser;
import com.fs.qw.mapper.*;
import com.fs.qw.service.*;
import com.fs.qw.service.impl.AsyncSopService;
import com.fs.qw.vo.QwFriendWelcomeDayPart;
import com.fs.qw.vo.QwFriendWelcomeVO;
import com.fs.qwApi.domain.QwResult;
import com.fs.qwApi.domain.inner.TextMessage;
import com.fs.qwApi.param.SendWelcomeMsgParam;
import com.fs.qwApi.service.QwApiService;
import com.fs.qwHookApi.param.QwHookSendMsgParam;
import com.fs.sop.mapper.QwSopLogsMapper;
import com.fs.sop.mapper.QwSopMapper;
import com.fs.sop.mapper.SopUserLogsInfoMapper;
import com.fs.sop.service.IQwSopService;
import com.fs.sop.service.ISopUserLogsService;
import com.fs.voice.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping(value="/app/test")
public class testController {

    @Autowired
    RedisCache redisCache;
    @Autowired
    QwExternalContactMapper qwExternalContactMapper;
    @Autowired
    QwUserMapper qwUserMapper;
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    @Autowired
    IQwSopService qwSopService;
    @Autowired
    QwSopMapper qwSopMapper;

    @Autowired
    ICompanyConfigService companyConfigService;

    @Autowired
    private FsCourseWatchLogMapper watchLogMapper;

    @Autowired
    private AsyncSopService asyncSopService;

    @Autowired
    QwApiService qwApiService;
    @Autowired
    QwContactWayMapper qwContactWayMapper;
    @Autowired
    private QwExternalContactTransferLogMapper qwExternalContactTransferLogMapper;
    @Autowired
    IQwContactWayService qwContactWayService;
    @Autowired
    QwContactWayUserMapper qwContactWayUserMapper;
    @Autowired
    QwContactWayLogsMapper qwContactWayLogsMapper;

    @Autowired
    QwFriendWelcomeMapper qwFriendWelcomeMapper;

    @Autowired
    QwAutoTagsMapper qwAutoTagsMapper;
    @Autowired
    CrmCustomerMapper crmCustomerMapper;
    @Autowired
    QwAutoTagsLogsMapper qwAutoTagsLogsMapper;

    @Autowired
    IQwExternalContactCrmService contactCrmService;

    @Autowired
    FsCourseSopLogsMapper fsSopLogsMapper;

    @Autowired
    FsCourseSopMapper fsSopMapper;

    @Autowired
    CrmCustomerMapper customerMapper;

    @Autowired
    FsCourseWatchLogMapper fsCourseWatchLogMapper;

    @Autowired
    private IFsCourseLinkService fsCourseLinkService;
    @Autowired
    QwAppContactWayLogsMapper qwAppContactWayLogsMapper;


    @Autowired
    private FsUserMapper fsUserMapper;
    @Autowired
    private QwSopLogsMapper qwSopLogsMapper;

    @Autowired
    private QwAppContactWayMapper  qwAppContactWayMapper;
    @Autowired
    private SopUserLogsInfoMapper sopUserLogsInfoMapper;


    @Autowired
    private ISopUserLogsService sopUserLogsService;

    @Autowired
    private IFsCourseLinkService iFsCourseLinkService;

    @Autowired
    private IQwExternalErrRetryService errRetryService;

    @Autowired
    IQwExternalContactService qwExternalContactService;

    @GetMapping("/qwHookNotify")
    public R qwHookNotify() throws ParseException {

//        sopUserLogsService.repairSopUserLogsTimer();
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now().withMinute(0).withSecond(0).withNano(0);
        LocalDateTime today = LocalDateTime.now().withSecond(0).withNano(0);
//        qwExternalContactService.insertQwExternalContactByExternalUserId2("ou_5e8d3d9d3d9d3d9d3d9d3d9d3d9d3d9d"
//                ,"ZhangZhanYue",100L,"ww5a88c4f879f204c5","","");


        QwUser qwUser = qwUserMapper.selectQwUserByCorpIdAndUserId("ww5a88c4f879f204c5", "ZhangZhanYue");

        // 查询成员的欢迎语以及欢迎图片
        QwFriendWelcomeVO qwFriendWelcomeVO = qwFriendWelcomeMapper.selectQwFriendWelcomeByUserIdVO(18931L, "ww5a88c4f879f204c5");
        if (qwFriendWelcomeVO != null) {
            SendWelcomeMsgParam sendWelcomeMsgParam = new SendWelcomeMsgParam();

            ArrayList<String> msgParamList=new ArrayList<>();
            if (qwFriendWelcomeVO.getIsDayparting().equals("1")) {
                List<QwFriendWelcomeDayPart.Schedule> schedules = JSON.parseArray(qwFriendWelcomeVO.getDaypartingItemlist(), QwFriendWelcomeDayPart.Schedule.class);
                LocalTime now = LocalTime.now();
                Integer week = LocalDate.now().getDayOfWeek().getValue();
                boolean match = false;
                for (QwFriendWelcomeDayPart.Schedule schedule : schedules) {
                    if (schedule.getWeek().contains(week)) {
                        LocalTime start = LocalTime.parse(schedule.getStartTime());
                        LocalTime end = LocalTime.parse(schedule.getEndTime().equals("24:00") ? "23:59:59" : schedule.getEndTime());
                        if (!now.isBefore(start) && !now.isAfter(end)) {

                            TextMessage textMessage = new TextMessage();
                            textMessage.setContent(schedule.getWelcomeText());
                            sendWelcomeMsgParam.setText(textMessage);
                            msgParamList.add(schedule.getWelcomeText());
                            List<SendWelcomeMsgParam.Attachment> attachments = schedule.getAttachments();
                            List<SendWelcomeMsgParam.Attachment> attachmentsMatch = attachmentsTools(attachments, qwUser, "ww5a88c4f879f204c5", 18931L);
                            sendWelcomeMsgParam.setAttachments(attachmentsMatch);
                            attachmentsMatch.forEach(item->{
                                if (("link").equals(item.getMsgtype())) {
                                    msgParamList.add(item.getLink().getUrl());
                                }
                            });
                            match = true;
                            break; // 找到匹配项后退出整个for循环
                        }
                    }
                }
                // 如果没有找到匹配项
                if (!match) {
                    TextMessage textMessage = new TextMessage();
                    textMessage.setContent(qwFriendWelcomeVO.getWelcomeText());
                    sendWelcomeMsgParam.setText(textMessage);
                    msgParamList.add(qwFriendWelcomeVO.getWelcomeText());
                    List<SendWelcomeMsgParam.Attachment> attachmentsAll = JSON.parseArray(qwFriendWelcomeVO.getAttachments(), SendWelcomeMsgParam.Attachment.class);
                    List<SendWelcomeMsgParam.Attachment> attachmentsNotMach = attachmentsTools(attachmentsAll, qwUser, "ww5a88c4f879f204c5", 9114148L);
                    sendWelcomeMsgParam.setAttachments(attachmentsNotMach);
                    attachmentsNotMach.forEach(item->{
                        if (("link").equals(item.getMsgtype())) {
                            msgParamList.add(item.getLink().getUrl());
                        }
                    });
                }

            } else {
                // 不分时段
                TextMessage textMessage = new TextMessage();
                textMessage.setContent(qwFriendWelcomeVO.getWelcomeText());
                sendWelcomeMsgParam.setText(textMessage);
                msgParamList.add(qwFriendWelcomeVO.getWelcomeText());
                // 设置所有附件
                List<SendWelcomeMsgParam.Attachment> attachmentsAll = JSON.parseArray(qwFriendWelcomeVO.getAttachments(), SendWelcomeMsgParam.Attachment.class);
                //加短链
                List<SendWelcomeMsgParam.Attachment> attachments = attachmentsTools(attachmentsAll, qwUser, "ww5a88c4f879f204c5", 9114148L);
                sendWelcomeMsgParam.setAttachments(attachments);
                attachments.forEach(item->{
                    if (("link").equals(item.getMsgtype())) {
                        msgParamList.add(item.getLink().getUrl());
                    }
                });
            }

            QwResult qwResult = qwApiService.sendWelcomeMsg(sendWelcomeMsgParam, "ww5a88c4f879f204c5");
//                    if (qwResult.getErrcode()==41050||qwResult.getErrcode()==41051){
//                        if (qwUser.getAppKey()!=null&& !qwUser.getAppKey().equals("")){
//                            if (msgParamList!=null&&msgParamList.size()>0){
//                                for (String value : msgParamList) {
//                                    QwHookSendMsgParam sendMsgParam=new QwHookSendMsgParam();
//                                    QwHookSendMsgParam.QwHookSendMsgData sendMsgData=new QwHookSendMsgParam.QwHookSendMsgData();
//                                    sendMsgParam.setType(101003);
//                                    sendMsgData.setMsg(value);
//                                    sendMsgData.setOpenId(qwExternalContact.getExternalUserId());
//                                    sendMsgData.setSyncKey("1");
//                                    sendMsgParam.setData(sendMsgData);
//                                    SendHookAIParam sendAIParam = new SendHookAIParam();
//                                    sendAIParam.setCmd("aiReplyMsg");
//                                    sendAIParam.setData(JSONUtil.toJsonStr(sendMsgParam));
//                                    sendAIParam.setKey(qwUser.getAppKey());
//                                    logger.info("补欢迎语:" + qwExternalContact.getExternalUserId()+":"+value);
//                                    redisTemplate.opsForList().leftPush("AiMsg:"+qwUser.getAppKey(), JSON.toJSONString(sendAIParam));
//                                }
//                            }
//                        }
//                    }
        }
        return  R.ok().put("data",currentTime).put("today",today);
    }

    public List<SendWelcomeMsgParam.Attachment> attachmentsTools( List<SendWelcomeMsgParam.Attachment> attachments,
                                                                  QwUser qwUser,
                                                                  String corpId,
                                                                  Long qwExternalId){

        if (attachments == null || attachments.isEmpty()) {
            return attachments;
        }

        attachments.forEach(att -> {
            // 生成短链的条件判断
            if ("link".equals(att.getMsgtype())
                    && !StringUtil.strIsNullOrEmpty(att.getLink().getCourseId())
                    && !StringUtil.strIsNullOrEmpty(att.getLink().getVideoId())) {

                try {
                    FsCourseLinkCreateParam param = new FsCourseLinkCreateParam();
                    param.setVideoId(Long.valueOf(att.getLink().getVideoId()));
                    param.setQwUserId(String.valueOf(qwUser.getId()));
                    param.setDays(att.getLink().getExpiresDays());
                    param.setCorpId(corpId);
                    param.setCourseId(Long.valueOf(att.getLink().getCourseId()));
                    param.setCompanyUserId(qwUser.getCompanyUserId());
                    param.setCompanyId(qwUser.getCompanyId());
                    param.setQwExternalId(qwExternalId);
                    param.setSendTime(new Date());

                    // 调用服务生成短链
                    R linkUrl = iFsCourseLinkService.createLinkUrlWc(param);

                    if (linkUrl != null && linkUrl.get("url") != null) {
                        att.getLink().setUrl(linkUrl.get("url").toString());
                    }
                    //生成观看记录

                }  catch (Exception e) {

                    System.out.println("欢迎语生成短链失败:"+e);
                }
            }
            //小程序
            if("miniprogram".equals(att.getMsgtype())
                    && !StringUtil.strIsNullOrEmpty(att.getMiniprogram().getCourseId())
                    && !StringUtil.strIsNullOrEmpty(att.getMiniprogram().getVideoId())){

                try {

                    String mediaId =(String)redisCache.getCacheObject("miniprogram:"+corpId+":"+att.getMiniprogram().getCourseId());

                    if (!StringUtil.strIsNullOrEmpty(mediaId)){

                        FsCourseLinkCreateParam param = new FsCourseLinkCreateParam();
                        param.setVideoId(Long.valueOf(att.getMiniprogram().getVideoId()));
                        param.setQwUserId(String.valueOf(qwUser.getId()));
                        param.setDays(att.getMiniprogram().getExpiresDays());
                        param.setCorpId(corpId);
                        param.setCourseId(Long.valueOf(att.getMiniprogram().getCourseId()));
                        param.setCompanyUserId(qwUser.getCompanyUserId());
                        param.setCompanyId(qwUser.getCompanyId());
                        param.setQwExternalId(qwExternalId);
                        param.setSendTime(new Date());

                        String linkUrl = iFsCourseLinkService.createLinkUrlWcmini(param);

                        if (!StringUtil.strIsNullOrEmpty(linkUrl)) {
                            att.getMiniprogram().setPage(linkUrl);
                        }

                        att.getMiniprogram().setPic_media_id(mediaId);


                    }else {
                        System.out.println(("查到课程相关信息:"+corpId+":"+att.getMiniprogram().getCourseId()));
                    }

                }  catch (Exception e) {
                    System.out.println("欢迎语生成小程序消息失败:"+e.getMessage()+"|"+corpId+"|"+att.getMiniprogram().getCourseId());

                }
            }

        });

        return attachments;
    }
    @GetMapping("/key/{key}")
    public R test(@PathVariable String key) {
        Set<String> keys = webSocketServer.getSessionPools();
        for (String s : keys) {
            if (s.equals(key)){
                return R.ok("key在线");
            }
        }
        return  R.ok("不在线");
    }
    @Autowired
    private IQwUserService qwUserService;
    @Autowired
    QwCompanyMapper qwCompanyMapper;
//    @GetMapping("/ren/{key}")
//    public R ren(@PathVariable String key) {
//        QwUser user=qwUserService.selectQwUserByQwHookId("1688857885596589");
//
//                QwCompany qwCompany = qwCompanyMapper.selectQwCompanyByCorpId(user.getCorpId());
//            QwSendMsgParam qwSendMsgParam = new QwSendMsgParam();
//
//            qwSendMsgParam.setAgentid(Integer.parseInt(qwCompany.getServerAgentId().trim()));
//            qwSendMsgParam.setTouser(user.getQwUserId());
//            QwSendMsgParam.Text text = new QwSendMsgParam.Text();
//            text.setContent("您的客户:"+"xxxx"+" 需要转人工,请及时回复");
//            qwSendMsgParam.setText(text);
//            qwSendMsgParam.setMsgtype("text");
//            QwSendMsgResult qwSendMsgResult1 = qwApiService.sendMsg(qwSendMsgParam, qwCompany.getCorpId());
//            System.out.println(qwSendMsgResult1);
//
//        QwSendMsgParam qwSendMsgParam2 = new QwSendMsgParam();
//        qwSendMsgParam2.setAgentid(Integer.parseInt(qwCompany.getServerAgentId().trim()));
//        qwSendMsgParam2.setTouser(user.getQwUserId());
//        QwSendMsgParam.Text text2 = new QwSendMsgParam.Text();
//        text2.setContent("xxxxx1");
//        qwSendMsgParam2.setText(text2);
//        qwSendMsgParam2.setMsgtype("text");
//        QwSendMsgResult qwSendMsgResult = qwApiService.sendMsg(qwSendMsgParam2, qwCompany.getCorpId());
//        System.out.println(qwSendMsgResult);
//
//        return  R.ok("不在线");
//    }

    @Autowired
    WebSocketServer webSocketServer;


    public  void addWebSocket(String s){
        int i=0;
        while (i<100){
            System.out.println(i);
            QwHookSendMsgParam sendMsgParam=new QwHookSendMsgParam();
            QwHookSendMsgParam.QwHookSendMsgData sendMsgData=new QwHookSendMsgParam.QwHookSendMsgData();
            sendMsgParam.setType(101003);
            sendMsgData.setMsg(i+"测试");
            sendMsgData.setOpenId("wmotXidAAAFN0SqV0Zd1vDI8OOCAmaVQ");
            sendMsgData.setSyncKey("1");
            sendMsgParam.setData(sendMsgData);
            SendAIParam sendAIParam = new SendAIParam();
            sendAIParam.setCmd("aiReplyMsg");
            sendAIParam.setData(JSONUtil.toJsonStr(sendMsgParam));
            sendAIParam.setKey("zx");
            redisTemplate.opsForList().leftPush("AiMsg:"+"zx", JSON.toJSONString(sendAIParam));

            i++;
        }
    }
}
