package com.face.attachment.controller;


import com.face.attachment.entity.FaceWeixin;
import com.face.attachment.mapper.FaceWeixinMapper;
import com.face.attachment.service.IFaceInfoService;
import com.face.attachment.vo.FaceInfoDetailResponseVO;
import com.face.attachment.vo.FaceInfoTxRequestVO;
import com.face.global.controller.ManageBaseController;
import com.face.global.vo.ApiResult;
import com.face.util.ApiResultBuilder;
import com.face.weixin.WXProperties;
import com.face.weixin.WeiXinRemoteService;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.facefusion.v20220927.FacefusionClient;
import com.tencentcloudapi.facefusion.v20220927.models.FuseFaceRequest;
import com.tencentcloudapi.facefusion.v20220927.models.FuseFaceResponse;
import com.tencentcloudapi.facefusion.v20220927.models.MergeInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/face/weixin")
@Slf4j
@Tag(name = "微信信息管理")
public class WeiXinManagerController extends ManageBaseController {

    @Autowired
    WeiXinRemoteService weiXinRemoteService;

    @Autowired
    protected WXProperties wxProperties;

    @Autowired
    protected FaceWeixinMapper faceWeixinMapper;

    /**
     * 获取配置信息
     *
     * @param url 当前网页的url
     * @return wx.config需要的配置参数
     */
    @GetMapping("/config")
    @ResponseBody
    public Map<String, Object> config(String url) {
        FaceWeixin oldfaceWeixin = faceWeixinMapper.selectById(wxProperties.getAppId());
        Long nowTime =System.currentTimeMillis() / 1000;
        Long hisTime= null!=oldfaceWeixin ? Long.parseLong(oldfaceWeixin.getNowTimestamp()): nowTime;

        if(null== oldfaceWeixin  ){
            FaceWeixin faceWeixin =new FaceWeixin();
            HashMap<String,Object> map =getJsDk (url);
            faceWeixin.setAppId(wxProperties.getAppId());
            faceWeixin.setNonceStr((String) map.get("nonceStr"));
            faceWeixin.setNowSignature((String) map.get("signature"));
            faceWeixin.setNowTimestamp((String) map.get("timestamp"));
            faceWeixinMapper.insert(faceWeixin);
            return map;
        }else if(((nowTime-hisTime) >6000)){
            //已经100分钟了
            HashMap<String,Object> map =getJsDk (url);
            //faceWeixin.setAppId(wxProperties.getAppId());
            oldfaceWeixin.setNonceStr((String) map.get("nonceStr"));
            oldfaceWeixin.setNowSignature((String) map.get("signature"));
            oldfaceWeixin.setNowTimestamp((String) map.get("timestamp"));
            faceWeixinMapper.updateById(oldfaceWeixin);
            return map;
        }else{
            return new HashMap<>() {{
                put("appId", wxProperties.getAppId());
                put("timestamp", oldfaceWeixin.getNowTimestamp());
                put("nonceStr", oldfaceWeixin.getNonceStr());
                put("signature", oldfaceWeixin.getNowSignature());
            }};
        }
    }


    private HashMap<String,Object> getJsDk(String url){
        // 拿到token
        String accessToken = weiXinRemoteService.getOfficialAccessToken().getAccess_token();
        // 拿到ticket
        String ticket = weiXinRemoteService.getTicket(accessToken).getTicket();
        // 生成时间戳
        String timestamp = System.currentTimeMillis() / 1000 + "";
        // 生成随机字符串
        String nonceStr = UUID.randomUUID().toString().replace("-", "");
        // 进行签名
        String signature = this.getSignature(ticket, nonceStr, timestamp, url);

        return new HashMap<>() {{
            put("appId", wxProperties.getAppId());
            put("timestamp", timestamp);
            put("nonceStr", nonceStr);
            put("signature", signature);
        }};
    }

    /**
     * 获取签名
     *
     * @param ticket 刚刚获取的ticket
     * @param nonceStr 随机字符串
     * @param timestamp 以秒为单位的时间戳
     * @param url 当前网页的URL，不包含#及其后面部分
     * @return 签名
     */
    private String getSignature(String ticket, String nonceStr, String timestamp, String url) {
        String concat = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url;
        return DigestUtils.sha1Hex(concat);
    }



}
