package com.ruoyi.web.controller.tool;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.Gson;
import com.ruoyi.common.config.BaiduConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.system.domain.ClewPhone;
import com.ruoyi.system.domain.NoticeRequest;
import com.ruoyi.system.domain.OppoCheck;
import com.ruoyi.system.service.IClewPhoneService;
import com.ruoyi.web.core.config.GlobalLogHelper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.security.GeneralSecurityException;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.utils.http.HttpUtils.sendPost;

/**
 * @author clunt
 * 通知模块
 */
@Slf4j
@Controller
@RequestMapping("/tool/notice")
public class NoticeController {

    @Autowired
    private BaiduConfig baiduConfig;

    @Autowired
    private IClewPhoneService clewPhoneService;

    @PostMapping("/logout")
    @ResponseBody
    public AjaxResult logout(@RequestBody NoticeRequest request){

        return AjaxResult.success("注销成功!");
    }

    @GetMapping("/exposure")
    @ResponseBody
    public AjaxResult exposure(){

        return AjaxResult.success("曝光成功!");
    }

    @GetMapping("/click")
    @ResponseBody
    public AjaxResult click(){

        return AjaxResult.success("点击成功!");
    }

    @GetMapping("/download")
    @ResponseBody
    public AjaxResult download(@RequestParam("aid")String aid,
                               @RequestParam("appId")String appId,
                               @RequestParam("oaid")String oaid,
                               @RequestParam("idType")String idType,
                               @RequestParam("uniqueId")String uniqueId,
                               @RequestParam("actionType")String actionType,
                               @RequestParam("callBack")String callBack){
        log.info("归因转化回调内容,{},{},{},{},{},{},{}", aid, appId, oaid, idType, uniqueId, actionType, callBack);
        String token= getToken();
        if (StringUtils.isEmpty(token)){
            token="eyJraWQiOiJ1MUFEcW95T21wT1ZHcXh6VzNnaWtPNER3UmJDZ2RNRCIsInR5cCI6IkpXVCIsImFsZyI6IkhTMjU2In0.eyJzdWIiOiIxMjczODgzNzQ1NTQ3NDkzODI0IiwiZG4iOjEsImNsaWVudF90eXBlIjoxLCJleHAiOjE3NDk2MjUyNDEsImlhdCI6MTc0OTQ1MjQ0MX0.yZnwxuUVxA8dC1TnMtKfnOKB3Cd4s4afujPs5F8pcX0";
        }
        HuaweiRequest huaweiRequest=new HuaweiRequest();
        huaweiRequest.setActionType("4");
        huaweiRequest.setActionTime(System.currentTimeMillis());
        huaweiRequest.setDeviceIdType("OAID");
        huaweiRequest.setAppId(appId);
        huaweiRequest.setCallBack(callBack);
        huaweiRequest.setDeviceId(oaid);
        huaweiRequest.setActionParam("[{'name':'付费金额','value':8}]"); // 根据业务需要调整
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/json");
        headerMap.put("client_id",  "1273883745547493824");
        headerMap.put("Authorization",  "Bearer "+token);
        log.info("请求https://connect-api.cloud.huawei.com/api/datasource/v1/track/activate的属性{},headermap{}", JSONObject.toJSONString(huaweiRequest),headerMap);
        String s = sendPost("https://connect-api.cloud.huawei.com/api/datasource/v1/track/activate", JSONObject.toJSONString(huaweiRequest), headerMap);
        log.info("请求https://connect-api.cloud.huawei.com/api/datasource/v1/track/activate的响应{}", s);


        return AjaxResult.success("下载成功!");
    }

    @GetMapping("/install")
    @ResponseBody
    public AjaxResult install(){

        return AjaxResult.success("安装成功!");
    }

    @PostMapping("/getLocation")
    @ResponseBody
    public AjaxResult getLocationByLot(@RequestBody JSONObject jsonObject){
        try {
            String location = jsonObject.getString("location");
            String url = baiduConfig.getUrl().replace("#AK#", baiduConfig.getAk()) + location;
            String result = HttpUtils.sendGet(url);
            result = result.replaceAll("\n", "").replaceAll("\t", "");
            JSONObject resultJson = JSONObject.parseObject(result);
            if("0".equals(resultJson.getString("status"))){
                return AjaxResult.success(resultJson.getJSONObject("result").getJSONObject("addressComponent"));
            }else {
                return AjaxResult.error("Api服务异常!");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }


    @PostMapping("/sendSms")
    @ResponseBody
    public AjaxResult sendMsg(@RequestBody @Valid NoticeRequest request){
        try {
            // 短信验证码
            String code = String.valueOf((int)((Math.random() * 9 + 1) * Math.pow(10,5)));

            // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html

            Client client = createClient("null", "null");
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName("保无忧法律咨询")
                    .setTemplateCode("SMS_268511098")
                    .setPhoneNumbers(request.getPhone())
                    .setTemplateParam("{\"code\":"+ code +"}");
            RuntimeOptions runtime = new RuntimeOptions();
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            log.info("发送给{}短信响应为{}", request.getPhone(), sendSmsResponse);
            CacheUtils.put(request.getPhone(), code);
            // 请求次数入库
            try {
                ClewPhone param = new ClewPhone();
                param.setPhone(request.getPhone());
                List<ClewPhone> clewPhones = clewPhoneService.selectClewPhoneList(param);
                if(CollectionUtils.isEmpty(clewPhones)){
                    ClewPhone model = new ClewPhone();
                    model.setPhone(request.getPhone());
                    model.setCreateTime(new Date());
                    model.setRemark(request.getFrom());
                    if(StringUtils.isNotEmpty(request.getSourceApp())){
                        model.setSourceApp(Long.valueOf(request.getSourceApp()));
                    }else {
                        model.setSourceApp(1L);
                    }
                    clewPhoneService.insertClewPhone(model);
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("手机号入库失败!,原因:{}", e.getMessage());
            }
            // 调用oppo的统计接口
            try {
                if("oppo".equalsIgnoreCase(request.getFrom())){
                    // 回调
                    OppoCheck model = new OppoCheck();
                    model.setDataType(2);
                    model.setTimestamp(System.currentTimeMillis());
                    if(StringUtils.isNotEmpty(request.getImei())){
                        model.setImei(encode(request.getImei().getBytes()));
                    }
                    if(StringUtils.isNotEmpty(request.getOaid())){
                        model.setOuId(encode(request.getOaid().getBytes()));
                    }
                    String content = JSONObject.toJSONString(model) + model.getTimestamp() + "e0u6fnlag06lc3pl";
                    log.info("请求的content加密前属性{}", content);
                    Map<String, String> headerMap = new HashMap<>();
                    headerMap.put("signature", Md5Utils.hash(content));
                    headerMap.put("timestamp", String.valueOf(model.getTimestamp()));
                    headerMap.put("Content-Type", "application/json");
                    log.info("请求https://api.ads.heytapmobi.com/api/uploadActiveData的属性{}", JSONObject.toJSONString(model));
                    String s = sendPost("https://api.ads.heytapmobi.com/api/uploadActiveData", JSONObject.toJSONString(model), headerMap);
                    log.info("请求https://api.ads.heytapmobi.com/api/uploadActiveData的响应{}", s);
                }else if("vivo".equalsIgnoreCase(request.getFrom())){
                    String token = "b447ca5eaa2aabac351bc798e8a826f2ad52927bb01aa0afcb8ca22397dac494";
                    String timeStamp = System.currentTimeMillis() + "";
                    String notice = "VIVO"+ (long)((Math.random()+1) * 10000000);
                    String url = "https://marketing-api.vivo.com.cn/openapi/v1/advertiser/behavior/upload?access_token="+token+"&timestamp="+timeStamp+"&nonce="+notice;
                    String content = "{\"dataList\":[{\"cvTime\":"+timeStamp+",\"cvType\":\"REGISTER\",\"userId\":\""+ request.getOaid() +"\",\"userIdType\":\"OAID\"}],\"pkgName\":\"com.yinliu.loan\",\"srcId\":\"ds-202502072511\",\"srcType\":\"app\"}";
                    Map<String, String> headerMap = new HashMap<>();
                    headerMap.put("Content-Type", "application/json");
                    log.info("请求{}的属性{}", url, content);
                    String s = sendPost(url, content, headerMap);
                    log.info("请求{}的响应{}", url, s);
                }else if("xiaomi".equalsIgnoreCase(request.getFrom())){
                    log.info("oaid : {}, imei:{}", request.getOaid(), request.getImei());
                    String imei = request.getImei();
                    String oaid = request.getOaid();
//                    String ua = "Dalvik/2.1.0 (Linux; U; Android 11; M2012K11AC Build/RKQ1.200826.002)";
                    String clientIp = "58.49.150.163";
                    long convTime = System.currentTimeMillis();
                    String convType = "APP_REGISTER";
                    int customerId = 445972;
                    long appId = 1545362;
                    String singKey = "rEQNdyVQxHlayYzw";
                    String encryptKey = "RPeKBIdybnbMAVlK";
                    if(request.getSourceApp() != null && "2".equals(request.getSourceApp())){
                        customerId = 593022;
                        appId = 1585622;
                        singKey = "WJzbmmPPufjyKESi";
                        encryptKey = "sTrlawivcqdHzUDB";
                    }
                    GlobalLogHelper.UploadInfo uploadInfo = GlobalLogHelper.UploadInfo.builder()
//                            .imei(imei)
                            .oaid(oaid)
//                            .ua(ua)
                            .clientIp(clientIp)
                            .convTime(convTime).convType(convType)
                            .appId(appId).customerId(customerId).signKey(singKey).encryptKey(encryptKey).build().genInfo();
                    log.info("请求xiaomi的属性{}", uploadInfo.getFinalUrl());
                    String s = HttpUtils.sendGet(uploadInfo.getFinalUrl());
                    log.info("请求xiaomi的响应{}", s);
                }else {
                    log.info("短信请求接口入参:{}", request);
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("回调oppo报错:{}", e.getMessage());
            }

        }catch (Exception e){
            log.error("给 {} 发送短信失败 {}", request.getPhone(), ExceptionUtil.getExceptionMessage(e));
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success("操作成功!");
    }

    @PostMapping("/checkSms")
    @ResponseBody
    public AjaxResult checkSms(@RequestBody @Valid NoticeRequest request){
        if(StringUtils.isNotEmpty(request.getCode())){
            Object obj = CacheUtils.get(request.getPhone());
            if(obj != null && request.getCode().equals(obj.toString())){
                CacheUtils.remove(request.getPhone());
                return AjaxResult.success("操作成功!");
            }
        }
        return AjaxResult.error("操作失败!");
    }

    public static String encode(byte[] data) throws GeneralSecurityException {
        final Key dataKey = new SecretKeySpec(Base64.decodeBase64("XGAXicVG5GMBsx5bueOe4w=="), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, dataKey);
        byte[] encryptData = cipher.doFinal(data);
        return Base64.encodeBase64String(encryptData).replaceAll("\r", "").replaceAll("\n", "");
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }
    @Data
    static class HuaweiRequest  {
        private String actionType;
        private long actionTime;
        private String deviceIdType;
        private String appId;
        private String callBack;
        private String deviceId;
        private String actionParam;

    }
   public static String getToken(){
       Map<String, String> headers = new HashMap<>();
       headers.put("Content-Type", "application/json");

       Map<String,String> params=new HashMap<>();
       params.put("grant_type", "client_credentials");
       params.put("client_id", "1273883745547493824");  // 从配置读取
       params.put("client_secret", "BBA385787FE8D5CA4F0C889915C6FBA752F7B18C19E99FFE6B09ACCC92C60181");  // 从配置读取
       String s;
       try {
          s=   sendPost(
                   "https://connect-api.cloud.huawei.com/api/oauth2/v1/token",
                   JSONObject.toJSONString(params),
                   headers
           );
       } catch (Exception e) {
           log.error("华为API调用失败", e);
           return "ERROR: " + e.getMessage();
       }

       if (StringUtils.isNotEmpty(s)){
           Gson gson = new Gson();
           Map<String, String> map = gson.fromJson(s, Map.class);
           String token=map.get("access_token");
           return  token;
       }


        return s;
   }


}
