package org.jeecg.modules.bytedance.advertise.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.bytedance.advertise.entity.BytedanceVideoSlogenInfo;
import org.jeecg.modules.bytedance.advertise.mapper.BytedanceVideoSlogenInfoMapper;
import org.jeecg.modules.bytedance.advertise.service.IBytedanceVideoSlogenInfoService;
import org.jeecg.modules.bytedance.common.utils.Check;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 头条视频文案信息
 * @author jeecg-boot
 * 2021-04-19
 * @version V1.0
 */
@Service
public class BytedanceVideoSlogenInfoServiceImpl extends ServiceImpl<BytedanceVideoSlogenInfoMapper, BytedanceVideoSlogenInfo> implements IBytedanceVideoSlogenInfoService {
    @Resource
    BytedanceVideoSlogenInfoMapper bytedanceVideoSlogenInfoMapper;


    @Override
    public void insertSlogans(Long projectId, String videoCode, JSONArray slogans,String userId){
        if(null==slogans||slogans.isEmpty()){
            return;
        }
        for(int i=0;i<slogans.size();i++){
            JSONObject sloganObject = slogans.getJSONObject(i);
            String title = sloganObject.getString("title");
            title = title.replaceAll("\\{\\{","{");
            title = title.replaceAll("\\}\\}","}");
            String creativeWordIds = Check.isNull(sloganObject.getJSONArray("creative_word_ids")) ? "" : sloganObject.getJSONArray("creative_word_ids").toJSONString();
            BytedanceVideoSlogenInfo slogenInfo = new BytedanceVideoSlogenInfo(projectId,videoCode,title,userId,creativeWordIds);
            this.save(slogenInfo);
        }
    }

    /**
     * 根据账户 和 文案数量 查询 指定文案
     * @param code 素材code
     * @param status 状态
     * @param copywritingNumber 文案数量
     * @return
     */
    @Override
    public List<BytedanceVideoSlogenInfo> listByParams(String code, Integer status,Integer copywritingNumber) {
        QueryWrapper<BytedanceVideoSlogenInfo>queryWrapper =new QueryWrapper<>();
        if(!Check.isNull(code)){
            queryWrapper.eq("video_code",code);
        }
        if(!Check.isNull(status)){
            queryWrapper.eq("status",status);
        }
        queryWrapper.orderByDesc("id");

        if (!Check.isNull(copywritingNumber)){
            queryWrapper.last("limit "+copywritingNumber);
        }

        return this.list(queryWrapper);
    }
    @Override
    public Result getVideoSlogenReport(String userId, String projectId,String keyWord,Integer status, String startTime, String endTime, Integer pageNum, Integer pageSize){

        List<String> projectIdList = new ArrayList<>();
        //查询普通用户的全量查询，当前用户所有项目
        if(Check.isNull(projectId)){
            projectIdList = bytedanceVideoSlogenInfoMapper.getProjectByUserId(userId);
        }else if(projectId == "admin"){//管理员的全量查询
            projectIdList = null;
        }else { //不论什么权限的用户的单独搜索一个项目
            projectIdList.add(projectId);
        }

        PageHelper.startPage(pageNum,pageSize);
        List<Map<String, Object>> videoSlogenReportList = bytedanceVideoSlogenInfoMapper.selectVideoSlogenReportByAccountIdAndTitle(projectIdList, keyWord, status, startTime, endTime);

        if(Check.isNull(videoSlogenReportList)){
            return Result.errorMsg("还没有此文案报表数据，请将此文案投放跑量！");
        }

        for (Map<String, Object> videoSlogenReportMap: videoSlogenReportList) {
            if(videoSlogenReportMap.get("count") == null){
                videoSlogenReportMap.put("count",0);
            }

            BigDecimal cost = new BigDecimal(Check.isNull(videoSlogenReportMap.get("cost")) ? "0" : videoSlogenReportMap.get("cost").toString());
            BigDecimal click = new BigDecimal(Check.isNull(videoSlogenReportMap.get("click")) ? "0" : videoSlogenReportMap.get("click").toString());
            BigDecimal showNum = new BigDecimal(Check.isNull(videoSlogenReportMap.get("showNum")) ? "0" : videoSlogenReportMap.get("showNum").toString());
            BigDecimal convertNum = new BigDecimal(Check.isNull(videoSlogenReportMap.get("convertNum")) ? "0" : videoSlogenReportMap.get("convertNum").toString());

            DecimalFormat decimalFormat = new DecimalFormat("0.00#");
            videoSlogenReportMap.put("cost", decimalFormat.format(cost));
            videoSlogenReportMap.put("click", click);
            videoSlogenReportMap.put("showNum", showNum);
            videoSlogenReportMap.put("convertNum", convertNum);

            //被除数不能为0
            if (StringUtils.equals("0",showNum.toString())){
                videoSlogenReportMap.put("costPerThousandShow", 0);
                videoSlogenReportMap.put("clickRate", 0);
            }else {
                BigDecimal costPerThousandShow = cost.multiply(new BigDecimal(1000)).divide(showNum, 2, BigDecimal.ROUND_HALF_UP);
                videoSlogenReportMap.put("costPerThousandShow", decimalFormat.format(costPerThousandShow));
                BigDecimal clickRate = click.multiply(new BigDecimal(100)).divide(showNum, 2, BigDecimal.ROUND_HALF_UP);
                videoSlogenReportMap.put("clickRate", decimalFormat.format(clickRate));
            }
            if (StringUtils.equals("0", convertNum.toString())) {
                videoSlogenReportMap.put("costConvert", 0);
            }else {
                BigDecimal costConvert = cost.divide(convertNum, 2, BigDecimal.ROUND_HALF_UP);
                videoSlogenReportMap.put("costConvert", decimalFormat.format(costConvert));
            }
            if (StringUtils.equals("0", click.toString())) {
                videoSlogenReportMap.put("costPerClick", 0);
                videoSlogenReportMap.put("convertRate", 0);
            }else {
                BigDecimal costPerClick = cost.divide(click, 2, BigDecimal.ROUND_HALF_UP);
                videoSlogenReportMap.put("costPerClick", decimalFormat.format(costPerClick));
                BigDecimal convertRate = convertNum.multiply(new BigDecimal(100)).divide(click,2,BigDecimal.ROUND_HALF_UP);
                videoSlogenReportMap.put("convertRate", decimalFormat.format(convertRate));
            }
        }

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(videoSlogenReportList);
        return Result.successMsg("数据加载成功。",pageInfo);
    }
    @Override
    public List<BytedanceVideoSlogenInfo> getVideoSlogenBySlogenAndProjectId(String slogen, Long projectId){
        return bytedanceVideoSlogenInfoMapper.getDataBySlogenAndProjectId(slogen, projectId);
    }
}
