package com.fs.qw.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.BeanCopyUtils;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.course.domain.FsCourseWatchLog;
import com.fs.course.mapper.FsCourseWatchLogMapper;
import com.fs.course.param.FsCourseLinkCreateParam;
import com.fs.course.service.IFsCourseLinkService;
import com.fs.qw.domain.*;
import com.fs.qw.mapper.QwContactWayLogsMapper;
import com.fs.qw.mapper.QwContactWayMapper;
import com.fs.qw.mapper.QwContactWayUserMapper;
import com.fs.qw.param.QwStatisticsParam;
import com.fs.qw.param.QwUpdateContactWayParam;
import com.fs.qw.service.IQwContactWayService;
import com.fs.qw.vo.QwWayStatisticsListVO;
import com.fs.qw.vo.QwWelcomeJsonFrom;
import com.fs.qwApi.Result.*;
import com.fs.qwApi.domain.QwResult;
import com.fs.qwApi.domain.inner.TextMessage;
import com.fs.qwApi.param.QwAddContactWayParam;
import com.fs.qwApi.param.QwGetContactWayParam;
import com.fs.qwApi.param.QwListContactWayParam;
import com.fs.qwApi.param.SendWelcomeMsgParam;
import com.fs.qwApi.service.QwApiService;
import com.fs.voice.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 企微活码Service业务层处理
 *
 * @author fs
 * @date 2024-07-05
 */
@Service
public class QwContactWayServiceImpl implements IQwContactWayService
{
    private static final Logger log = LoggerFactory.getLogger(QwContactWayServiceImpl.class);
    @Autowired
    private QwContactWayMapper qwContactWayMapper;

    @Autowired
    private QwApiService qwApiService;
    @Autowired
    private QwContactWayUserMapper qwContactWayUserMapper;

    @Autowired
    private IFsCourseLinkService iFsCourseLinkService;

    @Autowired
    private FsCourseWatchLogMapper  watchLogMapper;
    /**
     * 查询企微活码
     *
     * @param id 企微活码主键
     * @return 企微活码
     */
    @Override
    public QwContactWay selectQwContactWayById(Long id)
    {
        return qwContactWayMapper.selectQwContactWayById(id);
    }

    /**
     * 查询企微活码列表
     *
     * @param qwContactWay 企微活码
     * @return 企微活码
     */
    @Override
    public List<QwContactWay> selectQwContactWayList(QwContactWay qwContactWay)
    {
        List<QwContactWay> qwContactWays = qwContactWayMapper.selectQwContactWayList(qwContactWay);
        return qwContactWays;
    }

    /**
     * 新增企微活码
     *
     * @param qwContactWay 企微活码
     * @return 结果
     */
    @Transactional
    @Override
    public R insertQwContactWay(QwContactWay qwContactWay)
    {
        QwAddContactWayParam qwAddContactWayParam = new QwAddContactWayParam();
        List<String> users = JSON.parseArray(qwContactWay.getUserIds(), String.class);
        int type=2;
        String corpId = qwContactWay.getCorpId();
        log.info("新增企微活码corpId"+corpId);
        qwContactWay.setType(type);
        qwContactWay.setCreateTime(DateUtils.getNowDate());
        qwContactWayMapper.insertQwContactWay(qwContactWay);
        Long id = qwContactWay.getId();
        qwAddContactWayParam.setType(type);

        qwAddContactWayParam.setScene(2);
        qwAddContactWayParam.setState("way:"+corpId+":"+id);

        qwAddContactWayParam.setRemark(qwContactWay.getRemark());
        qwAddContactWayParam.setUser(users);
        qwAddContactWayParam.setSkip_verify(qwContactWay.getSkipVerify()==1?true:false);
        QwAddContactWayResult qwAddContactWayResult = qwApiService.addContactWay(qwAddContactWayParam, qwContactWay.getCorpId());
        System.out.println("qwAddContactWayResult:"+qwAddContactWayResult);
        if (qwAddContactWayResult.getErrcode()==0){
            if (qwContactWay.getIsWelcome()!=null&&qwContactWay.getIsWelcome()==1){
                if (qwContactWay.getImagePicUrl()!=null&&qwContactWay.getImagePicUrl()!=""){
                    try {
                        QwUploadImgResult uploadimg = qwApiService.uploadimgs(qwContactWay.getImagePicUrl(), qwContactWay.getCorpId());
                        if (uploadimg.getErrcode()==0){
                            qwContactWay.setImagePicUrl(uploadimg.getUrl());
                        }else {
                            return  R.error("上传活码图片失败:"+uploadimg.getErrMsg());
                        }

                    } catch (Exception e) {
                        return  R.error("上传活码图片出错:"+e);
                    }
                }
            }
            if (qwContactWay.getUserType()==1&&qwContactWay.getIsUserLimit()==1){
                String userLimitJson = qwContactWay.getUserLimitJson();
                List<QwContactWayUser> qwContactWayUsers = JSON.parseArray(userLimitJson, QwContactWayUser.class);
                for (QwContactWayUser qwContactWayUser : qwContactWayUsers) {
                    qwContactWayUser.setDayCount(qwContactWayUser.getLimitCount());
                    qwContactWayUser.setWayId(qwContactWay.getId());
                    qwContactWayUser.setCompanyId(qwContactWay.getCompanyId());
                    qwContactWayUserMapper.insertQwContactWayUser(qwContactWayUser);
                }
            }
            qwContactWay.setState("way:"+corpId+":"+id);
            qwContactWay.setConfigId(qwAddContactWayResult.getConfig_id());
            qwContactWay.setQrCode(qwAddContactWayResult.getQr_code());
            qwContactWayMapper.updateQwContactWay(qwContactWay);

        }else {
            throw new CustomException(qwAddContactWayResult.getErrmsg());
        }


        return R.ok();
    }

    /**
     * 修改企微活码
     *
     * @param qwContactWay 企微活码
     * @return 结果
     */
    @Override
    public R updateQwContactWay(QwContactWay qwContactWay)
    {
        List<String> users = JSON.parseArray(qwContactWay.getUserIds(), String.class);
        if (qwContactWay.getType()==1&&users.size()>1){
            return  R.error("单人连接不可添加多人");
        }
        QwUpdateContactWayParam qwUpdateContactWayParam = new QwUpdateContactWayParam();
        qwUpdateContactWayParam.setConfig_id(qwContactWay.getConfigId());
        qwUpdateContactWayParam.setUser(users);
        qwUpdateContactWayParam.setState("way:"+qwContactWay.getCompanyId()+":"+qwContactWay.getId());
        qwUpdateContactWayParam.setRemark(qwContactWay.getRemark());
        qwUpdateContactWayParam.setSkip_verify(qwContactWay.getSkipVerify()==1?true:false);
        if (qwContactWay.getIsWelcome()!=null&&qwContactWay.getIsWelcome()==1){
            if (qwContactWay.getImagePicUrl()!=null&&qwContactWay.getImagePicUrl()!=""){
                try {
                    QwUploadImgResult uploadimg = qwApiService.uploadimgs(qwContactWay.getImagePicUrl(), qwContactWay.getCorpId());
                    if (uploadimg.getErrcode()==0){
                        qwContactWay.setImagePicUrl(uploadimg.getUrl());
                    }else {
                        return  R.error("修改活码图片image失败:"+uploadimg.getErrMsg());
                    }


                } catch (Exception e) {
                    return  R.error("修改活码图片image出错:"+e);
                }
            }
        }

        if (qwContactWay.getIsSpanWelcome()!=null&&qwContactWay.getIsSpanWelcome()==1){
            boolean b=false;
            String welcomeJson = qwContactWay.getWelcomeJson();
            List<QwWelcomeJsonFrom> qwWelcomeJsonFroms = JSON.parseArray(welcomeJson, QwWelcomeJsonFrom.class);
            for (QwWelcomeJsonFrom qwWelcomeJsonFrom : qwWelcomeJsonFroms) {

                if (qwWelcomeJsonFrom.getAttachments() != null&& !qwWelcomeJsonFrom.getAttachments().isEmpty()) {
                    List<QwWelcomeJsonFrom.Attachment> attachments = qwWelcomeJsonFrom.getAttachments();
                    for (QwWelcomeJsonFrom.Attachment attachment : attachments) {
                        QwWelcomeJsonFrom.Attachment.ImageAttachment image = attachment.getImage();
                        QwWelcomeJsonFrom.Attachment.LinkAttachment link = attachment.getLink();
                        if (image!=null&&image.getPic_url()!=null&&image.getPic_url()!=""&&!image.getPic_url().contains("https://wework.qpic.cn")){
                            try {
                                QwUploadImgResult uploadimg = qwApiService.uploadimgs(image.getPic_url(), qwContactWay.getCorpId());
                                if (uploadimg.getErrcode()==0){
                                    attachment.getImage().setPic_url(uploadimg.getUrl());
                                }else {
                                    return  R.error("修改活码分时段图片image失败:"+uploadimg.getErrMsg());
                                }
                                b=true;
                            } catch (Exception e) {
                                return  R.error("修改活码分时段图片image出错:"+e);
                            }
                        }
                        if (link!=null&&link.getPicurl()!=null&&link.getPicurl()!=""&&!link.getPicurl().contains("https://wework.qpic.cn")){
                            try {
                                QwUploadImgResult uploadimg = qwApiService.uploadimgs(link.getPicurl(), qwContactWay.getCorpId());
                                if (uploadimg.getErrcode()==0){
                                    attachment.getLink().setPicurl(uploadimg.getUrl());
                                }else {
                                    return  R.error("修改活码分时段图片link失败:"+uploadimg.getErrMsg());

                                }
                                b=true;
                            } catch (Exception e) {
                                return  R.error("修改活码分时段图片link出错:"+e);
                            }
                        }
                    }
                }

                if (qwContactWay.getImagePicUrl()!=null&&qwContactWay.getImagePicUrl()!="") {
                    try {
                        QwUploadImgResult uploadimg = qwApiService.uploadimgs(qwContactWay.getImagePicUrl(), qwContactWay.getCorpId());
                        if (uploadimg.getErrcode() == 0) {
                            qwContactWay.setImagePicUrl(uploadimg.getUrl());

                        } else {
                            return R.error("修改活码分时段图片image失败2:" + uploadimg.getErrMsg());

                        }
                    } catch (Exception e) {
                        return R.error("修改活码分时段图片image出错2:" + e);
                    }
                }
            }
            if (b){
                qwContactWay.setWelcomeJson(JSON.toJSONString(qwWelcomeJsonFroms));
            }
        }

        QwResult qwResult = qwApiService.updateContactWay(qwUpdateContactWayParam, qwContactWay.getCorpId());
        if (qwResult.getErrcode()==0){
            qwContactWayMapper.updateQwContactWay(qwContactWay);
            if (qwContactWay.getUserType()==1&&qwContactWay.getIsUserLimit()==1){
                String userLimitJson = qwContactWay.getUserLimitJson();
                List<QwContactWayUser> qwContactWayUsers = JSON.parseArray(userLimitJson, QwContactWayUser.class);
                qwContactWayUserMapper.deleteQwContactWayUserByWayId(qwContactWay.getId());
                for (QwContactWayUser qwContactWayUser : qwContactWayUsers) {
                    qwContactWayUser.setDayCount(qwContactWayUser.getLimitCount());
                    qwContactWayUser.setWayId(qwContactWay.getId());
                    qwContactWayUser.setCompanyId(qwContactWay.getCompanyId());
                    qwContactWayUserMapper.insertQwContactWayUser(qwContactWayUser);
                }
            }


        }else {
            return  R.error(qwResult.getErrmsg());
        }

        return R.ok();
    }

    /**
     * 批量删除企微活码
     *
     * @param ids 需要删除的企微活码主键
     * @return 结果
     */
    @Override
    public R deleteQwContactWayByIds(Long[] ids)
    {
        for (Long id : ids) {
            QwContactWay qwContactWay1 = qwContactWayMapper.selectQwContactWayById(id);
            QwGetContactWayParam qwGetContactWayParam = new QwGetContactWayParam();
            qwGetContactWayParam.setConfig_id(qwContactWay1.getConfigId());
            QwResult qwResult = qwApiService.delContactWay(qwGetContactWayParam, qwContactWay1.getCorpId());

            if (qwResult.getErrcode()==0){
                QwContactWay qwContactWay = new QwContactWay();
                qwContactWay.setId(id);
                qwContactWay.setIsDel(2);
                qwContactWayMapper.updateQwContactWay(qwContactWay);
            }

        }
        return R.ok();
    }

    /**
     * 删除企微活码信息
     *
     * @param id 企微活码主键
     * @return 结果
     */
    @Override
    public int deleteQwContactWayById(Long id)
    {
        return qwContactWayMapper.deleteQwContactWayById(id);
    }

    @Override
    public R selectQwContactWaysync(String corpId) {
        QwListContactWayParam qwListContactWayParam = new QwListContactWayParam();
        qwListContactWayParam.setStart_time("1622476800");
        QwListContactWayReslut qwListContactWayReslut = qwApiService.listContactWay(qwListContactWayParam, corpId);
        List<QwGetContactWayParam> contactWay = qwListContactWayReslut.getContact_way();
        for (QwGetContactWayParam qwGetContactWayParam : contactWay) {
            String configId = qwGetContactWayParam.getConfig_id();
            QwContactWay qwContactWay = qwContactWayMapper.selectQwContactWayByConfigIdAndCompanyId(configId, corpId);
            if (qwContactWay==null){
                QwGetContactWayParam wayParam = new QwGetContactWayParam();
                wayParam.setConfig_id(configId);
                QwGetContactWayResult way = qwApiService.getContactWay(wayParam, corpId);
                System.out.println("way:"+way);
                if (way.getErrCode()==0) {
                    QwContactWayResult w = way.getContactWay();
                    QwContactWay qw = new QwContactWay();
                    qw.setConfigId(configId);
                    qw.setType(w.getType());
                    qw.setQrCode(w.getQr_code());
                    qw.setCreateTime(new Date());
                    qw.setUserIds(JSON.toJSONString(w.getUser()));
                    qw.setState(w.getState());
                    qw.setCorpId(corpId);
                    qw.setSkipVerify(w.isSkip_verify()?1:0);
                    qwContactWayMapper.insertQwContactWay(qw);
                }

            }
        }
        return R.ok();
    }

    @Override
    public void updateQwContactWayBYLimit(Long wayId) {
        QwContactWay qwContactWay = qwContactWayMapper.selectQwContactWayById(wayId);
        List<QwContactWayUser> qwContactWayUsers = qwContactWayUserMapper.selectQwContactWayUserByWayIdAndCount(wayId);
        List<String> users = new ArrayList<>();
        if (!qwContactWayUsers.isEmpty()) {
            for (QwContactWayUser qwContactWayUser : qwContactWayUsers) {
                users.add(qwContactWayUser.getUserId());
            }
        }else {
            users=JSON.parseArray(qwContactWay.getSpareUserIds(), String.class);
        }
        if (!users.isEmpty()) {
            QwUpdateContactWayParam qwUpdateContactWayParam = new QwUpdateContactWayParam();
            qwUpdateContactWayParam.setConfig_id(qwContactWay.getConfigId());
            qwUpdateContactWayParam.setUser(users);
            QwResult qwResult = qwApiService.updateContactWay(qwUpdateContactWayParam, qwContactWay.getCorpId());

        }

    }

    @Override
    public boolean sendWelcomeMsg(QwContactWay qwContactWay, String corpId, String welcomeCode,QwUser qwUser,Long qwExternalId) {


        if (qwContactWay.getIsSpanWelcome()==1){
            String welcomeJson = qwContactWay.getWelcomeJson();
            if (welcomeJson!=null&&welcomeJson!=""){
                LocalTime now = LocalTime.now();
                // 获取当前是周几
                Integer week = LocalDate.now().getDayOfWeek().getValue();

                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
                List<QwWelcomeJsonFrom> qwWelcomeJsonFroms = JSON.parseArray(welcomeJson, QwWelcomeJsonFrom.class);
                for (QwWelcomeJsonFrom qwWelcomeJsonFrom : qwWelcomeJsonFroms) {
                    if (qwWelcomeJsonFrom.getWeek().contains(week)){
                        // 解析为LocalTime对象
                        LocalTime startTime = LocalTime.parse(qwWelcomeJsonFrom.getStartTime(), formatter);
                        LocalTime endTime = LocalTime.parse(qwWelcomeJsonFrom.getEndTime(), formatter);
                        if (!now.isBefore(startTime) && !now.isAfter(endTime)) {

                            qwWelcomeJsonFrom.setAttachments(attachmentsTools(qwWelcomeJsonFrom.getAttachments(), qwUser, corpId, qwExternalId));

                            SendWelcomeMsgParam copy = BeanCopyUtils.copy(qwWelcomeJsonFrom, SendWelcomeMsgParam.class);
                            copy.setWelcome_code(welcomeCode);

                            QwResult qwResult = qwApiService.sendWelcomeMsg(copy, corpId);

                            if (qwResult.getErrcode()==0){
                                return false;
                            }else {
                                return true;
                            }

                        }
                    }
                }
            }


        }
        SendWelcomeMsgParam sendWelcomeMsgParam = new SendWelcomeMsgParam();
        sendWelcomeMsgParam.setWelcome_code(welcomeCode);
        TextMessage textMessage = new TextMessage();
        textMessage.setContent(qwContactWay.getTextContent());
        sendWelcomeMsgParam.setText(textMessage);
        SendWelcomeMsgParam.Attachment attachment = new SendWelcomeMsgParam.Attachment();
        SendWelcomeMsgParam.Attachment.ImageAttachment imageAttachment = new SendWelcomeMsgParam.Attachment.ImageAttachment();
        imageAttachment.setPic_url(qwContactWay.getImagePicUrl());
        attachment.setMsgtype("image");
        attachment.setImage(imageAttachment);
        sendWelcomeMsgParam.setAttachments(Arrays.asList(attachment));
        QwResult qwResult = qwApiService.sendWelcomeMsg(sendWelcomeMsgParam, corpId);
        if (qwResult.getErrcode()==0){
            return false;
        }else {
            return true;
        }
    }

    public List<QwWelcomeJsonFrom.Attachment> attachmentsTools( List<QwWelcomeJsonFrom.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());
                    }

                    //生成观看记录
                    addWatchLogIfNeeded(Integer.valueOf(att.getLink().getVideoId()),
                                        Integer.valueOf(att.getLink().getCourseId()),
                                        String.valueOf(qwUser.getId()),
                                        String.valueOf(qwUser.getCompanyUserId()),
                                        String.valueOf(qwUser.getCompanyId()),
                                        String.valueOf(qwExternalId));
                }  catch (Exception e) {
                    log.error("欢迎语生成短链失败:", e);
                }
            }
        });

        return attachments;
    }

    //添加watchLog记录
    public   void addWatchLogIfNeeded(Integer videoId, Integer courseId,
                                     String qwUserId, String companyUserId,
                                     String companyId, String externalId) {
        FsCourseWatchLog watchLog = new FsCourseWatchLog();
        watchLog.setVideoId(videoId != null ? videoId.longValue() : null);
        watchLog.setQwExternalContactId(externalId != null ? Long.valueOf(externalId) : null);
        watchLog.setSendType(2);
        watchLog.setQwUserId(qwUserId);
        watchLog.setSopId(null);
        watchLog.setCourseId(courseId != null ? courseId.longValue() : null);
        watchLog.setCompanyUserId(companyUserId != null ? Long.valueOf(companyUserId) : null);
        watchLog.setCompanyId(companyId != null ? Long.valueOf(companyId) : null);
        watchLog.setCreateTime(new Date());
        watchLog.setUpdateTime(new Date());
        watchLog.setLogType(3);
        watchLog.setUserId(0L);
        watchLogMapper.insertOrUpdateFsCourseWatchLog(watchLog);
    }

    @Override
    public List<QwWayStatisticsListVO> QwWayStatisticsListVO(QwStatisticsParam param) {
        return qwContactWayMapper.QwWayStatisticsListVO(param);
    }

    @Override
    public List<JSONObject> selectQwWayStatisticsCounts(Map<String, Object> map) {
        return qwContactWayMapper.selectQwWayStatisticsCounts(map);
    }
    @Autowired
    QwContactWayLogsMapper qwContactWayLogsMapper;
    @Override
    public void updateQwContactWayByLoss(QwExternalContact qwExternalContact) {

        QwContactWay qwContactWay = qwContactWayMapper.selectQwContactWayById(qwExternalContact.getWayId());
        if (qwContactWay!=null){
            qwContactWay.setDeleteNum(qwContactWay.getDeleteNum()+1);
            qwContactWay.setNum(qwContactWay.getNum()-1);
            qwContactWayMapper.updateQwContactWay(qwContactWay);
            QwContactWayLogs qwContactWayLogs = new QwContactWayLogs();
            qwContactWayLogs.setCreateTime(new Date());
            qwContactWayLogs.setType(2);
            qwContactWayLogs.setWayId(qwContactWay.getId());
            qwContactWayLogs.setExternalUserId(qwExternalContact.getId());
            qwContactWayLogs.setUserId(qwExternalContact.getQwUserId());
            qwContactWayLogs.setCompanyId(qwExternalContact.getCompanyId());
            qwContactWayLogs.setMsg("客户流失");
            qwContactWayLogsMapper.insertQwContactWayLogs(qwContactWayLogs);

        }
    }
}
