package com.ytpm.service.xjlrl.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.ytpm.advertise.enums.AdPlatformTypeEnum;
import com.ytpm.advertise.enums.AdSourceTypeEnum;
import com.ytpm.agent.enums.UserStatusEnum;
import com.ytpm.app.model.YtDyzAdRecord;
import com.ytpm.app.model.YtDyzUser;
import com.ytpm.app.param.DyzAdRecordParam;
import com.ytpm.dao.xjlrl.XjlrlAdRecordMapper;
import com.ytpm.dao.xjlrl.XjlrlUserMapper;
import com.ytpm.feign.RiskFeign;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.StatusCode;
import com.ytpm.handle.CustomerException;
import com.ytpm.middle.view.AppRankingListVO;
import com.ytpm.middle.view.DashboardRankingListVO;
import com.ytpm.middle.view.DashboardRevenueVO;
import com.ytpm.middle.view.UserRankingListVO;
import com.ytpm.service.xjlrl.XjlrlAdService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;

@Service
public class XjlrlAdServiceImpl implements XjlrlAdService {
    @Autowired
    private XjlrlAdRecordMapper xjlAdRecordMapper;
    @Autowired
    private XjlrlUserMapper xjlUserMapper;
    @Qualifier("com.ytpm.feign.RiskFeign")
    @Autowired
    private RiskFeign riskFeign;

    @Value("${risk.config.banned.tips}")
    private String tips;

    /**
     * 保存广告记录
     */
    @Override
    @Transactional
    public Result<?> saveRecord(DyzAdRecordParam param) {
        YtDyzUser user = xjlUserMapper.selectPrimaryKey(param.getUserId());
        if(Objects.isNull(user)){
            return Result.resultOk(RepMessage.SAVE_SUCCESS);
        }
        if(!UserStatusEnum.NORMAL.getCode().equals(user.getUserStatus())){
            return new Result<>(StatusCode.ACCESS_ERR,"当前用户处于风控中");
        }
        saveRecordAndChangeUser(param, user);
        //调用风控广告校验
        if(AdSourceTypeEnum.rewarded_video.getAdSourceType() == param.getAdSourceType()){
            Result<?> result = riskFeign.checkAdRisk(user);
            if(result.getCode()!=200){
                return new Result<>(StatusCode.ACCESS_ERR, getTipsMsg());
            }
        }
        return Result.resultOk(RepMessage.SAVE_SUCCESS);
    }
    private String getTipsMsg(){
        String[] split = tips.split(",");
        return split[RandomUtil.randomInt(split.length)];
    }
    /**
     * 根据应用查询广告数量
     */
    @Override
    public Map<String, BigDecimal> getAdCount(String appIds) {
        Map<String, BigDecimal> map = new HashMap<>();
        //查询这些app的用户统计广告数量相加
        int adCount = xjlUserMapper.getAdCount(appIds);
        BigDecimal total = xjlUserMapper.getRevenueCount(appIds);
        map.put("adCount", BigDecimal.valueOf(adCount));
        map.put("expectRevenue", total);
        return map;
    }

    /**
     * 查询排行榜信息
     */
    @Override
    public DashboardRankingListVO queryRankingList(Integer sortBy, Integer limit) {
        //查询前五个应用名称 当日收益  用户数量
        List<AppRankingListVO> appRankingList = xjlUserMapper.getAppRanking(sortBy,limit);
        //查询前五个用户  所属应用  视频数 总收益 ecpm
        List<UserRankingListVO> userRankingList = xjlUserMapper.getUserRanking(sortBy,limit);
        return new DashboardRankingListVO(appRankingList,userRankingList);
    }

    /**
     *  TODO 查询各渠道应用收益分时统计
     */
    @Override
    public DashboardRevenueVO revenueStatics(String apkIds) {
        //查询出各应用的用户及收益数据
        List<String> appIdList = Arrays.asList(apkIds.split(","));
        // 由于子表数据庞大导致range查询低于const
        CountDownLatch countDownLatch = new CountDownLatch(appIdList.size());
        return null;
    }

    /**
     * 保存记录
     *  始终创建新的事务以保障子方法的独立事务
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void saveRecordAndChangeUser(DyzAdRecordParam param,YtDyzUser user) {
        //增加广告记录
        YtDyzAdRecord adRecord = new YtDyzAdRecord();
        if(Objects.isNull(param.getBeginTime())){
            param.setBeginTime(param.getFinishTime());
        }
        BeanUtils.copyProperties(param, adRecord);
        adRecord.setRecordId(IdUtil.fastSimpleUUID());
        adRecord.setNetworkName(AdPlatformTypeEnum.getDesc(Integer.parseInt(param.getNetworkFormId())));
        xjlAdRecordMapper.addOne(adRecord);
        //修改用户信息， 广告次数+1  总收益 + revenue
        YtDyzUser dyzUser = new YtDyzUser();
        dyzUser.setUserId(user.getUserId());
        dyzUser.setTotalVideo(Objects.isNull(user.getTotalVideo())?1:(user.getTotalVideo()+1));
        dyzUser.setTotalIncome(user.getTotalIncome().add(param.getRevenue()));
        xjlUserMapper.updateUser(dyzUser);
    }
}
