package com.ningdatech.carapi.irs.service.impl;

import java.security.MessageDigest;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ningdatech.basic.exception.BizException;
import com.ningdatech.basic.function.VUtils;
import com.ningdatech.cache.model.cache.CacheKey;
import com.ningdatech.cache.repository.CachePlusOps;
import com.ningdatech.carapi.common.util.CodeUtil;
import com.ningdatech.carapi.irs.constant.SmsConstant;
import com.ningdatech.carapi.irs.service.SmsService;
import com.ningdatech.carapi.open.model.dto.UserLoginDTO;
import com.ningdatech.carapi.sys.contants.UserLoginConstant;
import com.ningdatech.carapi.user.entity.NdUserAuth;
import com.ningdatech.carapi.user.entity.NdUserInfo;
import com.ningdatech.carapi.user.service.INdUserAuthService;
import com.ningdatech.carapi.user.service.INdUserInfoService;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.crypto.digest.MD5;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @Classname SmsServieImpl
 * @Description
 * @Date 2023/3/1 16:58
 * @Author PoffyZhang
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SmsServieImpl implements SmsService {

    private final RestTemplate restTemplate;
    private final INdUserInfoService ndUserInfoService;
    private final INdUserAuthService ndUserAuthService;
    private final CachePlusOps cachePlusOps;

    @Value("${sms.user}")
    private String user;

    @Value("${sms.siid}")
    private String siid;

    @Value("${sms.secretKey}")
    private String secretKey;

    @Value("${sms.url}")
    private String url;

    @Override
    public String sendMessage(String mobile, String content) {
        String secretKey = "082e691f65fd4a4d9f353b9c54b6735e";
        String accessKey = "bff297b3ac7f45f293de72087ba6d095";

        String timeStamp = LocalDateTimeUtil.format(LocalDateTime.now(),"yyyyMMddHHmmssSSS");
        String transactionID = timeStamp;
        String streamingNo = "9000001120230507162550676";
        String authenticator = Base64.getEncoder().encodeToString((timeStamp + transactionID + streamingNo + secretKey).getBytes());

        Map<String,Object> map = new HashMap<>();
        map.put("siid","zhejiang1");
        map.put("user","httpadmin");
        map.put("authenticator",authenticator);
        map.put("timeStamp",timeStamp);
        map.put("transactionID",transactionID);
        map.put("streamingNo",streamingNo);
        map.put("mobile",mobile);
        map.put("content",content);
        ResponseEntity<String> responseEntity = null;

        //发送post请求
        RequestEntity<Map<String,Object>> requestEntity = RequestEntity
                .post("http://115.239.134.217/smsservice/httpservices/capService")
                .header("Accept", MediaType.APPLICATION_JSON.toString())
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .body(map); //也可以是DTO
        //http://115.239.134.217/smsservice/httpservices/capService
        //https://interface.zjzwfw.gov.cn/gateway/component/routing/agent.htm
        try {
            responseEntity=  restTemplate.exchange(requestEntity,String.class);
        } catch (Exception e) {
            log.error("[RestTemplateTest-test] http request error", e);
        }
        //请求参数      参数类型      是否必填     描述           示例值
        //siid           String          否          客户编号
       // user          String          否          HTTP帐号
       // authenticator  String          否          认证码 参数4.4 BASE64（timeStamp+transactionID + streamingNO + 接口密钥）
       // timestamp     String          否         当前时间戳
        //transactionID   String         否          事务号
        //streamingNo   String        否           流水号
        //mobile        String        否           多个号码用英文逗号分隔
        //extcode       String         否         扩展码
       // contet        String          否        内容
        return responseEntity.toString();
    }

    @Override
    public String sendSmsCode(String mobile, String verificationCode) {
        String timeStamp = LocalDateTimeUtil.format(LocalDateTime.now(),"yyyyMMddHHmmssSSS");
        String transactionID = timeStamp;
        String streamingNo = siid + transactionID;
        String authenticator = encoderByMd5(timeStamp + transactionID + streamingNo + secretKey);

        Map<String,Object> map = new HashMap<>();
        map.put("siid",siid);
        map.put("user",user);
        map.put("authenticator",authenticator);
        map.put("timeStamp",timeStamp);
        map.put("transactionID",transactionID);
        map.put("streamingNo",streamingNo);
        map.put("mobile",mobile);
        String content = String.format(SmsConstant.SMS_CONSTANT_TEMPLATE,verificationCode);
        map.put("content",content);
        ResponseEntity<String> responseEntity = null;

        //发送post请求
        RequestEntity<Map<String,Object>> requestEntity = RequestEntity
                .post(url)
                .header("Accept", MediaType.APPLICATION_JSON.toString())
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                //也可以是DTO
                .body(map);
        try {
            responseEntity=  restTemplate.exchange(requestEntity,String.class);
        } catch (Exception e) {
            log.error("[RestTemplateTest-test] http request error", e);
        }
        return responseEntity.toString();
    }
    private String encoderByMd5(String str) {
        try {
            // 确定计算方法
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            // 加密后的字符串
            return cn.hutool.core.codec.Base64.encode(md5.digest(str.getBytes("UTF-8")));
        } catch (Exception e) {
            return "";
        }
    }

    @Override
    public String getCode(UserLoginDTO param) {
        // 获取用户名入参信息
        String userName = param.getUsername();
        // 根据用户名获取用户账号信息
        NdUserAuth userAuth = ndUserAuthService.getOne(Wrappers.lambdaQuery(NdUserAuth.class)
                .eq(NdUserAuth::getIdentifier, userName));
        VUtils.isTrue(Objects.isNull(userAuth)).throwMessage("该用户不存在!");
        // 根据用户ID获取用户信息
        NdUserInfo ndUserInfo = ndUserInfoService.getOne(Wrappers.lambdaQuery(NdUserInfo.class)
                .eq(NdUserInfo::getId, userAuth.getUserId()));
        VUtils.isTrue(Objects.isNull(ndUserInfo)).throwMessage("该用户不存在!");
        String mobile = ndUserInfo.getMobile();
        VUtils.isTrue(StringUtils.isBlank(mobile)).throwMessage("该用户没有设置手机号!");

        String verificationCode = CodeUtil.codeFen(6);
        // 将验证码保存到redis中，并设置过期时间
        CacheKey key = new CacheKey(UserLoginConstant.RedisKey.USER_LOGIN + userName);
        key.setExpire(Duration.ofMinutes(10));
        cachePlusOps.set(key,verificationCode,false);

        String url = "http://shuiniche.ningdatech.com/cm/open/api/sms/send-sms-code";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("mobile", mobile);
        requestBody.put("verificationCode", verificationCode);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        try {
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
            return responseEntity.getBody();
        } catch (RestClientException e) {
            throw new BizException("调用短信转发服务失败!");
        }
    }

    public static void main(String[] args) {
        //String mobile = "15058187290";
        String mobile = "18556991003";
        String content = "司机爱UI时候爱US哈UI晒u";
        RestTemplate restTemplate = new RestTemplate();

//        String secretKey = "082e691f65fd4a4d9f353b9c54b6735e";
//        String accessKey = "bff297b3ac7f45f293de72087ba6d095";
        String secretKey = "ZjHc5%7&";

        String timeStamp = LocalDateTimeUtil.format(LocalDateTime.now(),"yyyyMMddHHmmssSSS");
        String transactionID = timeStamp;
        String streamingNo = "9000001120230507162550677";
        String authenticator = Base64.getEncoder().encodeToString(
                MD5.create().digest((timeStamp + transactionID + streamingNo + secretKey).getBytes()));

        Map<String,Object> map = new HashMap<>();
        map.put("siid","ZJHCJSJXTYXGS9");
        map.put("user","zjhc9");
        map.put("authenticator",authenticator);
        map.put("timeStamp",timeStamp);
        map.put("transactionID",transactionID);
        map.put("streamingNo",streamingNo);
        map.put("mobile",mobile);
        map.put("content",content);
        ResponseEntity<String> responseEntity = null;

        //发送post请求
        RequestEntity<Map<String,Object>> requestEntity = RequestEntity
                .post("http://115.239.134.217/smsservice/httpservices/capService")
                .header("Accept", MediaType.APPLICATION_JSON.toString())
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .body(map); //也可以是DTO

        try {
            responseEntity=  restTemplate.exchange(requestEntity,String.class);
        } catch (Exception e) {
            log.error("[RestTemplateTest-test] http request error", e);
        }

        System.out.println(responseEntity.toString());
    }
}
