package com.ruixuan.isc.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.Subscribe;
import com.kuaidi100.sdk.contant.ApiInfoConstant;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.request.SubscribeParam;
import com.kuaidi100.sdk.request.SubscribeParameters;
import com.kuaidi100.sdk.request.SubscribeReq;
import com.ruixuan.common.core.domain.entity.SysUser;
import com.ruixuan.common.utils.Check;
import com.ruixuan.common.utils.DateUtils;
import com.ruixuan.common.utils.PageUtils;
import com.ruixuan.isc.entity.KuaishouItemCollectSampleExpress;
import com.ruixuan.isc.entity.KuaishouItemCollectSampleLog;
import com.ruixuan.isc.entity.KuaishouItemCollectSamples;
import com.ruixuan.isc.mapper.KuaishouItemCollectSamplesMapper;
import com.ruixuan.isc.service.IKuaishouItemCollectSamplesService;
import com.ruixuan.isc.service.IKuaishouPromoterService;
import com.ruixuan.isc.service.ISupplyChainService;
import com.ruixuan.system.service.ISysDeptService;
import com.ruixuan.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2023-02-08
 */
@Service
public class KuaishouItemCollectSamplesServiceImpl implements IKuaishouItemCollectSamplesService {
    @Autowired
    private KuaishouItemCollectSamplesMapper kuaishouItemCollectSamplesMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IKuaishouPromoterService promoterService;

    @Autowired
    private ISupplyChainService supplyChainService;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public KuaishouItemCollectSamples selectKuaishouItemCollectSamplesById(Long id) {
        return kuaishouItemCollectSamplesMapper.selectKuaishouItemCollectSamplesById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param requestMap 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<KuaishouItemCollectSamples> selectKuaishouItemCollectSamplesList(Map<String, Object> requestMap) {
        List<KuaishouItemCollectSamples> kuaishouItemCollectSamples = kuaishouItemCollectSamplesMapper.selectKuaishouItemCollectSamplesList(requestMap);
        Map<String, JSONObject> dataMap = new HashMap<>();
        if (!Check.isNull(kuaishouItemCollectSamples)) {
            Map<String, String> map = new HashMap<>();
            for (KuaishouItemCollectSamples samples : kuaishouItemCollectSamples) {
                map.put(samples.getPromoterId() + "", samples.getPromoterId() + "");
            }
            List<JSONObject> promoterList = kuaishouItemCollectSamplesMapper.selectPromoterInfo(map);
            for (int i = 0; i < promoterList.size(); i++) {
                JSONObject jsonObject = promoterList.get(i);
                dataMap.put(jsonObject.getString("promoterId"), jsonObject);
            }
        }
        if (!Check.isNull(kuaishouItemCollectSamples)) {
            for (KuaishouItemCollectSamples samples : kuaishouItemCollectSamples) {
                String promoterId = samples.getPromoterId();
                JSONObject jsonObject = dataMap.get(promoterId);
                if (!Check.isNull(jsonObject)) {
                    samples.setValidAmount(jsonObject.getLong("validAmount"));
                    samples.setValidOrderNum(jsonObject.getLong("validOrderNum"));
                }
            }
        }
        return kuaishouItemCollectSamples;
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param kuaishouItemCollectSamples 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertKuaishouItemCollectSamples(KuaishouItemCollectSamples kuaishouItemCollectSamples) {
        kuaishouItemCollectSamples.setCreateTime(DateUtils.getNowDate());
        return kuaishouItemCollectSamplesMapper.insertKuaishouItemCollectSamples(kuaishouItemCollectSamples);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param kuaishouItemCollectSamples 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateKuaishouItemCollectSamples(KuaishouItemCollectSamples kuaishouItemCollectSamples) {
        kuaishouItemCollectSamples.setUpdateTime(DateUtils.getNowDate());
        return kuaishouItemCollectSamplesMapper.updateKuaishouItemCollectSamples(kuaishouItemCollectSamples);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteKuaishouItemCollectSamplesByIds(Long[] ids) {
        return kuaishouItemCollectSamplesMapper.deleteKuaishouItemCollectSamplesByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteKuaishouItemCollectSamplesById(Long id) {
        return kuaishouItemCollectSamplesMapper.deleteKuaishouItemCollectSamplesById(id);
    }


    @Override
    public JSONObject preview(Long userId, String nickName, JSONArray itemIds, JSONArray ids) {
        JSONObject previewJson = new JSONObject();
        List<JSONObject> itemList = kuaishouItemCollectSamplesMapper.getItemList(itemIds);
        Map<Long, JSONObject> itemMap = new HashMap<>();
        for (int i = 0; i < itemList.size(); i++) {
            JSONObject itemJson = itemList.get(i);
            itemMap.put(itemJson.getLong("itemId"), itemJson);
        }
        Map<Long, JSONObject> promoterMap = new HashMap<>();
        List<JSONObject> promoterList = kuaishouItemCollectSamplesMapper.promoterList(ids);
        for (int i = 0; i < promoterList.size(); i++) {
            JSONObject promoterJson = promoterList.get(i);
            promoterMap.put(promoterJson.getLong("id"), promoterJson);
        }
        Integer sampleReceivedCount = 0;
        List<JSONObject> samples = new ArrayList<>();
        for (int i = 0; i < itemIds.size(); i++) {
            Long itemId = itemIds.getLong(i);
            JSONObject itemJson = itemMap.get(itemId);

            for (int j = 0; j < ids.size(); j++) {
                Long id = ids.getLong(j);
                JSONObject promoterJson = promoterMap.get(id);
                if (Check.isNull(promoterJson)) {
                    continue;
                }

                Long relateId = itemJson.getLong("relateId");
                String promoterId = promoterJson.getString("promoterId");
                Integer count = kuaishouItemCollectSamplesMapper.checkByRelateIdAndPromoterId(relateId, promoterId);
                if (count > 0) {
                    sampleReceivedCount++;
                    continue;
                }
                Integer itemMediaId = itemJson.getInteger("mediaId");
                Integer promoterMediaId = promoterJson.getInteger("mediaId");
                if (itemMediaId != promoterMediaId) {
                    continue;
                }
                JSONObject sampleJson = new JSONObject();
                sampleJson.put("mediaId", itemMediaId);
                sampleJson.put("itemId", itemJson.getLong("itemId"));
                sampleJson.put("itemTitle", itemJson.getString("itemTitle"));
                sampleJson.put("itemPrice", itemJson.getLong("itemPrice"));
                sampleJson.put("itemImgUrl", itemJson.getString("itemImgUrl"));
                sampleJson.put("commissionRate", itemJson.getLong("commissionRate"));
                sampleJson.put("regimentalPromotion", itemJson.getLong("regimentalPromotion"));
                sampleJson.put("itemCreateId", itemJson.getLong("userId"));
                sampleJson.put("itemCreateName", itemJson.getString("userName"));
                sampleJson.put("collectSampleId", userId);
                sampleJson.put("collectSampleName", nickName);

                sampleJson.put("promoterId", promoterId);
                sampleJson.put("promoterNickName", promoterJson.getString("promoterNickName"));
                sampleJson.put("promoterPhone", promoterJson.getString("promoterPhone"));
                sampleJson.put("promoterAddress", promoterJson.getString("promoterAddress"));
                sampleJson.put("consignee", promoterJson.getString("consignee"));
                sampleJson.put("promoterUrl", promoterJson.getString("promoterUrl"));
                sampleJson.put("collectSampleStatus", 1);
                sampleJson.put("collectSampleDesc", "待招商审核");
                samples.add(sampleJson);
            }
            previewJson.put("sampleReceivedCount", sampleReceivedCount);
            previewJson.put("samples", samples);
        }


        return previewJson;
    }

    @Override
    public void batchAdd(JSONArray temCollectSamples) {
        List<KuaishouItemCollectSamples> adds = new ArrayList<>();
        for (int i = 0; i < temCollectSamples.size(); i++) {
            JSONObject sampleJson = temCollectSamples.getJSONObject(i);
            KuaishouItemCollectSamples sample = new KuaishouItemCollectSamples();
            Long itemId = sampleJson.getLong("itemId");
            String promoterId = sampleJson.getString("promoterId");
            Integer check = kuaishouItemCollectSamplesMapper.check(itemId, promoterId);
            if (check > 0) {
                continue;
            }
            sample.setItemId(itemId);
            sample.setItemTitle(sampleJson.getString("itemTitle"));
            sample.setItemPrice(sampleJson.getLong("itemPrice"));
            sample.setItemImgUrl(sampleJson.getString("itemImgUrl"));
            sample.setItemDesc(sampleJson.getString("itemDesc"));
            sample.setCommissionRate(sampleJson.getLong("commissionRate"));
            sample.setRegimentalPromotion(sampleJson.getLong("regimentalPromotion"));
            sample.setSampleCount(sampleJson.getInteger("sampleCount"));
            sample.setSampleRequirement(sampleJson.getString("sampleRequirement"));
            sample.setItemCreateId(sampleJson.getLong("itemCreateId"));
            sample.setItemCreateName(sampleJson.getString("itemCreateName"));
            sample.setCollectSampleId(sampleJson.getLong("collectSampleId"));
            sample.setCollectSampleName(sampleJson.getString("collectSampleName"));
            sample.setPartnerRecommendText(sampleJson.getString("partnerRecommendText"));
            sample.setPromoterId(promoterId);
            sample.setPromoterPhone(sampleJson.getString("promoterPhone"));
            sample.setPromoterAddress(sampleJson.getString("promoterAddress"));
            sample.setConsignee(sampleJson.getString("consignee"));
            sample.setCollectSampleStatus(sampleJson.getInteger("collectSampleStatus"));
            sample.setCollectSampleDesc(sampleJson.getString("collectSampleDesc"));
            sample.setPromoterNickName(sampleJson.getString("promoterNickName"));
            sample.setPromoterUrl(sampleJson.getString("promoterUrl"));
            sample.setMediaId(sampleJson.getInteger("mediaId"));
            String sampleVoucher = sampleJson.getString("sampleVoucher");
            if (!Check.isNull(sampleVoucher)) {
                sample.setSampleVoucher(sampleVoucher);
                sample.setSampleVoucherStatus(2);
            } else {
                sample.setSampleVoucherStatus(1);
            }
            adds.add(sample);
        }
        if (!Check.isNull(adds)) {
            kuaishouItemCollectSamplesMapper.batchAdd(adds);
        }

    }

    @Override
    public void subscribe(Long id, String courierNumber, String code) throws Exception {
        KuaishouItemCollectSamples samples = kuaishouItemCollectSamplesMapper.selectKuaishouItemCollectSamplesById(id);
        SubscribeParameters subscribeParameters = new SubscribeParameters();
        subscribeParameters.setCallbackurl("http://ruixuan.api.tjyourong.com.cn/itemCollectSamples/callback");
        subscribeParameters.setPhone(samples.getPromoterPhone());
        SubscribeParam subscribeParam = new SubscribeParam();
        subscribeParam.setParameters(subscribeParameters);
        subscribeParam.setCompany(code);
        subscribeParam.setNumber(courierNumber);
        subscribeParam.setKey("BPEQUJxB9244");
        SubscribeReq subscribeReq = new SubscribeReq();
        subscribeReq.setSchema(ApiInfoConstant.SUBSCRIBE_SCHEMA);
        subscribeReq.setParam(new Gson().toJson(subscribeParam));
        IBaseClient subscribe = new Subscribe();
        JSONObject jsonObject = JSONObject.parseObject(subscribe.execute(subscribeReq).getBody());
        String returnCode = jsonObject.getString("returnCode");
        KuaishouItemCollectSamples updateSample = new KuaishouItemCollectSamples();
        updateSample.setId(id);
        if ("200".equals(returnCode)) {
            updateSample.setCollectSampleDesc("快递推送订阅成功");
        } else {
            updateSample.setCollectSampleStatus(3);
            updateSample.setCollectSampleDesc("快递推送订阅失败，失败原因：" + jsonObject.getString("message"));
        }
        kuaishouItemCollectSamplesMapper.updateKuaishouItemCollectSamples(updateSample);
    }

    @Override
    public void updateByNum(KuaishouItemCollectSamples updateSample) {
        kuaishouItemCollectSamplesMapper.updateByNum(updateSample);
    }

    @Override
    public void replaceExpress(KuaishouItemCollectSampleExpress express) {
        kuaishouItemCollectSamplesMapper.replaceExpress(express);
    }

    @Override
    public JSONObject getDetail(Long id) {
        JSONObject json = new JSONObject();
        KuaishouItemCollectSamples sample = kuaishouItemCollectSamplesMapper.selectKuaishouItemCollectSamplesById(id);
        KuaishouItemCollectSampleLog log = new KuaishouItemCollectSampleLog();
        log.setCollectSampleStatus(1);
        log.setUserId(sample.getCollectSampleId());
        log.setUserName(sample.getCollectSampleName());
        log.setSampleId(sample.getId());
        log.setCreateTime(sample.getCreateTime());
        log.setUpdateTime(sample.getCreateTime());
        kuaishouItemCollectSamplesMapper.insertLog(log);
        json.put("sample", sample);
        if (!Check.isNull(sample.getCourierNumber())) {
            KuaishouItemCollectSampleExpress express = kuaishouItemCollectSamplesMapper.getExpress(sample.getCourierNumber());
            if (!Check.isNull(express)) {
                json.put("express", express);
            }
        }
        List<KuaishouItemCollectSampleLog> logs = kuaishouItemCollectSamplesMapper.getLogList(id);
        if (!Check.isNull(logs)) {
            json.put("logs", logs);
        }

        return json;
    }

    @Override
    public Integer getStatusByCourierNumbe(String nu) {
        return kuaishouItemCollectSamplesMapper.getStatusByCourierNumbe(nu);
    }

    @Override
    public JSONObject courierNumberInfo(String courierNumber) {
        return kuaishouItemCollectSamplesMapper.courierNumberInfo(courierNumber);
    }

    @Override
    public void insertLog(KuaishouItemCollectSampleLog sampleLog) {
        kuaishouItemCollectSamplesMapper.insertLog(sampleLog);
    }

    @Override
    public void cleanLogs(Long id, Integer status) {
        kuaishouItemCollectSamplesMapper.cleanLogs(id, status);
    }

    @Override
    public List<JSONObject> exportCollectSamples(Map<String, Object> requestMap) {
        return kuaishouItemCollectSamplesMapper.exportCollectSamples(requestMap);

    }

    @Override
    public JSONObject getCollectSampleInfo(Long itemId) {
        return kuaishouItemCollectSamplesMapper.getCollectSampleInfo(itemId);
    }

    @Override
    public JSONObject getCopyInfo(String promoterId) {
        JSONObject returnJson = kuaishouItemCollectSamplesMapper.promoterInfo(promoterId);
        return returnJson;
    }

    @Override
    public Long getItemIdById(Long id) {
        return kuaishouItemCollectSamplesMapper.getItemIdById(id);
    }


    @Override
    public JSONObject getPersonalInfo(Long userId, String type) {
        String roleKey = userService.getRoleKeyByUserId(userId);
        List<Long> userList = null;
        if ("courtshipManager".equals(roleKey) || "bdManager".equals(roleKey) || "associationManager".equals(roleKey)) {
            Long deptId = deptService.getDeptIdByUserId(userId);
            userList = deptService.getDeptUserListByDeptId(deptId);
        } else if ("supplyChainAdmin".equals(roleKey)) {
            //社群查看所有 all
            userList = null;
        } else {
            userList = Arrays.asList(userId);
        }
        int userType = 1;
        if (!"1".equals(type)) {
            userType = 2;
        }
        JSONObject returnJson = new JSONObject();
        JSONObject data = new JSONObject();
        SysUser sysUser = userService.selectUserById(userId);
        if (Check.isNotNull(sysUser)) {
            data.put("userName", sysUser.getNickName());
        }
        Integer status = 1; //待审核领样数
        data.put("toBeReviewed", kuaishouItemCollectSamplesMapper.getSampleCountByUserId(userList, userType, status));
        status = 3;//待发货领样数
        data.put("toBeShipped", kuaishouItemCollectSamplesMapper.getSampleCountByUserId(userList, userType, status));
        status = 6;//作业上传成功待招商审核
        data.put("toBeUploaded", kuaishouItemCollectSamplesMapper.getSampleCountByUserId(userList, userType, status));
        returnJson.put("code", 0);
        returnJson.put("message", "调用成功");
        returnJson.put("data", data);
        return returnJson;
    }

    @Override
    public JSONObject getOrderData(Long userId, String startDate, String endDate, String type, String mediaId) {
        String roleKey = userService.getRoleKeyByUserId(userId);
        List<Long> userList = null;
        if ("courtshipManager".equals(roleKey) || "bdManager".equals(roleKey)) {
            Long deptId = deptService.getDeptIdByUserId(userId);
            userList = deptService.getDeptUserListByDeptId(deptId);
        } else if (roleKey.contains("association") || "supplyChainAdmin".equals(roleKey)) {
            //社群查看所有 all
            userList = null;
        } else {
            userList = Arrays.asList(userId);
        }

        JSONObject returnJson = new JSONObject();
        returnJson.put("code", 0);
        returnJson.put("message", "调用成功");
        if ("1".equals(type)) {
            returnJson.put("data", getOrderDataByChannel(userList, startDate, endDate, mediaId));
        } else {
            returnJson.put("data", getOrderDataByAttractInvestment(userList, startDate, endDate, mediaId));
        }
        return returnJson;
    }

    //渠道数据
    private JSONObject getOrderDataByChannel(List<Long> userList, String startDate, String endDate, String mediaId) {
        JSONObject data = new JSONObject();
        List<String> promoterIds = null;
        if (Check.isNotNull(userList)) {
            if ("2".equals(mediaId)) {
                promoterIds = promoterService.selectPromoterIdListByTime(userList, DateUtils.strDateToInt(startDate), DateUtils.strDateToInt(endDate));
            } else {
                promoterIds = promoterService.selectPromoterIdList(userList, mediaId);
            }
            if (Check.isNull(promoterIds)) {
                return data;
            }
        }
        JSONObject sample = kuaishouItemCollectSamplesMapper.queryTheNumberOfCompletedJobs(promoterIds, startDate, endDate, mediaId);

        data.put("completeCount", sample.getInteger("completeCount"));//完成作业数
        data.put("completeRate", sample.getString("completeRate"));//合格作业率
        JSONObject order = new JSONObject();

        if ("1".equals(mediaId)) {
            order = supplyChainService.selectOrderInfoBytedance(promoterIds, DateUtils.strDateToInt(startDate), DateUtils.strDateToInt(endDate));
        } else {
            order = supplyChainService.selectOrderInfo(promoterIds, startDate, endDate);
        }
        data.put("allNumber", order.getInteger("allNumber"));//订单总数
        data.put("promoterCount", order.getInteger("promoterCount"));//达人总数
        data.put("validOrderNUm", order.getInteger("validOrderNUm"));//有效订单数
        data.put("inValidOrderNUm", order.getInteger("allNumber") - order.getInteger("validOrderNUm"));//失效订单数
        data.put("orderAmount", order.getInteger("orderAmount"));//订单金额
        data.put("regimentalPromotionAmount", order.getInteger("regimentalPromotionAmount"));//预估服务费
        data.put("baseAmount", order.getInteger("baseAmount"));//累计货贷基数

        Date date = new Date();
        //当前小时
        Integer hour = DateUtils.getNowHour() - 1;
        //当天
        String today = DateUtils.getNowDateStr();
        //昨天
        String yesterday = DateUtils.getSubtractTime(date, 1);
        //上周的同一天（上个近七天的结束日期）
        String todayOfLastWeek = DateUtils.getSubtractTime(date, 7);

        //当天数据
        JSONObject toData = getOrderRate(today, today, hour, promoterIds, null, mediaId);

        //昨日数据
        JSONObject yesData = getOrderRate(yesterday, yesterday, hour, promoterIds, null, mediaId);

        //上周当日数据
        JSONObject weeklyDayData = getOrderRate(todayOfLastWeek, todayOfLastWeek, hour, promoterIds, null, mediaId);

        //日环比 (今天-昨天)/昨天*100%
        data.put("dateOrderRate", getOrderRateValue(toData, yesData));
        data.put("dateAmountRate", getAmountRateValue(toData, yesData));

        //周同比
        data.put("monthOrderRate", getOrderRateValue(toData, weeklyDayData));
        data.put("monthAmountRate", getAmountRateValue(toData, weeklyDayData));

        JSONObject inDayData = null;
        JSONObject lastDayData = null;
        if (startDate.equals(endDate) && startDate.equals(today)) {
            //当前近七天的开始日期
            String start = DateUtils.getSubtractTime(date, 6);
            //当前近七天的数据
            inDayData = getOrderRate(start, today, hour, promoterIds, null, mediaId);
            //上个近七天的开始日期
            String lastStart = DateUtils.getSubtractTime(date, 13);
            //上个近七天的数据
            lastDayData = getOrderRate(lastStart, todayOfLastWeek, hour, promoterIds, null, mediaId);
        } else if (startDate.equals(endDate) && !startDate.equals(today)) {
            // startDate 环比 startDate的前一天
            inDayData = getOrderRate(startDate, startDate, 23, promoterIds, null, mediaId);
            // startDate -1
            String lastDay = DateUtils.getSubtractTime(DateUtils.parseDate(startDate), 1);
            lastDayData = getOrderRate(lastDay, lastDay, 23, promoterIds, null, mediaId);
        } else if (!startDate.equals(endDate) && !endDate.equals(today)) {
            // startDate 环比 startDate的前一天
            inDayData = getOrderRate(startDate, endDate, 23, promoterIds, null, mediaId);
            int days = DateUtils.differentDaysByMillisecond(DateUtils.parseDate(startDate), DateUtils.parseDate(endDate)) + 1;
            String lastStart = DateUtils.getSubtractTime(DateUtils.parseDate(startDate), days);
            String lastEnd = DateUtils.getSubtractTime(DateUtils.parseDate(endDate), days);
            lastDayData = getOrderRate(lastStart, lastEnd, 23, promoterIds, null, mediaId);
        } else {
            inDayData = getOrderRate(startDate, endDate, hour, promoterIds, null, mediaId);
            int days = DateUtils.differentDaysByMillisecond(DateUtils.parseDate(startDate), DateUtils.parseDate(endDate)) + 1;
            String lastStart = DateUtils.getSubtractTime(DateUtils.parseDate(startDate), days);
            String lastEnd = DateUtils.getSubtractTime(DateUtils.parseDate(endDate), days);
            lastDayData = getOrderRate(lastStart, lastEnd, hour, promoterIds, null, mediaId);
        }
        //数据对比
        data.put("dataOrderRate", getOrderRateValue(inDayData, lastDayData));
        data.put("dataAmountRate", getAmountRateValue(inDayData, lastDayData));
        return data;
    }

    private JSONObject getOrderRate(String startDate, String endDate, int hour, List<String> promoterIds, List<Long> itemIds, String mediaId) {
        if ("1".equals(mediaId)) {
            Long startHourTemp = DateUtils.strDateToInt(startDate);
            Long endHourTemp = DateUtils.strDateToInt(endDate);
            return supplyChainService.selectOrderRateBytedance(promoterIds, itemIds, startHourTemp, endHourTemp);
        } else if ("2".equals(mediaId)) {
            Long startHourTemp = DateUtils.getStartLongTime(startDate); // startDate开始时间戳
            Long endHourTemp = DateUtils.getNowEndHourTemp(endDate, hour); // endDate结束时间戳
            return supplyChainService.selectOrderRate(promoterIds, itemIds, startHourTemp, endHourTemp);
        }
        return null;
    }

    private BigDecimal getOrderRateValue(JSONObject toData, JSONObject yesData) {
        BigDecimal allNumber = yesData.getBigDecimal("allNumber");
        if ((BigDecimal.ZERO).compareTo(allNumber) != 0) {
            return toData.getBigDecimal("allNumber").subtract(allNumber).divide(allNumber, 4, RoundingMode.HALF_UP);
        } else {
            return new BigDecimal(0);
        }
    }

    private BigDecimal getAmountRateValue(JSONObject toData, JSONObject yesData) {
        BigDecimal orderAmount = yesData.getBigDecimal("orderAmount");
        if ((BigDecimal.ZERO).compareTo(orderAmount) != 0) {
            return toData.getBigDecimal("orderAmount").subtract(orderAmount).divide(orderAmount, 4, RoundingMode.HALF_UP);
        } else {
            return new BigDecimal(0);
        }
    }

    //招商数据
    private JSONObject getOrderDataByAttractInvestment(List<Long> userList, String startDate, String endDate, String mediaId) {
        JSONObject data = new JSONObject();
        //查询登录人（创建人）的所有商品
        List<Long> itemIds = kuaishouItemCollectSamplesMapper.getItemIdsByCreateId(userList, mediaId);
        if (Check.isNotNull(itemIds)) {
            JSONObject order = null;
            if ("1".equals(mediaId)) {
                Long startHourTemp = DateUtils.strDateToInt(startDate);
                Long endHourTemp = DateUtils.strDateToInt(endDate);
                order = supplyChainService.selectOrderInfoByItemIdsBytedance(itemIds, startHourTemp, endHourTemp);
            } else {
                order = supplyChainService.selectOrderInfoByItemIds(itemIds, startDate, endDate);
            }
            data.put("sendCount", order.getInteger("sendCount"));//发货数
            data.put("sendRate", order.getString("sendRate"));//订单发货率
            data.put("allNumber", order.getInteger("allNumber"));//订单总数
            data.put("promoterCount", order.getInteger("promoterCount"));//达人总数
            data.put("validOrderNUm", order.getInteger("validOrderNUm"));//有效订单数
            data.put("inValidOrderNUm", order.getInteger("allNumber") - order.getInteger("validOrderNUm"));//失效订单数
            data.put("orderAmount", order.getInteger("orderAmount"));//订单金额
            data.put("regimentalPromotionAmount", order.getInteger("regimentalPromotionAmount"));//预估服务费
            data.put("baseAmount", order.getInteger("baseAmount"));//累计货贷基数

            Date date = new Date();
            //当前小时
            Integer hour = DateUtils.getNowHour() - 1;
            //当天
            String today = DateUtils.getNowDateStr();
            //昨天
            String yesterday = DateUtils.getSubtractTime(date, 1);
            //上周的同一天（上个近七天的结束日期）
            String todayOfLastWeek = DateUtils.getSubtractTime(date, 7);

            //当天数据
            JSONObject toData = getOrderRate(today, today, hour, null, itemIds, mediaId);

            //昨日数据
            JSONObject yesData = getOrderRate(yesterday, yesterday, hour, null, itemIds, mediaId);

            //上周当日数据
            JSONObject weeklyDayData = getOrderRate(todayOfLastWeek, todayOfLastWeek, hour, null, itemIds, mediaId);

            //日环比 (今天-昨天)/昨天*100%
            data.put("dateOrderRate", getOrderRateValue(toData, yesData));
            data.put("dateAmountRate", getAmountRateValue(toData, yesData));

            //周同比
            data.put("monthOrderRate", getOrderRateValue(toData, weeklyDayData));
            data.put("monthAmountRate", getAmountRateValue(toData, weeklyDayData));

            JSONObject inDayData = null;
            JSONObject lastDayData = null;
            if (startDate.equals(endDate) && startDate.equals(today)) {
                String start = DateUtils.getSubtractTime(date, 6); //当前近七天的开始日期
                //当前近七天的数据
                inDayData = getOrderRate(start, today, hour, null, itemIds, mediaId);

                String lastStart = DateUtils.getSubtractTime(date, 13); //上个近七天的开始日期
                //上个近七天的数据
                lastDayData = getOrderRate(lastStart, todayOfLastWeek, hour, null, itemIds, mediaId);
            } else if (startDate.equals(endDate) && !startDate.equals(today)) {
                // startDate 环比 startDate的前一天
                inDayData = getOrderRate(startDate, startDate, 23, null, itemIds, mediaId);
                // startDate -1
                String lastDay = DateUtils.getSubtractTime(DateUtils.parseDate(startDate), 1);
                lastDayData = getOrderRate(lastDay, lastDay, 23, null, itemIds, mediaId);
            } else if (!startDate.equals(endDate) && !endDate.equals(today)) {
                // startDate 环比 startDate的前一天
                inDayData = getOrderRate(startDate, endDate, 23, null, itemIds, mediaId);
                int days = DateUtils.differentDaysByMillisecond(DateUtils.parseDate(startDate), DateUtils.parseDate(endDate)) + 1;
                String lastStart = DateUtils.getSubtractTime(DateUtils.parseDate(startDate), days);
                String lastEnd = DateUtils.getSubtractTime(DateUtils.parseDate(endDate), days);
                lastDayData = getOrderRate(lastStart, lastEnd, 23, null, itemIds, mediaId);
            } else {
                inDayData = getOrderRate(startDate, endDate, hour, null, itemIds, mediaId);
                int days = DateUtils.differentDaysByMillisecond(DateUtils.parseDate(startDate), DateUtils.parseDate(endDate)) + 1;
                String lastStart = DateUtils.getSubtractTime(DateUtils.parseDate(startDate), days);
                String lastEnd = DateUtils.getSubtractTime(DateUtils.parseDate(endDate), days);
                lastDayData = getOrderRate(lastStart, lastEnd, hour, null, itemIds, mediaId);
            }
            //数据对比
            data.put("dataOrderRate", getOrderRateValue(inDayData, lastDayData));
            data.put("dataAmountRate", getAmountRateValue(inDayData, lastDayData));
        }
        return data;
    }

    @Override
    public JSONObject getDataAnalysis(Long userId, String startDate, String endDate, String type, String mediaId) {
        String roleKey = userService.getRoleKeyByUserId(userId);
        List<Long> userList = null;
        if ("courtshipManager".equals(roleKey) || "bdManager".equals(roleKey)) {
            Long deptId = deptService.getDeptIdByUserId(userId);
            userList = deptService.getDeptUserListByDeptId(deptId);
        } else if (roleKey.contains("association") || "supplyChainAdmin".equals(roleKey)) {
            //社群查看所有 all
            userList = null;
        } else {
            userList = Arrays.asList(userId);
        }

        JSONObject returnJson = new JSONObject();
        returnJson.put("code", 0);
        returnJson.put("message", "调用成功");
        if ("1".equals(type)) {
            returnJson.put("data", getDataAnalysisByChannel(userList, startDate, endDate, mediaId));
        } else {
            returnJson.put("data", getDataAnalysisByAttractInvestment(userList, startDate, endDate, mediaId));
        }
        return returnJson;
    }

    @Override
    public List<JSONObject> queryProductList(Map<String, Object> map) {
        PageUtils.startPage();
        return kuaishouItemCollectSamplesMapper.queryProductList(map);
    }

    @Override
    public List<JSONObject> exportProductList(Map<String, Object> map) {
        return kuaishouItemCollectSamplesMapper.queryProductList(map);
    }

    @Override
    public void batchProcess(JSONArray ids, Integer status) {
        kuaishouItemCollectSamplesMapper.batchProcess(ids, status);
    }

    @Override
    public void batchAddLogs(List<KuaishouItemCollectSampleLog> logs) {
        kuaishouItemCollectSamplesMapper.batchAddLogs(logs);
    }

    @Override
    public List<KuaishouItemCollectSamples> getListByPromoterId(String promoterId, Long userId) {
        return kuaishouItemCollectSamplesMapper.getListByPromoterId(promoterId, userId);
    }

    @Override
    public void checkAndUpdateStatus() {
        List<Long> ids = kuaishouItemCollectSamplesMapper.getAccordWithOrderQuantityList();
        if (Check.isNotNull(ids)) {
            kuaishouItemCollectSamplesMapper.updateByIds(ids);
        }
    }

    // 渠道—数据分析
    private JSONObject getDataAnalysisByChannel(List<Long> userList, String startDate, String endDate, String mediaId) {
        JSONObject data = new JSONObject();
        List<String> promoterIds = null;
        if (Check.isNotNull(userList)) {
            if ("2".equals(mediaId)) {
                promoterIds = promoterService.selectPromoterIdListByTime(userList, DateUtils.strDateToInt(startDate), DateUtils.strDateToInt(endDate));
            } else {
                promoterIds = promoterService.selectPromoterIdList(userList, mediaId);
            }
            if (Check.isNull(promoterIds)) {
                return data;
            }
        }
        if (Check.isNull(startDate) && Check.isNull(endDate)) {
            //当前月份第一天
            startDate = DateUtils.getFirstDayByMonth();
            //当天
            endDate = DateUtils.getNowDateStr();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("start", startDate);
        map.put("end", endDate);
        map.put("userList", userList);
        map.put("promoterIds", promoterIds);
        if ("1".equals(mediaId)) {
            map.put("startLong", Long.valueOf(startDate.replace("-", "")));
            map.put("endLong", Long.valueOf(endDate.replace("-", "")));
        } else {
            map.put("startLong", DateUtils.getStartLongTime(startDate));
            map.put("endLong", DateUtils.getEndLongTime(endDate));
        }
        List<JSONObject> list = null;
        if ("1".equals(mediaId)) {
            list = supplyChainService.getMonthOrderAmountBytedance(map);
        } else {

            list = supplyChainService.getMonthOrderAmount(map);
        }

        List<String> allDates = DateUtils.getAllDatesOfTwoTimes(startDate, endDate);
        if (Check.isNull(list) || list.size() != allDates.size()) {
            String orderAmountStr = JSONObject.toJSONString(list);
            for (String date : allDates) {
                if (!orderAmountStr.contains(date)) {
                    JSONObject obj = new JSONObject();
                    obj.put("date", date);
                    obj.put("orderAmount", 0);
                    obj.put("regimentalPromotionAmount", 0);
                    obj.put("promoterCount", 0);
                    obj.put("orderCount", 0);
                    obj.put("validOrderCount", 0);
                    list.add(obj);
                }
            }
        }
        //排序
        Collections.sort(list, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                return o1.getString("date").compareTo(o2.getString("date"));
            }
        });
        data.put("list", list);
        map.put("toStartLong", DateUtils.getStartLongTime(endDate));
        JSONObject amount = null;
        if ("1".equals(mediaId)) {
            amount = supplyChainService.getMonthOrderAmountTotalBytedance(map);
        } else {
            amount = supplyChainService.getMonthOrderAmountTotal(map);
        }

        if (Check.isNotNull(amount)) {
            data.put("orderAmount", amount.getInteger("orderAmount"));
            data.put("regimentalPromotionAmount", amount.getInteger("regimentalPromotionAmount"));
            data.put("orderAmountRate", amount.getString("orderAmountRate"));
            data.put("regimentalPromotionAmountRate", amount.getString("regimentalPromotionAmountRate"));
        }
        JSONObject promoter = promoterService.getgetMonthPromoterTotal(userList, startDate, endDate, mediaId);
        if (Check.isNotNull(promoter)) {
            data.put("promoterCount", promoter.getString("count"));
            data.put("promoterRate", promoter.getString("rate"));
        }
        return data;
    }

    // 招商—数据分析
    private JSONObject getDataAnalysisByAttractInvestment(List<Long> userList, String startDate, String endDate, String mediaId) {
        JSONObject data = new JSONObject();
        //查询登录人（创建人）的所有商品
        List<Long> itemIds = kuaishouItemCollectSamplesMapper.getItemIdsByCreateId(userList, mediaId);
        if (Check.isNotNull(itemIds)) {
            if (Check.isNull(startDate) && Check.isNull(endDate)) {
                //当前月份第一天
                startDate = DateUtils.getFirstDayByMonth();
                //当天
                endDate = DateUtils.getNowDateStr();
            }
            Map<String, Object> map = new HashMap<>();
            map.put("start", startDate);
            map.put("end", endDate);
            map.put("itemIds", itemIds);
            map.put("IntStart", DateUtils.strDateToInt(startDate));
            map.put("IntEnd", DateUtils.strDateToInt(endDate));
            map.put("startLong", DateUtils.getStartLongTime(startDate));
            map.put("toStartLong", DateUtils.getStartLongTime(endDate));
            map.put("endLong", DateUtils.getEndLongTime(endDate));
            List<JSONObject> list = null;
            if ("1".equals(mediaId)) {
                list = supplyChainService.getMonthOrderAmountByItemsBytedance(map);
            } else {
                list = supplyChainService.getMonthOrderAmountByItems(map);
                ;
            }
            List<String> allDates = DateUtils.getAllDatesOfTwoTimes(startDate, endDate);
            if (Check.isNull(list) || list.size() != allDates.size()) {
                String orderAmountStr = JSONObject.toJSONString(list);
                for (String date : allDates) {
                    if (!orderAmountStr.contains(date)) {
                        JSONObject obj = new JSONObject();
                        obj.put("date", date);
                        obj.put("orderAmount", 0);
                        obj.put("regimentalPromotionAmount", 0);
                        obj.put("orderCount", 0);
                        obj.put("validOrderCount", 0);
                        list.add(obj);
                    }
                }
            }
            //排序
            Collections.sort(list, new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    return o1.getString("date").compareTo(o2.getString("date"));
                }
            });
            data.put("list", list);
            JSONObject amount = null;
            if ("1".equals(mediaId)) {
                amount = supplyChainService.getMonthOrderAmountTotalByItemsBytedance(map);
            } else {
                amount = supplyChainService.getMonthOrderAmountTotalByItems(map);
            }
            if (Check.isNotNull(amount)) {
                data.put("orderAmount", amount.getInteger("orderAmount"));
                data.put("regimentalPromotionAmount", amount.getInteger("regimentalPromotionAmount"));
                data.put("orderAmountRate", amount.getString("orderAmountRate"));
                data.put("regimentalPromotionAmountRate", amount.getString("regimentalPromotionAmountRate"));
                data.put("orderCount", amount.getString("orderCount"));
                data.put("orderCountRate", amount.getString("orderCountRate"));
            }
        }
        return data;
    }

}

