package org.jeecg.ctop.material.service.impl;

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.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.ctop.material.constants.Check;
import org.jeecg.ctop.material.entity.ManagerSaleValue;
import org.jeecg.ctop.material.mapper.ManagerSaleValueMapper;
import org.jeecg.ctop.material.service.IManagerSaleValueService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 分公司总经理&销售总监阶段性目标值
 *
 * @author jeecg-boot
 * 2022-04-14
 * @version V1.0
 */
@Service
public class ManagerSaleValueServiceImpl extends ServiceImpl<ManagerSaleValueMapper, ManagerSaleValue> implements IManagerSaleValueService {


    @Override
    public Result<Object> getCompany(String userId) {
        String roleCode = baseMapper.getRoleCodeByUserId(userId);
        List<JSONObject> companies = new ArrayList<>();
        if ("admin".equals(roleCode)) {
            return Result.ok(baseMapper.queryList());
        } else if ("saleDirector".equals(roleCode) || "CompanyManager".equals(roleCode)) {
            String name = baseMapper.getUserNameById(userId);
            if ("丁兆明".equals(name)) {
                companies = baseMapper.queryList();
                List<JSONObject> companie = new ArrayList<>();
                for (JSONObject company : companies) {
                    String companyId = company.getString("companyId");
                    //丁兆明可以查看 骄阳和华北的2个公司
                    if ("5e46b5dea3d740eeb8ff1a2895015a4b".equals(companyId) || "d57fecdcf7a94d009736d9c850731582".equals(companyId)) {
                        companie.add(company);
                    }
                }
                return Result.ok(companie);
            }
            return Result.ok(baseMapper.queryUserCompany(userId));
        } else if ("saleAm".equals(roleCode)) {
            List<JSONObject> list = baseMapper.queryUserCompany(userId);
            JSONObject c = new JSONObject();
            c.put("companyId", "5e46b5dea3d740eeb8ff1a2895015a4b");
            c.put("companyName", "北京骄阳数字科技有限公司");
            list.add(c);
            return Result.ok(list);
        } else {
            return Result.error("角色权限不足");
        }
    }

    @Override
    public Result<Object> getDayAndMonthlyCharges(String userId, String mediaId, String startTime, String endTime, String operate) throws ParseException {
        Result<Object> result = new Result<>();
        String roleCode = baseMapper.getRoleCodeByUserId(userId);
        List<String> oneUserIds = new ArrayList<>();
        List<String> twoUserIds = new ArrayList<>();
        //销售总监
        if ("saleDirector".equals(roleCode) || "saleAm".equals(roleCode)) {
            //丁兆明特殊处理
            if ("b161b7d9793942f980dbfe8c931cd1b0".equals(userId) || "228c45f913924639bf20c79ce5dadb16".equals(userId)) {
                //账户集合
                List<Long> accountIds = baseMapper.querySalesDirectorAccountIds(null, mediaId, null);
                if (Check.isNull(accountIds)) {
                    return Result.error("未查询到账户！");
                }
                JSONObject data = getManagerData(accountIds, userId, mediaId, null, startTime, endTime);
                return Result.ok(data);
            }
            //查询销售总监及旗下的人员 集
            List<String> saleTeaMber = baseMapper.querySaleDirctorItsTeamMember(userId);
            saleTeaMber.add(userId);
            //账户集合
            List<Long> accountIds = baseMapper.querySalesDirectorAccountIds(null, mediaId, saleTeaMber);
            if (Check.isNull(accountIds)) {
                return Result.error("未查询到账户！");
            }
            JSONObject data = getManagerData(accountIds, userId, mediaId, saleTeaMber, startTime, endTime);
            result = Result.ok(data);
            //分公司总经理
        } else if ("CompanyManager".equals(roleCode) || "admin".equals(roleCode)) {
            //账户集合
            List<Long> accountIds = baseMapper.querySalesDirectorAccountIds(null, mediaId, null);
            if (Check.isNull(accountIds)) {
                return Result.error("未查询到账户！");
            }
            JSONObject data = getManagerData(accountIds, userId, mediaId, null, startTime, endTime);
            result = Result.ok(data);
        } else {
            result = Result.error("该用户角色权限不足！");
        }
        return result;
    }


    private JSONObject getManagerData(List<Long> accountIds, String userId, String mediaId, List<String> saleTeaMber, String startTime, String endTime) throws ParseException {
        //当天日期
        String statDay = DateUtils.date2Str();
        //当前小时数
        Integer hour = DateUtils.getHour(DateUtils.formatDateTime());
        //本周一
        String weekFirstDay = DateUtils.getdateFromWeek(1);
        //本月第一天
        String monthFirstday = DateUtils.dateformat(DateUtils.initDateByMonth(), DateUtils.WEB_FORMAT);
        //前月第一天
        String lastMonthFirstday = DateUtils.lastMonthFirstDay(DateUtils.WEB_FORMAT);

        JSONObject result = null;
        String weekCharge = null;
        //运营一部：李超及其下级 李超 id：f6a6843879c949618e4a859140c8a127
        List<Long> oneAccountIds = null;
        String lichaoId = "f6a6843879c949618e4a859140c8a127";
        //运营二部：陈思宇及其下级 陈思宇id：4afe739502ae4258a18c36a000d7ff20,00d630a129e4487cba5427788a1f08ce
        List<Long> twoAccountIds = null;
        //1 头条
        if ("1".equals(mediaId)) {
            //查询当日消耗 + 环比
            result = baseMapper.queryTtTodayCharge(statDay, hour, saleTeaMber, null);
            //周消耗
            weekCharge = baseMapper.queryTtManydaysTotalCharge(weekFirstDay, statDay, saleTeaMber, null);
            //月消耗
            String monthCharge = baseMapper.queryTtManydaysTotalCharge(monthFirstday, statDay, saleTeaMber, null);
            result.put("weekCharge", new BigDecimal(weekCharge));
            result.put("monthCharge", new BigDecimal(monthCharge));
            //现金消耗 + 环比ROI  因为存在非本地账户，所以只能用本地账户查询现金消耗
            JSONObject realCharged = baseMapper.queryTtRealCharged(lastMonthFirstday, monthFirstday, statDay, accountIds, null);
            result.put("realCharged", realCharged.getBigDecimal("realCharged"));
            result.put("realChargedRoi", realCharged.getString("realChargedRoi"));

            long days = DateUtils.getDiscrepantDays(startTime, endTime) + 1;
            if (!startTime.equals(statDay)) {
                hour = 23;
            }
            JSONObject oneResult = baseMapper.queryTtTodayCharge2(startTime, endTime, hour, saleTeaMber, null, days);
            result.put("oneCharge", oneResult.getBigDecimal("totalCharge"));
            result.put("oneChargeRoi", oneResult.getString("chargeRoi"));

                /*//运营一部：李超及其下级 李超 id：f6a6843879c949618e4a859140c8a127
                oneAccountIds = baseMapper.querySalesDirectorAccountIds(companyId, mediaId, saleTeaMber, Arrays.asList(lichaoId));
                JSONObject oneResult = baseMapper.queryTtTodayCharge2(startTime, endTime, hour, oneAccountIds, companyId, days);
                result.put("oneCharge", oneResult.getBigDecimal("totalCharge"));
                result.put("oneChargeRoi", oneResult.getString("chargeRoi"));

                //运营二部：陈思宇及其下级 陈思宇id：4afe739502ae4258a18c36a000d7ff20
                twoAccountIds = baseMapper.querySalesDirectorAccountIds2(companyId, mediaId, saleTeaMber);
                JSONObject twoResult = baseMapper.queryTtTodayCharge2(startTime, endTime, hour, twoAccountIds, companyId, days);
                result.put("twoCharge", twoResult.getBigDecimal("totalCharge"));
                result.put("twoChargeRoi", twoResult.getString("chargeRoi"));

                JSONObject twoResult2 = baseMapper.queryTtTodayCharge3(startTime, endTime, mediaId, hour, companyId, days);
                result.put("twoCharge2", twoResult2.getBigDecimal("totalCharge"));
                result.put("twoChargeRoi2", twoResult2.getString("chargeRoi"));*/

        } else if ("2".equals(mediaId)) {
            result = baseMapper.queryKsTodayCharge(statDay, hour, saleTeaMber, null);
            //周消耗
            weekCharge = baseMapper.queryKsManydaysTotalCharge(weekFirstDay, statDay, saleTeaMber, null);
            //月消耗
            String monthCharge = baseMapper.queryKsManydaysTotalCharge(monthFirstday, statDay, saleTeaMber, null);
            result.put("weekCharge", new BigDecimal(weekCharge));
            result.put("monthCharge", new BigDecimal(monthCharge));
            //现金消耗 + 环比ROI
            JSONObject realCharged = baseMapper.queryKsRealCharged(lastMonthFirstday, monthFirstday, statDay, accountIds, null);
            result.put("realCharged", realCharged.getBigDecimal("realCharged"));
            result.put("realChargedRoi", realCharged.getString("realChargedRoi"));
            long days = DateUtils.getDiscrepantDays(startTime, endTime) + 1;
            if (!startTime.equals(statDay)) {
                hour = 23;
            }
            JSONObject oneResult = baseMapper.queryKsTodayCharge2(startTime, endTime, hour, saleTeaMber, null, days);
            result.put("oneCharge", oneResult.getBigDecimal("totalCharge"));
            result.put("oneChargeRoi", oneResult.getString("chargeRoi"));
                /*result.put("oneCharge", oneResult.getBigDecimal("totalCharge"));
                result.put("oneChargeRoi", oneResult.getString("chargeRoi"));
                //运营一部：李超及其下级 李超 id：f6a6843879c949618e4a859140c8a127
                oneAccountIds = baseMapper.querySalesDirectorAccountIds(companyId, mediaId, saleTeaMber, Arrays.asList(lichaoId));
                JSONObject oneResult = baseMapper.queryKsTodayCharge2(startTime, endTime, hour, oneAccountIds, companyId, days);
                result.put("oneCharge", oneResult.getBigDecimal("totalCharge"));
                result.put("oneChargeRoi", oneResult.getString("chargeRoi"));

                //运营二部：陈思宇及其下级 陈思宇id：4afe739502ae4258a18c36a000d7ff20,00d630a129e4487cba5427788a1f08ce
                //专查询 陈思宇组 并去除 郭浩和王雪莹账户
                twoAccountIds = baseMapper.querySalesDirectorAccountIds2(companyId, mediaId, saleTeaMber);
                JSONObject twoResult = baseMapper.queryKsTodayCharge2(startTime, endTime, hour, twoAccountIds, companyId, days);
                result.put("twoCharge", twoResult.getBigDecimal("totalCharge"));
                result.put("twoChargeRoi", twoResult.getString("chargeRoi"));

                JSONObject twoResult2 = baseMapper.queryKsTodayCharge3(startTime, endTime, mediaId, hour, companyId, days);
                result.put("twoCharge2", twoResult2.getBigDecimal("totalCharge"));
                result.put("twoChargeRoi2", twoResult2.getString("chargeRoi"));*/
        }
        result.put("weeklyGoalValue", baseMapper.getWeekly(userId, null, mediaId));
        result.put("monthlyGoalValue", baseMapper.getMonthly(userId, null, mediaId));
        return result;
    }


    private BigDecimal getBigDecimalVal(String afterCharge, BigDecimal todayCharge) {
        BigDecimal charge = new BigDecimal(afterCharge);
        return todayCharge.add(charge);
    }


    @Override
    public void setUpManagerSaleValue(ManagerSaleValue sale) throws Exception {
        QueryWrapper<ManagerSaleValue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("media_id", sale.getMediaId());
        queryWrapper.eq("user_id", sale.getUserId());
        ManagerSaleValue one = this.getOne(queryWrapper);
        if (Check.isNull(one)) {
            sale.setId(UUID.randomUUID().toString().replace("-", ""));
            this.save(sale);
        } else {
            if (!Check.isNull(sale.getWeeklyGoalValue())) {
                one.setWeeklyGoalValue(sale.getWeeklyGoalValue());
            }
            if (!Check.isNull(sale.getMonthlyGoalValue())) {
                one.setMonthlyGoalValue(sale.getMonthlyGoalValue());
            }
            this.updateById(one);
        }
    }

    @Override
    public Result<Object> getHomeCharges(String userId, String mediaId, String startTime, String endTime) throws ParseException {
        String roleCode = baseMapper.getRoleCodeByUserId(userId);
        JSONObject data = null;
        //销售总监
        if ("saleDirector".equals(roleCode) || "saleAm".equals(roleCode)) {
            //丁兆明特殊处理
            if ("b161b7d9793942f980dbfe8c931cd1b0".equals(userId) || "228c45f913924639bf20c79ce5dadb16".equals(userId)) {
                if (startTime.equals(endTime)) {
                    data = getDailyCharges(null, null, userId, mediaId, null, startTime);
                } else {
                    data = getManyDaysCharges(null, null, userId, mediaId, null, startTime, endTime);
                }
                return Result.ok(data);
            }
            //查询销售总监及旗下的人员 集
            List<String> saleTeaMber = baseMapper.querySaleDirctorItsTeamMember(userId);
            saleTeaMber.add(userId);
            if (startTime.equals(endTime)) {
                //消耗数据
                data = getDailyCharges("all", saleTeaMber, userId, mediaId, null, startTime);

            } else {
                data = getManyDaysCharges("all", saleTeaMber, userId, mediaId, null, startTime, endTime);
            }
            //分公司总经理
        } else if ("CompanyManager".equals(roleCode) || "admin".equals(roleCode)) {
            if (startTime.equals(endTime)) {
                data = getDailyCharges(null, null, userId, mediaId, null, startTime);
            } else {
                data = getManyDaysCharges(null, null, userId, mediaId, null, startTime, endTime);
            }
        } else {
            return Result.error("该用户角色权限不足！");
        }
        return Result.ok(data);
    }

    private JSONObject getManyDaysCharges(String type, List<String> saleTeaMber, String userId, String mediaId, String companyId, String startTime, String endTime) throws ParseException {
        Map<String, String> map = DateUtils.getStartEndTime(startTime, endTime);

        //下个周期的开始时间
        String lastTimeStart = map.get("lastTimeStart");
        //下个周期的结束时间
        String lastTimeEnd = map.get("lastTimeEnd");

        JSONObject result = null;
        //1 头条
        if ("1".equals(mediaId)) {
            //查询 消耗 + 环比
            result = baseMapper.queryTtManydaysChargeAndRoi(startTime, endTime, lastTimeStart, lastTimeEnd, saleTeaMber, companyId);
            List<JSONObject> list = baseMapper.queryTtManydaysCharge(startTime, endTime, saleTeaMber, companyId);
            result.put("list", list);
            //平台消耗
            if (type == null) {
                result.put("platformCharge", result.getString("totalCharge"));
                result.put("platformChargeRoi", result.getString("chargeRoi"));
            } else {
                JSONObject ptdata = baseMapper.queryTtManydaysChargeAndRoi(startTime, endTime, lastTimeStart, lastTimeEnd, null, companyId);
                result.put("platformCharge", ptdata.getString("totalCharge"));
                result.put("platformChargeRoi", ptdata.getString("chargeRoi"));
            }
        } else if ("2".equals(mediaId)) {
            result = baseMapper.queryKsManydaysChargeAndRoi(startTime, endTime, lastTimeStart, lastTimeEnd, saleTeaMber, companyId);
            List<JSONObject> list = baseMapper.queryKsManydaysCharge(startTime, endTime, saleTeaMber, companyId);
            result.put("list", list);
            //平台消耗
            if (type == null) {
                result.put("platformCharge", result.getString("totalCharge"));
                result.put("platformChargeRoi", result.getString("chargeRoi"));
            } else {
                JSONObject ptdata = baseMapper.queryKsManydaysChargeAndRoi(startTime, endTime, lastTimeStart, lastTimeEnd, null, companyId);
                result.put("platformCharge", ptdata.getString("totalCharge"));
                result.put("platformChargeRoi", ptdata.getString("chargeRoi"));
            }
        }
        return result;
    }


    private JSONObject getDailyCharges(String type, List<String> saleTeaMber, String userId, String mediaId, String companyId, String date) throws ParseException {
        //当前小时数
        Integer hour = DateUtils.getHour(DateUtils.formatDateTime());
        if (!date.equals(DateUtils.date2Str())) {
            hour = null;
        }
        JSONObject result = null;
        //1 头条
        if ("1".equals(mediaId)) {
            //查询当日消耗 + 环比
            result = baseMapper.queryTtTodayCharge(date, hour, saleTeaMber, companyId);
            List<JSONObject> list = baseMapper.queryTtHourList(date, saleTeaMber, companyId);
            result.put("list", list);
            //平台消耗
            if (type == null) {
                result.put("platformCharge", result.getString("totalCharge"));
                result.put("platformChargeRoi", result.getString("chargeRoi"));
            } else {
                JSONObject ptdata = baseMapper.queryTtTodayCharge(date, hour, null, companyId);
                result.put("platformCharge", ptdata.getString("totalCharge"));
                result.put("platformChargeRoi", ptdata.getString("chargeRoi"));
            }
        } else if ("2".equals(mediaId)) {
            result = baseMapper.queryKsTodayCharge(date, hour, saleTeaMber, companyId);
            List<JSONObject> list = baseMapper.queryKsHourList(date, saleTeaMber, companyId);
            result.put("list", list);
            //平台消耗
            if (type == null) {
                result.put("platformCharge", result.getString("totalCharge"));
                result.put("platformChargeRoi", result.getString("chargeRoi"));
            } else {
                JSONObject ptdata = baseMapper.queryKsTodayCharge(date, hour, null, companyId);
                result.put("platformCharge", ptdata.getString("totalCharge"));
                result.put("platformChargeRoi", ptdata.getString("chargeRoi"));
            }
        }
        return result;
    }

    @Override
    public PageInfo getProjectChargeTop(String userId, String mediaId, String startTime, String endTime, String operate, Integer pageNo, Integer pageSize) throws Exception {
        //账户集合
        List<Long> accountIds = null;
        //当天日期
        String today = DateUtils.formatDate(new Date());
        JSONObject data = null;
        String roleCode = baseMapper.getRoleCodeByUserId(userId);
        //销售总监
        if ("saleDirector".equals(roleCode) || "saleAm".equals(roleCode)) {
            //丁兆明特殊处理
            if ("b161b7d9793942f980dbfe8c931cd1b0".equals(userId) || "228c45f913924639bf20c79ce5dadb16".equals(userId)) {
                accountIds = baseMapper.querySalesDirectorAccountIds(null, mediaId, null);
                if (Check.isNull(accountIds)) {
                    throw new Exception("未查询到账户！");
                }
                if (startTime.equals(endTime) && today.equals(startTime)) {
                    return getProjectDailyCharges(null, accountIds, null, mediaId, startTime, null, pageNo, pageSize);
                } else if (startTime.equals(endTime)) {
                    return getProjectDailyCharges(null, accountIds, null, mediaId, startTime, startTime, pageNo, pageSize);
                } else {
                    return getProjectDailyCharges(null, accountIds, null, mediaId, startTime, endTime, pageNo, pageSize);
                }
            }
            //查询销售总监及旗下的人员 集
            List<String> saleTeaMber = baseMapper.querySaleDirctorItsTeamMember(userId);
            saleTeaMber.add(userId);
            accountIds = baseMapper.querySalesDirectorAccountIds(null, mediaId, saleTeaMber);
            if (startTime.equals(endTime) && today.equals(startTime)) {
                return getProjectDailyCharges(saleTeaMber, accountIds, null, mediaId, startTime, null, pageNo, pageSize);
            } else if (startTime.equals(endTime)) {
                return getProjectDailyCharges(saleTeaMber, accountIds, null, mediaId, startTime, startTime, pageNo, pageSize);
            } else {
                return getProjectDailyCharges(saleTeaMber, accountIds, null, mediaId, startTime, endTime, pageNo, pageSize);
            }
            //分公司总经理
        } else if ("CompanyManager".equals(roleCode) || "admin".equals(roleCode)) {
            accountIds = baseMapper.querySalesDirectorAccountIds(null, mediaId, null);
            if (Check.isNull(accountIds)) {
                throw new Exception("未查询到账户！");
            }
            if (startTime.equals(endTime) && today.equals(startTime)) {
                return getProjectDailyCharges(null, accountIds, null, mediaId, startTime, null, pageNo, pageSize);
            } else if (startTime.equals(endTime)) {
                return getProjectDailyCharges(null, accountIds, null, mediaId, startTime, startTime, pageNo, pageSize);
            } else {
                return getProjectDailyCharges(null, accountIds, null, mediaId, startTime, endTime, pageNo, pageSize);
            }
        } else {
            throw new Exception("该用户角色权限不足！");
        }
    }

    private PageInfo getProjectDailyCharges(List<String> saleTeaMber, List<Long> accountIds, String companyId, String mediaId, String startTime, String endTime, Integer pageNo, Integer pageSize) throws ParseException {
        Long days = 1L;
        Integer hour = DateUtils.getHour(DateUtils.formatDateTime());
        if (endTime == null) {
            endTime = startTime;
        } else {
            days = DateUtils.getDiscrepantDays(startTime, endTime) + 1;
            hour = 23;
        }
        //1 头条
        if ("1".equals(mediaId)) {
            Long total = baseMapper.queryTtHourProjectTopTotal(saleTeaMber, startTime, endTime, companyId);
            PageHelper.startPage(pageNo, pageSize, false);
            List<JSONObject> list = baseMapper.queryTtHourProjectTop(saleTeaMber, accountIds, startTime, endTime, days, hour, companyId);
            PageInfo pageInfo = new PageInfo(list);
            pageInfo.setTotal(total);
            return pageInfo;
        } else if ("2".equals(mediaId)) {
            Long total = baseMapper.queryKsHourProjectTopTotal(saleTeaMber, startTime, endTime, companyId);
            PageHelper.startPage(pageNo, pageSize, false);
            List<JSONObject> list = baseMapper.queryKsHourProjectTop(saleTeaMber, accountIds, startTime, endTime, days, hour, companyId);
            PageInfo pageInfo = new PageInfo(list);
            pageInfo.setTotal(total);
            return pageInfo;
        }
        return null;
    }
}
