package cn.com.ctop.toutiao.modules.report.utils;

import cn.com.ctop.common.module.utils.Check;
import com.alibaba.fastjson.JSONObject;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by JQ.bi on 2020.6.5
 */
public class LinkUtils {


    //数据对比,环比计算
    public static List<JSONObject> getCompareDate(List<JSONObject> beforeData, List<JSONObject> AfterData, String standard) {
        List<JSONObject> result = new ArrayList<>();
        for (int i = 0; i < beforeData.size(); i++) {
            JSONObject before = beforeData.get(i);
            String yesStat = String.valueOf(before.get(standard));
            //修改点记率 乱码
            String clickRate = before.getString("clickRate");
            if (!Check.isNull(clickRate)) {
//                String clickRate = new String(click, Charset.forName("UTF-8"));
                before.put("clickRate", clickRate);
            }
            AfterData.forEach(after -> {
                if ((String.valueOf(after.get(standard))).equals(yesStat)) {
                    //消耗较昨日环比
                    after.put("costProportion", countLink(after.getBigDecimal("cost"), before.getBigDecimal("cost")));
                    //展示量较昨日环比
                    after.put("showProportion", countLink(BigDecimal.valueOf(after.getLong("showNum")), BigDecimal.valueOf(before.getLong("showNum"))));
                    //点击量较昨日环比
                    after.put("photoClickProportion", countLink(BigDecimal.valueOf(after.getLong("click")), BigDecimal.valueOf(before.getLong("click"))));
                    if (after.getLong("convertNum") != null) {
                        after.put("convertNumProportion", countLink(BigDecimal.valueOf(after.getLong("convertNum")), BigDecimal.valueOf(before.getLong("convertNum"))));
                    }
                    //修改点记率 乱码
                    String aftClick = after.getString("clickRate");
                    if (!Check.isNull(aftClick)) {
//                        String afterCli = new String(aftClick, Charset.forName("UTF-8"));
                        after.put("clickRate", aftClick);
                    }
                    before.put("afterData", after);
                }
            });
            result.add(before);
        }
        return result;
    }

    //环比计算
    public static BigDecimal countLink(BigDecimal numA, BigDecimal numB) {
        BigDecimal link = new BigDecimal(0);
        if (numB.compareTo(BigDecimal.ZERO) != 0) {
            link = (numA.subtract(numB)).divide(numB, 4, RoundingMode.HALF_UP);
        }
        return link;
    }
}
