package com.repair.common.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.repair.config.WxOpenidConfig;
import com.repair.model.pojo.WxAccessToken;
import com.repair.model.result.CommonResult;
import com.repair.services.WxAccessTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: binguo
 * @Date: 2023/8/1 星期二 8:50
 * @Description: com.repair.common.utils
 * @Version: 1.0
 */
@Component
public class WeiXiaoUtil {
    @Autowired
    private WxOpenidConfig wxOpenidConfig;
    @Autowired
    private WxAccessTokenService wxAccessTokenService;

    /**
     * 获取token
     * @return
     */
    public String getApplicationToken() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, 1);
        String dateNow = sdf.format(nowTime.getTime());
        System.out.println();
        WxAccessToken aData = wxAccessTokenService.getRepairByDate(dateNow);
        if(aData != null){
            return aData.getAccessToken();
        }

        Map<String, Object> jsonMap = doGetApplicationToken();
        String accessToken = jsonMap.get("access_token").toString();
        String expiresIn = jsonMap.get("expires_in").toString();
        System.out.println("accessToken："+accessToken+"；expires_in："+expiresIn);

        aData = new WxAccessToken();
        aData.setAccessToken(accessToken);
        Calendar newTime = Calendar.getInstance();
        newTime.add(Calendar.SECOND, Integer.valueOf(expiresIn));
        aData.setExpiresTime(newTime.getTime());

        wxAccessTokenService.insertwxAccessToken(aData);
        return accessToken;
    }

    /**
     * 发送通知
     * @param cards 卡号集合
     * @param digest 摘要
     * @param title 通知标题
     * @param content 通知内容
     * @param customs 自定义参数，长度为2，分别为提示文案和通知跳转链接
     */
    public CommonResult sendNotice(List<String> cards, String digest, String title, String content, List<String> customs) {
        String uri = "https://open.wecard.qq.com/cgi-bin/notice/send?access_token="+ getApplicationToken();
        Map<String, String> params = new HashMap<>();

        try {
            ObjectMapper mapper = new ObjectMapper();
            params.put("cards", mapper.writeValueAsString(cards));
            params.put("title", title);
            params.put("content", content);
            params.put("sender", "报修系统");
            params.put("digest", digest);
            if (customs != null && customs.size() == 2) {
                params.put("customs", mapper.writeValueAsString(customs));
            }

            RestTemplate client = new RestTemplate();
            ResponseEntity<String> tokenResponse = client.postForEntity(uri, params, String.class);
            String body = tokenResponse.getBody();
            //log.info("微校发送通知返回结果【{}】", body);
            System.out.println("微校发送通知返回结果："+body);
            return CommonResult.ok("操作成功");
        } catch (Exception e) {
            System.out.println("微校发送通知错误："+e.getMessage());
            //log.error("微校发送通知错误【{}】", e.getMessage());
            return CommonResult.fail("操作失败");
        }
    }

    /**
     * 获取token
     * @return
     */
    private Map<String, Object> doGetApplicationToken() {
        String uri = "https://open.wecard.qq.com/cgi-bin/oauth2/token";

        // 构建请求参数
        Map<String, String> tokenParams = new HashMap<>();
        tokenParams.put("app_key", wxOpenidConfig.getAppid());
        tokenParams.put("app_secret", wxOpenidConfig.getAppkey());
        tokenParams.put("grant_type", "client_credentials");
        tokenParams.put("scope", "base");
        tokenParams.put("ocode", wxOpenidConfig.getOcode());

        try {
            RestTemplate client = new RestTemplate();
            ResponseEntity<String> tokenResponse = client.postForEntity(uri, tokenParams, String.class);
            String body = tokenResponse.getBody();
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> jsonMap = mapper.readValue(body, new TypeReference<Map<String, Object>>() {});


            return jsonMap;
        } catch (Exception e) {
            String sss = e.getMessage();
        }
        return null;
    }
}
