package com.ruoyi.web.controller.system;

import java.security.GeneralSecurityException;
import java.security.Key;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
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.OppoCheck;
import com.ruoyi.system.service.IClewPhoneService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Clew;
import com.ruoyi.system.service.IClewService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 线索Controller
 *
 * @author ruoyi
 * @date 2023-05-15
 */
@Slf4j
@Controller
@RequestMapping("/system/clew")
public class ClewController extends BaseController
{
    private String prefix = "system/clew";

    @Autowired
    private IClewService clewService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IClewPhoneService clewPhoneService;

    @RequiresPermissions("system:clew:view")
    @GetMapping()
    public String clew(ModelMap modelMap)
    {
        List<SysUser> users = sysUserService.selectUserList(new SysUser());
        modelMap.put("users", users);
        return prefix + "/clew";
    }

    /**
     * 查询线索列表
     */
    @RequiresPermissions("system:clew:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Clew clew)
    {
        startPage();
        if(!"admin".equals(getSysUser().getLoginName())){
            clew.setSaleId(getSysUser().getUserId());
        }
        List<Clew> list = clewService.selectClewList(clew);
        list.forEach(model->{
            if(model.getSaleId() != null){
                SysUser user = sysUserService.selectUserById(model.getSaleId());
                if(user != null){
                    model.setSaleName(user.getUserName());
                }
            }
        });
        return getDataTable(list);
    }

    /**
     * 导出线索列表
     */
    @RequiresPermissions("system:clew:export")
    @Log(title = "线索", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Clew clew)
    {
        List<Clew> list = clewService.selectClewList(clew);
        ExcelUtil<Clew> util = new ExcelUtil<Clew>(Clew.class);
        return util.exportExcel(list, "线索数据");
    }

    /**
     * 新增线索
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存线索
     */
    @RequiresPermissions("system:clew:add")
    @Log(title = "线索", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Clew clew)
    {
        return toAjax(clewService.insertClew(clew));
    }


    @PostMapping("/app/add")
    @ResponseBody
    public AjaxResult appAddSave(@RequestBody Clew clew)
    {
        Clew param = new Clew();
        param.setPhone(clew.getPhone());
        List<Clew> result = clewService.selectClewList(param);
        if (CollectionUtils.isNotEmpty(result)){
            return AjaxResult.success();
        }

        // 不存在手机号则入库线索
        clewService.insertClew(clew);

        // 将初始线索设置成已跟踪
        ClewPhone model = new ClewPhone();
        model.setPhone(clew.getPhone());
        List<ClewPhone> clewPhoneList =  clewPhoneService.selectClewPhoneList(model);
        clewPhoneList.forEach(x->{
            x.setStatus("1");
            clewPhoneService.updateClewPhone(x);
        });
        // 调用oppo的统计接口
        try {
            // 回调
            if("oppo".equalsIgnoreCase(clew.getRemark())){
                OppoCheck oppoCheck = new OppoCheck();
                oppoCheck.setDataType(7);
                oppoCheck.setTimestamp(System.currentTimeMillis());
                if(StringUtils.isNotEmpty(clew.getImei())){
                    oppoCheck.setImei(encode(clew.getImei().getBytes()));
                }
                if(StringUtils.isNotEmpty(clew.getOaid())){
                    oppoCheck.setOuId(encode(clew.getOaid().getBytes()));
                }
                String content = JSONObject.toJSONString(oppoCheck) + oppoCheck.getTimestamp() + "e0u6fnlag06lc3pl";
                log.info("请求的content加密前属性{}", content);
                Map<String, String> headerMap = new HashMap<>();
                headerMap.put("signature", Md5Utils.hash(content));
                headerMap.put("timestamp", String.valueOf(oppoCheck.getTimestamp()));
                headerMap.put("Content-Type", "application/json");
                log.info("请求https://api.ads.heytapmobi.com/api/uploadActiveData的属性{}", JSONObject.toJSONString(oppoCheck));
                String s = HttpUtils.sendPost("https://api.ads.heytapmobi.com/api/uploadActiveData", JSONObject.toJSONString(oppoCheck), headerMap);
                log.info("请求https://api.ads.heytapmobi.com/api/uploadActiveData的响应{}", s);
            }else if("vivo".equalsIgnoreCase(clew.getRemark())){
                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\":\"PAY\",\"userId\":\""+ clew.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);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("回调oppo报错:{}", e.getMessage());
        }
        return AjaxResult.success();
    }

    //huawei-归因
    public String getHuaWeiToken(){

        return null;
    }

    public String send() throws Exception{
        JSONObject vivoJson = new JSONObject();
        vivoJson.put("srcType", "APP");
        vivoJson.put("pkgName", "");
        vivoJson.put("pageUrl", "");
        vivoJson.put("srcId", "");
        vivoJson.put("dataFrom", "0");
        String url = "https://sandbox-marketing-api.vivo.com.cn/openapi/v1/advertiser/behavior/upload";
        String advertiserId = "XX";
        String nonce = "XX";
        String accessToken = "595a46633e3f8162363a37092037a436f62e4d462102ddbf3eb503fa52017b93";
        String timestamp = String.valueOf(System.currentTimeMillis());
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        String jsonStr = "XX"; //使用请求参数的json串替换，格式如下方示例
        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, jsonStr);
        Request request = new Request.Builder()
                .url(url + "?access_token=" + accessToken + "&timestamp=" + timestamp + "&nonce=" + nonce + "&advertiser_id=" + advertiserId)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    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", "");
    }

    /**
     * 修改线索
     */
    @RequiresPermissions("system:clew:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Clew clew = clewService.selectClewById(id);
        mmap.put("clew", clew);
        return prefix + "/edit";
    }

    /**
     * 修改保存线索
     */
    @RequiresPermissions("system:clew:edit")
    @Log(title = "线索", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Clew clew)
    {
        return toAjax(clewService.updateClew(clew));
    }

    /**
     * 删除线索
     */
    @RequiresPermissions("system:clew:remove")
    @Log(title = "线索", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(clewService.deleteClewByIds(ids));
    }

    @PostMapping("/changeUser")
    @ResponseBody
    public AjaxResult changeUser(Clew clew)
    {
        return toAjax(clewService.updateClew(clew));
    }

    @GetMapping("/changeUser/{clewId}")
    public String changeUser(@PathVariable("clewId") String id, ModelMap mmap)
    {
        mmap.put("clewId", id);
        mmap.put("users", sysUserService.selectUserList(new SysUser()));
        return "system/clew/changeUser";
    }

}
