package com.usky.system.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.redis.core.RedisHelper;
import com.usky.system.domain.MceMbuser;
import com.usky.system.mapper.MceMbuserMapper;
import com.usky.system.service.ISysDictDataService;
import com.usky.system.service.MceMbuserService;
import com.usky.system.constant.constant;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.system.service.vo.SendWeChatMessageRequestVO;
import com.usky.system.service.vo.TemplateData;
import com.usky.system.service.vo.TemplateMsgEntityVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 消息中心_移动端注册表 服务实现类
 * </p>
 *
 * @author han
 * @since 2024-05-06
 */
@Service
@Slf4j
public class MceMbuserServiceImpl extends AbstractCrudService<MceMbuserMapper, MceMbuser> implements MceMbuserService {

    @Autowired
    private RedisHelper redisHelper;

    public String getWeChatAccessToken() {
        try {
            // 微信公众号官方获取AccessToken
            RestTemplate restTemplate = new RestTemplate();
            String requestParams = String.format(constant.WE_CHAT_ACCESS_TOKEN_URL, constant.WE_CHAT_APP_ID, constant.WE_CHAT_SECRET);
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(requestParams, String.class);

            String accessToken = JSONObject.parseObject(responseEntity.getBody()).getString("access_token");
            log.info("we_chat_access_token: " + accessToken);

            return accessToken;
        } catch (Exception e) {
            log.info("异常信息:{}", e);
        }
        return null;
    }

    public static long getTimeDifference(String oldTime,String newTime) throws ParseException {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long NTime =df.parse(newTime).getTime();
        //从对象中拿到时间
        long OTime = df.parse(oldTime).getTime();
        long diff=(NTime-OTime)/1000/60;
        return diff;
    }

    @Override
    public JSONObject sendWeChatMessage(@RequestBody SendWeChatMessageRequestVO requestVO) {

        String infoTitle = requestVO.getInfoTitle();
        String infoContent = requestVO.getInfoContent();
        Integer infoId = requestVO.getInfoId();
        String openId = requestVO.getOpenId();

        //access_token时效校验，判断获取access_token获取时间是否超过有效时间，超过就调用更新，保证一直有效
        if(!redisHelper.hasKey("access_key")){
            redisHelper.set("access_time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            redisHelper.set("access_key",this.getWeChatAccessToken());
        }else{
            try{
                String access_time = redisHelper.get("access_time").toString();
                String now_time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                long i = getTimeDifference(access_time,now_time);
                if(i > 115){ //大于115分钟
                    redisHelper.set("access_time",LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    redisHelper.set("access_key",this.getWeChatAccessToken());
                }
            }catch (Exception e){
                throw new BusinessException(e.getMessage());
            }

        }

        Object obj = redisHelper.get("access_key");
        if(obj == null){
            throw new BusinessException("token不能为空");
        }

        String token = obj.toString();

        TemplateMsgEntityVO messageVo=new TemplateMsgEntityVO();
        messageVo.setTTitle(infoTitle);
        messageVo.setTKeyword1(infoContent);
        messageVo.setTKeyword3(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        messageVo.setTRemark(infoContent);
        if(Objects.nonNull(requestVO.getInfoTypeName())){
            messageVo.setTUrl(String.format(constant.WE_CHAT_CUSTOMER_CALL_URL,requestVO.getInfoType(),requestVO.getInfoTypeName(),infoId));
            messageVo.setTKeyword2(requestVO.getInfoTypeName());
        }else{
            messageVo.setTUrl(String.format(constant.WE_CHAT_CUSTOMER_CALL_URL1,requestVO.getInfoType(),infoId));
            messageVo.setTKeyword2("");
        }

        messageVo.setTemplateId(constant.WE_CHAT_TEMPLATE_ID);

        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="  + token;
        Map<String,Object> content=new HashMap<>();
        Map<String, TemplateData> data = new HashMap<>();
        data.put("first",new TemplateData(messageVo.getTTitle(),"#44b549"));
        data.put("keyword1",new TemplateData(messageVo.getTKeyword1(),"#173177"));
        data.put("keyword2",new TemplateData(messageVo.getTKeyword2(),"#173177"));
        data.put("keyword3",new TemplateData(messageVo.getTKeyword3(),"#173177"));
        data.put("remark",new TemplateData(messageVo.getTRemark(),"#173177"));

        content.put("touser",openId);
        content.put("url",messageVo.getTUrl());
        content.put("template_id",messageVo.getTemplateId());
        content.put("data",data);
        String resp = HttpUtil.post(requestUrl, JSONUtil.parseObj(content).toString());
        System.out.println(content.toString());
        System.out.println(JSONUtil.parseObj(content));
        JSONObject result = JSONObject.parseObject(resp);
        System.out.println("发送消息:" + resp);
        return result;
    }
}
