package cn.com.ctop.kuaishou.modules.report.service.impl;

import cn.com.ctop.kuaishou.modules.report.entity.NewMonitorInfo;
import cn.com.ctop.kuaishou.modules.report.mapper.NewMonitorMapper;
import cn.com.ctop.kuaishou.modules.report.service.NewMonitorService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

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

@Service
@Slf4j
public class NewMonitorServiceImpl implements NewMonitorService {

    @Resource
    NewMonitorMapper newMonitorMapper;


    /**
     * 同步快手新上监控数据
     *
     * @param
     * @return
     */
    @Async("calcThreadExecutor")
    public Result synchronousKuaiShouMonitor(String type, Long accId) {
        log.info("同步快手新上数据:{}", accId);
        Result result = new Result();
        List<Map> kuaiShouGroup = new ArrayList<>();
        List<Map> kuaiShouCampaign = new ArrayList<>();
        List<Map> TouTiaoCampaign = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (accId != null) {
            /*--------------------快手广告组-----------------------*/
            if (type.equals("0")) {
                //查询创建不满7天的快手组信息
                kuaiShouGroup = newMonitorMapper.getKuaiShouGroup(sdf.format(new Date()), String.valueOf(accId));
            } else if (type.equals("1")) {
                //查询当日快手组信息
                kuaiShouGroup = newMonitorMapper.getKuaiShouGroupNow(sdf.format(new Date()), String.valueOf(accId));
            } else {
                //查询全量快手组信息
                kuaiShouGroup = newMonitorMapper.getKuaiShouGroup(null, String.valueOf(accId));
            }
            //处理快手组数据
            if (!kuaiShouGroup.isEmpty()) {
                kuaiShouGroup.stream().forEach(obj -> {
                    if (obj != null) {
                        String unitId = obj.get("unitId") == null ? null : String.valueOf(obj.get("unitId"));
                        String afterTime = obj.get("afterTime") == null ? null : (String) obj.get("afterTime");
                        String accountId = obj.get("accountId") == null ? null : String.valueOf(obj.get("accountId"));
                        String accountName = obj.get("accountName") == null ? null : (String) obj.get("accountName");
                        String userName = obj.get("userName") == null ? null : (String) obj.get("userName");
                        String groupCreatTime = obj.get("groupCreatTime") == null ? null : (String) obj.get("groupCreatTime");
                        if (unitId != null && afterTime != null) {
                            BigDecimal groupCharge = newMonitorMapper.getGroupCharge(unitId, afterTime);
                            //大于500为有效广告组
                            String effective = "0";
                            if (groupCharge != null && groupCharge.compareTo(new BigDecimal(500)) == 1) {
                                //有效
                                effective = "1";
                            }
                            String effectiveResult = newMonitorMapper.getMonitorGroupByUnitId(unitId);
                            //判断是否存在
                            if (effectiveResult != null) {
                                if (!effectiveResult.equals(effective)) {
                                    //存在更新
                                    newMonitorMapper.updateMonitorGroupByUnitId(unitId, effective);
                                }

                            } else {
                                //不存在插入
                                newMonitorMapper.saveMonitorGroup(accountId, accountName, userName, unitId, groupCreatTime, "1", effective);
                            }
                        }
                    }
                });
            }


            /*---------------快手广告计划------------------*/
            if (type.equals("0")) {
                //查询创建不满7天的快手广告计划
                kuaiShouCampaign = newMonitorMapper.getKuaiShouCampaign(sdf.format(new Date()), String.valueOf(accId));
            } else if (type.equals("1")) {
                //查询当日快手广告计划
                kuaiShouCampaign = newMonitorMapper.getKuaiShouCampaignNow(sdf.format(new Date()), String.valueOf(accId));
            } else {
                //查询全量快手广告计划
                kuaiShouCampaign = newMonitorMapper.getKuaiShouCampaign(null, String.valueOf(accId));
            }
            //处理快手广告计划数据
            if (!kuaiShouCampaign.isEmpty()) {
                kuaiShouCampaign.stream().forEach(obj -> {
                    if (obj != null) {
                        String campaignId = obj.get("campaignId") == null ? null : String.valueOf(obj.get("campaignId"));
                        String afterTime = obj.get("afterTime") == null ? null : (String) obj.get("afterTime");
                        String accountId = obj.get("accountId") == null ? null : String.valueOf(obj.get("accountId"));
                        String accountName = obj.get("accountName") == null ? null : (String) obj.get("accountName");
                        String userName = obj.get("userName") == null ? null : (String) obj.get("userName");
                        String campaignCreatTime = obj.get("campaignCreatTime") == null ? null : (String) obj.get("campaignCreatTime");
                        if (campaignId != null && afterTime != null) {
                            BigDecimal campaignCharge = newMonitorMapper.getCampaignCharge(campaignId, afterTime);
                            //大于500为有效广告计划
                            String effective = "0";
                            if (campaignCharge != null && campaignCharge.compareTo(new BigDecimal(500)) == 1) {
                                //有效
                                effective = "1";
                            }
                            String effectiveResult = newMonitorMapper.getMonitorPlanByCampaignId(campaignId);
                            //判断是否存在
                            if (effectiveResult != null) {
                                if (!effectiveResult.equals(effective)) {
                                    //存在更新
                                    newMonitorMapper.updateMonitorPlanByCampaignId(campaignId, effective);
                                }
                            } else {
                                //不存在插入
                                newMonitorMapper.saveMonitorCampaign(accountId, accountName, userName, campaignId, campaignCreatTime, "1", effective);
                            }
                        }
                    }
                });
            }
        }


        return result;
    }


    /**
     * 同步头条新上监控数据
     *
     * @param
     * @return
     */
    public Result synchronousTouTiaoMonitor(String type, Long accId) {
        log.info("同步头条新上数据:{}", accId);
        Result result = new Result();
        List<Map> kuaiShouGroup = new ArrayList<>();
        List<Map> kuaiShouCampaign = new ArrayList<>();
        List<Map> TouTiaoCampaign = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (accId != null) {
            /*---------------头条广告计划------------------*/
            if (type.equals("0")) {
                //查询创建不满7天的头条广告计划
                TouTiaoCampaign = newMonitorMapper.getTouTiaoCampaign(sdf.format(new Date()), String.valueOf(accId));
            } else if (type.equals("1")) {
                //查询当日头条广告计划
                TouTiaoCampaign = newMonitorMapper.getTouTiaoCampaignNow(sdf.format(new Date()), String.valueOf(accId));
            } else {
                //查询全量头条广告计划
                TouTiaoCampaign = newMonitorMapper.getTouTiaoCampaign(null, String.valueOf(accId));
            }
            //处理快手广告计划数据
            if (!TouTiaoCampaign.isEmpty()) {
                TouTiaoCampaign.stream().forEach(obj -> {
                    if (obj != null) {
                        String campaignId = obj.get("campaignId") == null ? null : String.valueOf(obj.get("campaignId"));
                        String afterTime = obj.get("afterTime") == null ? null : (String) obj.get("afterTime");
                        String accountId = obj.get("accountId") == null ? null : String.valueOf(obj.get("accountId"));
                        String accountName = obj.get("accountName") == null ? null : (String) obj.get("accountName");
                        String userName = obj.get("userName") == null ? null : (String) obj.get("userName");
                        String campaignCreatTime = obj.get("campaignCreatTime") == null ? null : (String) obj.get("campaignCreatTime");
                        if (campaignId != null && afterTime != null) {
                            BigDecimal campaignCharge = newMonitorMapper.getCampaignChargeTouTiao(campaignId, afterTime);
                            //大于500为有效广告计划
                            String effective = "0";
                            if (campaignCharge != null && campaignCharge.compareTo(new BigDecimal(500)) == 1) {
                                //有效
                                effective = "1";
                            }
                            String effectiveResult = newMonitorMapper.getMonitorPlanByCampaignId(campaignId);
                            //判断是否存在
                            if (effectiveResult != null) {
                                if (!effectiveResult.equals(effective)) {
                                    //存在更新
                                    newMonitorMapper.updateMonitorPlanByCampaignId(campaignId, effective);
                                }
                            } else {
                                //不存在插入
                                newMonitorMapper.saveMonitorCampaign(accountId, accountName, userName, campaignId, campaignCreatTime, "0", effective);
                            }
                        }
                    }
                });
            }
        }

        return result;
    }


    /**
     * 查询快手组信息
     *
     * @param
     * @return
     */
    @Override
    public List<JSONObject> getKuaiShouGroupMessage(JSONArray array, String startDate, String endDate, String target) {
        return newMonitorMapper.getKuaiShouGroupMessage(array, startDate, endDate);
    }

    /**
     * 查询快手组新上和有效数量
     *
     * @param
     * @return
     */
    @Override
    public JSONObject getKuaiShouGroupSum(JSONArray array, String startDate, String endDate) {
        return newMonitorMapper.getKuaiShouGroupSum(array, startDate, endDate);
    }

    /**
     * 查询快手组时间轴数据
     *
     * @param
     * @return
     */
    @Override
    public List<JSONObject> getKuaiShouGroupMessageGroup(JSONArray array, String startDate, String endDate) {
        String group = "0";
        List<JSONObject> kuaiShouGroupMessageGroup = new ArrayList<>();
        try {
            if (DateUtils.isMoreSixMonth(startDate, endDate)) {
                group = "1";
            }
            kuaiShouGroupMessageGroup = newMonitorMapper.getKuaiShouGroupMessageGroup(array, startDate, endDate, group);
        } catch (Exception e) {
            log.info("查询数据错误:{}", e.toString());
        }

        return kuaiShouGroupMessageGroup;
    }

    @Override
    public List<JSONObject> getPlanMessage(JSONArray array, String startDate, String endDate, String target, String project) {
        return newMonitorMapper.getPlanMessage(array, startDate, endDate, project);
    }

    /**
     * 查询快手广告计划 新上和有效数量
     *
     * @param
     * @return
     */
    @Override
    public JSONObject getPlanSum(JSONArray array, String startDate, String endDate, String project) {
        return newMonitorMapper.getPlanSum(array, startDate, endDate, project);
    }

    @Override
    public List<JSONObject> getPlanMessageGroup(JSONArray array, String startDate, String endDate, String project) {
        String group = "0";
        List<JSONObject> planGroupMessageGroup = new ArrayList<>();
        try {
            if (DateUtils.isMoreSixMonth(startDate, endDate)) {
                group = "1";
            }
            planGroupMessageGroup = newMonitorMapper.getPlanMessageGroup(array, startDate, endDate, group, project);
        } catch (Exception e) {
            log.info("查询数据错误:{}", e.toString());
        }

        return planGroupMessageGroup;
    }

    @Override
    public List<JSONObject> getOperator(String userId, String userName) {
        List<JSONObject> list = new ArrayList<>();
        JSONObject ob = new JSONObject();
        ob.put("user_id", userId);
        ob.put("user_name", userName);
        list.add(ob);
        try {
            if (userId != null) {
                List<NewMonitorInfo> operator = newMonitorMapper.getOperator(userId);
                list.addAll(getAllNode(operator));
            }
        } catch (Exception e) {
            log.info("查询失败:{}", e.toString());
        }
        return list;
    }

    List<JSONObject> getAllNode(List<NewMonitorInfo> operator) {
        List<JSONObject> objects = new ArrayList<>();
        if (!operator.isEmpty()) {
            for (NewMonitorInfo newMonitorInfo : operator) {
                JSONObject js = new JSONObject();
                js.put("user_id", newMonitorInfo.getUser_id());
                js.put("user_name", newMonitorInfo.getUser_name());
                objects.add(js);
                if (newMonitorInfo.getChildren() != null && newMonitorInfo.getChildren().size() > 0) {
                    objects.addAll(getAllNode(newMonitorInfo.getChildren()));
                }
            }
        }
        return objects;
    }
}
