package org.tio.sitexxx.server.controller;

import cn.hutool.core.util.StrUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.tio.http.common.HttpRequest;
import org.tio.http.server.annotation.RequestPath;
import org.tio.jfinal.plugin.activerecord.Record;
import org.tio.sitexxx.server.utils.Sha256Util;
import org.tio.sitexxx.server.utils.WebUtils;
import org.tio.sitexxx.server.vo.IsAdShowVo;
import org.tio.sitexxx.service.model.main.Task;
import org.tio.sitexxx.service.model.main.TaskRecord;
import org.tio.sitexxx.service.model.main.User;
import org.tio.sitexxx.service.model.main.UserTask;
import org.tio.sitexxx.service.service.ConfService;
import org.tio.sitexxx.service.service.TaskService;
import org.tio.sitexxx.service.service.base.UserService;
import org.tio.sitexxx.service.vo.Const;
import org.tio.sitexxx.service.vo.ReportAdVo;
import org.tio.sitexxx.service.vo.TaskDetailVo;
import org.tio.utils.crypto.Md5;
import org.tio.utils.resp.Resp;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <pre>
 *    @author : vagrancy
 *    e-mail : 18050829067@163.com
 *    time   : 2026-02-25 16:23
 *    desc   : 任务控制
 * </pre>
 */
@RequestPath(value = "/task")
@Slf4j
public class TaskController {
    /**
     * 详情
     */
    @RequestPath(value = "/detail")
    public Resp detail(HttpRequest request) {
        Integer userId = WebUtils.currUserId(request);
        User curr = UserService.ME.getById(userId);
        if (curr == null) {
            return Resp.fail("未登录");
        }
        UserTask userTask = TaskService.me.getOne(curr.getId());
        TaskDetailVo vo = new TaskDetailVo();
        if (userTask != null) {
            if (userTask.getCoin() == null) {
                vo.setCoinTotal(0);
            } else {
                vo.setCoinTotal(userTask.getCoin().intValue());
            }
        } else {
            userTask = new UserTask();
            userTask.setStatus(1);
            userTask.setUid(curr.getId());
            userTask.setUtime(new Date());
            userTask.setCtime(new Date());
            userTask.setCoin(new BigDecimal(0));
            userTask.save();
            vo.setCoinTotal(0);
        }
        vo.setRate(ConfService.getInt(Const.ConfMapping.COIN_RATE,10000));
        List<Task> tasks = TaskService.me.getList();
        List<TaskDetailVo.Item> list = new ArrayList<>();
        for (Task task : tasks) {
            TaskDetailVo.Item item = new TaskDetailVo.Item();
            item.desc = task.getSummary();
            item.title = task.getTitle();
            item.type = task.getType();
            item.adType = task.getAdType();
            item.id = task.getId();
            if (task.getType() == Const.TaskType.AD) {
                item.maxCount = curr.getMaxCount();
                item.count = TaskService.me.getDayCount(curr.getId(), task.getId());
                item.done = 0;
            } else {
                item.maxCount = task.getMaxCount();
                item.done = TaskService.me.getDayCountByDoneInvite(curr.getId(), task.getId());
                if (item.done == 1) {
                    item.count = item.maxCount;
                } else {
                    item.count = TaskService.me.getDayCountByInvite(curr.getId(), curr.getInvitecode());
                }
            }
            item.adId = task.getAdId();
            list.add(item);
        }
        vo.setItems(list);
        return Resp.ok(vo);
    }

    @RequestPath(value = "/isAdShow")
    public Resp isAdShow(HttpRequest request, Integer taskId, String deviceId, String ip){
        User curr = WebUtils.currUser(request);
        if (curr == null) {
            return Resp.fail("未登录");
        }
        int uid = curr.getId();
        int maxCount = curr.getMaxCount();
        int count = TaskService.me.getDayCount(uid, taskId);
        int ipCount = TaskService.me.getDayCountByIp(taskId, ip);
        int deviceIdCount = TaskService.me.getDayCountByDeviceId(taskId, deviceId);
        boolean isStatus;
        if (count >= maxCount) {
            isStatus = false;
        } else {
            if (ipCount >= maxCount) {
                isStatus = false;
            } else {
                isStatus = deviceIdCount < maxCount;
            }
        }
        IsAdShowVo vo = new IsAdShowVo();
        if (isStatus) {
            long ctime = TaskService.me.getNew(taskId, uid);
            if (ctime == 0) {
                vo.type = Const.AdShow.SUCCESS;
            } else {
                long oneTime = System.currentTimeMillis() - ctime;
                if (oneTime < 60000) {
                    vo.time = String.valueOf((600000 - oneTime)/1000);
                    vo.type = Const.AdShow.TIME_LIMIT;
                } else {
                    vo.type = Const.AdShow.SUCCESS;
                }
            }
        } else {
            vo.type = Const.AdShow.MAX_LIMIT;
        }
        return Resp.ok(vo);
    }

    @RequestPath(value = "/receivePrize")
    public Resp receivePrize(HttpRequest request, Integer taskId, String deviceId, String ip) {
        User curr = WebUtils.currUser(request);
        if (curr == null) {
            return Resp.fail("未登录");
        }
        int uid = curr.getId();
        TaskRecord taskRecord = TaskService.me.getTaskRecordByInvite(uid, taskId);
        if (taskRecord != null) {
            return Resp.fail("任务已完成,请明天在尝试");
        }
        //获取任务
        Task task = TaskService.me.getTask(taskId);
        //获取完成任务
        List<Record> list = TaskService.me.getDayByInvite(uid);
        boolean result = false;
        int maxCount = task.getMaxCount();
        if (list.size() >= maxCount) {
            result = true;
            TaskService.me.addTaskRecordByInvite(taskId, uid, String.valueOf(task.getCoin()), deviceId, ip);
            for (Record record : list) {
                TaskService.me.addTaskDoneInvite(uid, record.getInt("uid"));
            }
            UserTask userTask = TaskService.me.getOne(uid);
            if (userTask != null) {
                userTask.setCoin(userTask.getCoin().add(task.getCoin()));
                userTask.setUtime(new Date());
                userTask.update();
            }
        }
        return Resp.ok(result);
    }

    @RequestPath(value = "/reportAd")
    public Resp reportAd(HttpRequest request, Integer taskId, Integer adType, String deviceId, String ip, String transId, String ecpm) {
        User curr = WebUtils.currUser(request);
        if (curr == null) {
            return Resp.fail("未登录");
        }
        int uid = curr.getId();
        int maxCount = curr.getMaxCount();
        int count = TaskService.me.getDayCount(uid, taskId);

        ReportAdVo vo = new ReportAdVo();
        vo.setTaskId(taskId);
        vo.setMaxCount(maxCount);
        vo.setCount(count);
        vo.setRate(ConfService.getInt(Const.ConfMapping.COIN_RATE,10000));

        if (adType == Const.AdType.TENCENT_AD) {
            TaskRecord record = TaskService.me.getTaskRecord(uid, transId, Const.AdType.TENCENT_AD);
            if (record != null) {
                //结算价格
                addCoin(uid, ecpm);
                record.setCoin(ecpm);
                record.setDeviceId(deviceId);
                record.setIp(ip);
                record.update();
            }
        }else if (adType == Const.AdType.BAIDU_AD){
            //TaskRecord record = TaskService.me.getTaskRecord(uid, transId, Const.AdType.BAIDU_AD);
            //if (record != null) {
                //结算价格
                //addCoin(uid, ecpm);
                //record.setCoin(ecpm);
            //    record.setDeviceId(deviceId);
            //    record.setIp(ip);
            //    record.update();
            //}
        } else if (adType == Const.AdType.KUAISHOU_AD) {
            TaskRecord record = TaskService.me.getTaskRecord(uid, transId, Const.AdType.KUAISHOU_AD);
            if (record != null) {
                //结算价格
                addCoin(uid, ecpm);
                record.setCoin(ecpm);
                record.setDeviceId(deviceId);
                record.setIp(ip);
                record.update();
            }
        }
        UserTask userTask = TaskService.me.getOne(uid);
        if (userTask != null) {
            vo.setCoinTotal(userTask.getCoin().intValue());
        } else {
            userTask = new UserTask();
            userTask.setStatus(1);
            userTask.setUid(curr.getId());
            userTask.setUtime(new Date());
            userTask.setCtime(new Date());
            userTask.setCoin(new BigDecimal(0));
            userTask.save();
            vo.setCoinTotal(0);
        }
        //ecpm 单位分
        return Resp.ok(vo);
    }

    //103947940 e0df7ab75e9292534094647b8f40cec8
    //https://www.366w.com/mytio/task/adCallback?adn_name=pangle&ecpm=10000.0&extra=&mediation_rit=977756275&play_end_ts=1773280309274&play_start_ts=1773280294272&plugin_version=7.5.0.7&prime_rit=103947684&reward_amount=1&reward_name=%E6%BF%80%E5%8A%B12&reward_type=0&risk_level=0&sdk_version=7.4.2.1&sign=8a1db8bf769cced54c6b5cb8614f444669c292aa7a90f35dbb3fae14fa5ab6dd&trans_id=26a3377f-ec50-4e78-a152-b2b53146d548&user_id=117199

    /**
     * 穿山甲回调
     * @param adn_name
     * @param trans_id
     * @param ecpm
     * @param sign
     * @param prime_rit
     * @param user_id
     * @param mediation_rit
     * @return
     */
    @RequestPath("/adCallback")
    public String adCallback(HttpRequest request, String adn_name, String trans_id, String ecpm, String sign, String prime_rit, String user_id, Integer mediation_rit) {
        log.error("body=>"+ new Gson().toJson(request.getParam()));
        Task task = TaskService.me.getTaskByAdId(prime_rit, Const.AdType.PANGLE_AD);
        if (task == null) {
            return toResult(false, "该任务不存在");
        }
        int uid = Integer.parseInt(user_id);
        TaskRecord oldRecord = TaskService.me.getTaskRecord(uid, trans_id, Const.AdType.PANGLE_AD);
        if (oldRecord != null) {
            return toResult(false, "该广告已处理");
        }
        String newSign = Sha256Util.sha256Hex(task.getSign()+":"+trans_id);
        if (!sign.equals(newSign)) {
            return toResult(false, "签名不同");
        }
        addCoin(uid, ecpm);
        User user = UserService.ME.getById(uid);
        String pCode = "";
        if (user != null) {
            pCode = user.getParentInvite();
        }
        TaskService.me.addTaskRecord(task.getId(), uid, pCode, task.getAdType(), ecpm, adn_name, trans_id, mediation_rit);
        return toResult(true, "成功");
    }
    private String toResult(boolean isVerify, String reason){
        JsonObject object = new JsonObject();
        object.addProperty("is_verify", isVerify);
        object.addProperty("isValid", isVerify);
        object.addProperty("reason", reason);
        return object.toString();
    }

    /**
     * 腾讯广告回调
     * @param ecpm
     * @return
     */
    ///mytio/task/tAdCallback?sig=8d04a1dfae611246ae65bf2191de9e261e6fe569978efe29a0b040133b378359&amp;userid=117199&amp;transid=025a5c9066a16f0e9de45108c303bbdf&amp;appid=1215284569&amp;pid=4248109581095631&amp;extrainfo=
    @RequestPath("/tAdCallback")
    public String tAdCallback(HttpRequest request, String transid, String ecpm, String sig, String pid, String userid) {
        log.error("body=>"+ new Gson().toJson(request.getParam()));
        Task task = TaskService.me.getTaskByAdId(pid, Const.AdType.TENCENT_AD);
        if (task == null) {
            return toResult(false, "该任务不存在");
        }
        int uid = Integer.parseInt(userid);
        ecpm = "5000";
        TaskRecord oldRecord = TaskService.me.getTaskRecord(uid, transid, Const.AdType.TENCENT_AD);
        if (oldRecord != null) {
            return toResult(false, "该广告已处理");
        }
        String newSign = Sha256Util.sha256Hex(transid+":"+task.getSign());
        if (!sig.equals(newSign)) {
            return toResult(false, "签名不同");
        }
        addCoin(uid, ecpm);
        User user = UserService.ME.getById(uid);
        String pCode = "";
        if (user != null) {
            pCode = user.getParentInvite();
        }
        TaskService.me.addTaskRecord(task.getId(), uid, pCode, task.getAdType(), ecpm, "tencent", transid, 0);
        return toResult(true, "成功");
    }

    //19274856 bn2lsxyrt0d0cwybkvl4o75
    // /mytio/task/bAdCallback?user_id=117241&amp;apid=19274856&amp;appid=f5a7b2f5&amp;extra=&amp;sign=6ca1dcd6fb4f430428b4d901d7306618231c8a03be7e28032f5662422bb4024f&amp;trans_id=8083d21bd7d68c74&amp;ts=1774430812389

    @RequestPath("/bAdCallback")
    public String bAdCallback(HttpRequest request, String trans_id, String ecpm, String sign, String apid, String user_id) {
        log.error("body=>"+ new Gson().toJson(request.getParam()));
        Task task = TaskService.me.getTaskByAdId(apid, Const.AdType.BAIDU_AD);
        if (task == null) {
            return toResult(false, "该任务不存在");
        }
        int uid = Integer.parseInt(user_id);
        ecpm = "5000";
        TaskRecord oldRecord = TaskService.me.getTaskRecord(uid, trans_id, Const.AdType.BAIDU_AD);
        if (oldRecord != null) {
            return toResult(false, "该广告已处理");
        }
        String newSign = Sha256Util.sha256Hex(trans_id+":"+task.getSign());
        if (!sign.equals(newSign)) {
            return toResult(false, "签名不同");
        }
        addCoin(uid, ecpm);
        User user = UserService.ME.getById(uid);
        String pCode = "";
        if (user != null) {
            pCode = user.getParentInvite();
        }
        TaskService.me.addTaskRecord(task.getId(), uid, pCode, task.getAdType(), ecpm, "baidu", trans_id, 0);
        return toResult(true, "成功");
    }

    // 32290000001  01f83659e8747935e76f4b129c7c27e6
    // 32290000003  784645e34acb4e668c9735ee78525e8b
    @RequestPath("/kAdCallback")
    public String kAdCallback(HttpRequest request,String transId, String sign, String extra, String userId) {
        log.error("body=>"+ new Gson().toJson(request.getParam()));
        String[] str = extra.split(":");
        String adId = str[0];
        Task task = TaskService.me.getTaskByAdId(adId, Const.AdType.KUAISHOU_AD);
        if (task == null) {
            return toResult(false, "该任务不存在");
        }
        int uid = Integer.parseInt(userId);
        String oldTransId = "";
        if (str.length > 1) {
            oldTransId = str[1];
        }
        TaskRecord oldRecord = TaskService.me.getTaskRecord(uid, oldTransId, Const.AdType.KUAISHOU_AD);
        if (oldRecord != null) {
            return toResult(false, "该广告已处理");
        }
        String newSign = Md5.getMD5(task.getSign()+":"+transId);
        if (!sign.equals(newSign)) {
            return toResult(false, "签名不同");
        }
        User user = UserService.ME.getById(uid);
        String pCode = "";
        if (user != null) {
            pCode = user.getParentInvite();
        }
        TaskService.me.addTaskRecord(task.getId(), uid, pCode, task.getAdType(), "0", "kuaishou", oldTransId, 0);
        return toResult(true, "成功");
    }

    private void addCoin(Integer uid, String ecpm){
        UserTask userTask = TaskService.me.getOne(uid);
        if (userTask == null) {
            userTask = new UserTask();
            userTask.setCtime(new Date());
            userTask.setUtime(new Date());
            userTask.setCoin(new BigDecimal(0));
            userTask.setStatus(1);
            userTask.setUid(uid);
            userTask.save();
        }
        int adLayerRate = ConfService.getInt(Const.ConfMapping.AD_LAYER_RATE, 50);
        BigDecimal adLayer = new BigDecimal(adLayerRate).divide(new BigDecimal(100));
        //单位 分
        BigDecimal moneyUnit = new BigDecimal(1000);
        //获得千次几元 在除以1000次 获得1次
        BigDecimal coin;
        if (StrUtil.isEmpty(ecpm)) {
            coin = new BigDecimal(0);
        } else {
            BigDecimal money = new BigDecimal(ecpm).divide(moneyUnit).divide(new BigDecimal(1000));
            coin = money.multiply(adLayer);
        }
        //25
        int coinRate = ConfService.getInt(Const.ConfMapping.COIN_RATE, 10000);
        BigDecimal coinUnit = new BigDecimal(coinRate);
        BigDecimal coinCount = coinUnit.multiply(coin);
        BigDecimal beforeCoin = userTask.getCoin();
        BigDecimal afterCoin = beforeCoin.add(coinCount);
        userTask.setCoin(afterCoin);
        userTask.setUtime(new Date());
        userTask.update();
        TaskService.me.addUserTaskRecord(uid, beforeCoin, coinCount, afterCoin);
    }
}
