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.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.common.utils.uuid.UUID;
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 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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
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;

/**
 * @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("注销成功!");
    }

    @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("LTAI5tLDuQRdfyHASSxehs9m", "CraRUliWZNMJhhSRIZ0nVWrxFkGTOH");
            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);
            // 调用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 = HttpUtils.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 = "78c0170798cf83a7f79ce8fcb5eba68f3329b0e94967686917efcb1dc37e336f";
                    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-202310270565\",\"srcType\":\"app\"}";
                    Map<String, String> headerMap = new HashMap<>();
                    headerMap.put("Content-Type", "application/json");
                    log.info("请求{}的属性{}", url, content);
                    String s = HttpUtils.sendPost(url, content, headerMap);
                    log.info("请求{}的响应{}", url, s);
                }else {
                    log.info("短信请求接口入参:{}", request);
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("回调oppo报错:{}", e.getMessage());
            }
            // 请求次数入库
            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());
                    clewPhoneService.insertClewPhone(model);
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("手机号入库失败!,原因:{}", 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);
    }

}
