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 companyId) throws ParseException {
        Result<Object> result = new Result<>();
        String roleCode = baseMapper.getRoleCodeByUserId(userId);
        Long weekly = baseMapper.getWeekly(userId, companyId, mediaId);
        Long monthly = baseMapper.getMonthly(userId, companyId, mediaId);
        //销售总监
        if ("saleDirector".equals(roleCode) || "saleAm".equals(roleCode)) {
            //丁兆明特殊处理
            if ("b161b7d9793942f980dbfe8c931cd1b0".equals(userId) || "228c45f913924639bf20c79ce5dadb16".equals(userId)) {
                //账户集合
                List<Long> accountIds = baseMapper.querySalesDirectorAccountIds(companyId, mediaId, null);
                if (Check.isNull(accountIds)) {
                    return Result.error("未查询到账户！");
                }
                JSONObject data = getManagerData(accountIds, userId, mediaId, companyId);
                data.put("weeklyGoalValue", weekly);
                data.put("monthlyGoalValue", monthly);
                return Result.ok(data);
            }
            //查询销售总监及旗下的人员 集
            List<String> saleTeaMber = baseMapper.querySaleDirctorItsTeamMember(userId);
            saleTeaMber.add(userId);
            //账户集合
            List<Long> accountIds = baseMapper.querySalesDirectorAccountIds(companyId, mediaId, saleTeaMber);
            if (Check.isNull(accountIds)) {
                return Result.error("未查询到账户！");
            }
            JSONObject data = getManagerData(accountIds, userId, mediaId, companyId);
            data.put("weeklyGoalValue", weekly);
            data.put("monthlyGoalValue", monthly);
            result = Result.ok(data);
            //分公司总经理
        } else if ("CompanyManager".equals(roleCode) || "admin".equals(roleCode)) {
            //账户集合
            List<Long> accountIds = baseMapper.querySalesDirectorAccountIds(companyId, mediaId, null);
            if (Check.isNull(accountIds)) {
                return Result.error("未查询到账户！");
            }
            JSONObject data = getManagerData(accountIds, userId, mediaId, companyId);
            data.put("weeklyGoalValue", weekly);
            data.put("monthlyGoalValue", monthly);
            result = Result.ok(data);
        } else {
            result = Result.error("该用户角色权限不足！");
        }

        return result;
    }

    private JSONObject getManagerData(List<Long> accountIds, String userId, String mediaId, String companyId) 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;
        //1 头条
        if ("1".equals(mediaId)) {
            //查询当日消耗 + 环比
            result = baseMapper.queryTtTodayCharge(statDay, hour, accountIds, companyId);
            //周消耗
            weekCharge = baseMapper.queryTtManydaysTotalCharge(weekFirstDay, statDay, accountIds, companyId);
            //月消耗
            String monthCharge = baseMapper.queryTtManydaysTotalCharge(monthFirstday, statDay, accountIds, companyId);
            result.put("weekCharge", new BigDecimal(weekCharge));
            result.put("monthCharge", new BigDecimal(monthCharge));
            //现金消耗 + 环比ROI
            JSONObject realCharged = baseMapper.queryTtRealCharged(lastMonthFirstday, monthFirstday, statDay, accountIds, companyId);
            result.put("realCharged", realCharged.getBigDecimal("realCharged"));
            result.put("realChargedRoi", realCharged.getString("realChargedRoi"));
        } else if ("2".equals(mediaId)) {
            result = baseMapper.queryKsTodayCharge(statDay, hour, accountIds, companyId);
            //周消耗
            weekCharge = baseMapper.queryKsManydaysTotalCharge(weekFirstDay, statDay, accountIds, companyId);
            //月消耗
            String monthCharge = baseMapper.queryKsManydaysTotalCharge(monthFirstday, statDay, accountIds, companyId);
            result.put("weekCharge", new BigDecimal(weekCharge));
            result.put("monthCharge", new BigDecimal(monthCharge));
            //现金消耗 + 环比ROI
            JSONObject realCharged = baseMapper.queryKsRealCharged(lastMonthFirstday, monthFirstday, statDay, accountIds, companyId);
            result.put("realCharged", realCharged.getBigDecimal("realCharged"));
            result.put("realChargedRoi", realCharged.getString("realChargedRoi"));
        }
        result.put("weeklyGoalValue", baseMapper.getWeekly(userId, companyId, mediaId));
        result.put("monthlyGoalValue", baseMapper.getMonthly(userId, companyId, 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("company_id", sale.getCompanyId());
        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 companyId, String startTime, String endTime) throws ParseException {
        String roleCode = baseMapper.getRoleCodeByUserId(userId);

        List<Long> compayAllAccountIds = baseMapper.querySalesDirectorAccountIds(companyId, mediaId, null);
        if (Check.isNull(compayAllAccountIds)) {
            return Result.error("未查询到账户！");
        }

        JSONObject data = null;
        //销售总监
        if ("saleDirector".equals(roleCode) || "saleAm".equals(roleCode)) {
            //丁兆明特殊处理
            if ("b161b7d9793942f980dbfe8c931cd1b0".equals(userId) || "228c45f913924639bf20c79ce5dadb16".equals(userId)) {
                if (startTime.equals(endTime)) {
                    data = getDailyCharges(null, compayAllAccountIds, userId, mediaId, companyId, startTime);
                } else {
                    data = getManyDaysCharges(null, compayAllAccountIds, userId, mediaId, companyId, startTime, endTime);
                }
                return Result.ok(data);
            }
            //查询销售总监及旗下的人员 集
            List<String> saleTeaMber = baseMapper.querySaleDirctorItsTeamMember(userId);
            saleTeaMber.add(userId);
            //账户集合
            List<Long> accountIds = baseMapper.querySalesDirectorAccountIds(companyId, mediaId, saleTeaMber);
            if (Check.isNull(accountIds)) {
                return Result.error("未查询到账户！");
            }
            if (startTime.equals(endTime)) {
                //消耗数据
                data = getDailyCharges(compayAllAccountIds, accountIds, userId, mediaId, companyId, startTime);

            } else {
                data = getManyDaysCharges(compayAllAccountIds, accountIds, userId, mediaId, companyId, startTime, endTime);

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

    private JSONObject getManyDaysCharges(List<Long> compayAllAccountIds, List<Long> accountIds, 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, accountIds, companyId);
            List<JSONObject> list = baseMapper.queryTtManydaysCharge(startTime, endTime, accountIds, companyId);
            result.put("list", list);
            //平台消耗
            if (compayAllAccountIds == null) {
                result.put("platformCharge", result.getString("totalCharge"));
                result.put("platformChargeRoi", result.getString("chargeRoi"));
            } else {
                JSONObject ptdata = baseMapper.queryTtManydaysChargeAndRoi(startTime, endTime, lastTimeStart, lastTimeEnd, compayAllAccountIds, 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, accountIds, companyId);
            List<JSONObject> list = baseMapper.queryKsManydaysCharge(startTime, endTime, accountIds, companyId);
            result.put("list", list);
            //平台消耗
            if (compayAllAccountIds == null) {
                result.put("platformCharge", result.getString("totalCharge"));
                result.put("platformChargeRoi", result.getString("chargeRoi"));
            } else {
                JSONObject ptdata = baseMapper.queryKsManydaysChargeAndRoi(startTime, endTime, lastTimeStart, lastTimeEnd, compayAllAccountIds, companyId);
                result.put("platformCharge", ptdata.getString("totalCharge"));
                result.put("platformChargeRoi", ptdata.getString("chargeRoi"));
            }
        }
        return result;
    }


    private JSONObject getDailyCharges(List<Long> compayAllAccountIds, List<Long> accountIds, 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, accountIds, companyId);
            List<JSONObject> list = baseMapper.queryTtHourList(date, accountIds, companyId);
            result.put("list", list);
            //平台消耗
            if (compayAllAccountIds == null) {
                result.put("platformCharge", result.getString("totalCharge"));
                result.put("platformChargeRoi", result.getString("chargeRoi"));
            } else {
                JSONObject ptdata = baseMapper.queryTtTodayCharge(date, hour, compayAllAccountIds, companyId);
                result.put("platformCharge", ptdata.getString("totalCharge"));
                result.put("platformChargeRoi", ptdata.getString("chargeRoi"));
            }
        } else if ("2".equals(mediaId)) {
            result = baseMapper.queryKsTodayCharge(date, hour, accountIds, companyId);
            List<JSONObject> list = baseMapper.queryKsHourList(date, accountIds, companyId);
            result.put("list", list);
            //平台消耗
            if (compayAllAccountIds == null) {
                result.put("platformCharge", result.getString("totalCharge"));
                result.put("platformChargeRoi", result.getString("chargeRoi"));
            } else {
                JSONObject ptdata = baseMapper.queryKsTodayCharge(date, hour, compayAllAccountIds, companyId);
                result.put("platformCharge", ptdata.getString("totalCharge"));
                result.put("platformChargeRoi", ptdata.getString("chargeRoi"));
            }
        }
        return result;
    }

    @Override
    public PageInfo getProjectChargeTop(String userId, String mediaId, String companyId, String startTime, String endTime, Integer pageNo, Integer pageSize) throws Exception {
        String roleCode = baseMapper.getRoleCodeByUserId(userId);
        //当天日期
        String today = DateUtils.formatDate(new Date());
        JSONObject data = null;
        //销售总监
        if ("saleDirector".equals(roleCode) || "saleAm".equals(roleCode)) {
            //丁兆明特殊处理
            if ("b161b7d9793942f980dbfe8c931cd1b0".equals(userId) || "228c45f913924639bf20c79ce5dadb16".equals(userId)) {
                //账户集合
                List<Long> accountIds = baseMapper.querySalesDirectorAccountIds(companyId, mediaId, null);
                if (Check.isNull(accountIds)) {
                    throw new Exception("未查询到账户！");
                }
                if (startTime.equals(endTime) && today.equals(startTime)) {
                    return getProjectDailyCharges(accountIds, companyId, mediaId, startTime, null, pageNo, pageSize);
                } else if (startTime.equals(endTime)) {
                    return getProjectDailyCharges(accountIds, companyId, mediaId, startTime, startTime, pageNo, pageSize);
                } else {
                    return getProjectDailyCharges(accountIds, companyId, mediaId, startTime, endTime, pageNo, pageSize);
                }
            }

            //查询销售总监及旗下的人员 集
            List<String> saleTeaMber = baseMapper.querySaleDirctorItsTeamMember(userId);
            saleTeaMber.add(userId);
            //账户集合
            List<Long> accountIds = baseMapper.querySalesDirectorAccountIds(companyId, mediaId, saleTeaMber);
            if (Check.isNull(accountIds)) {
                throw new Exception("未查询到账户！");
            }
            if (startTime.equals(endTime) && today.equals(startTime)) {
                return getProjectDailyCharges(accountIds, companyId, mediaId, startTime, null, pageNo, pageSize);
            } else if (startTime.equals(endTime)) {
                return getProjectDailyCharges(accountIds, companyId, mediaId, startTime, startTime, pageNo, pageSize);
            } else {
                return getProjectDailyCharges(accountIds, companyId, mediaId, startTime, endTime, pageNo, pageSize);
            }
            //分公司总经理
        } else if ("CompanyManager".equals(roleCode) || "admin".equals(roleCode)) {
            //账户集合
            List<Long> accountIds = baseMapper.querySalesDirectorAccountIds(companyId, mediaId, null);
            if (Check.isNull(accountIds)) {
                throw new Exception("未查询到账户！");
            }
            if (startTime.equals(endTime) && today.equals(startTime)) {
                return getProjectDailyCharges(accountIds, companyId, mediaId, startTime, null, pageNo, pageSize);
            } else if (startTime.equals(endTime)) {
                return getProjectDailyCharges(accountIds, companyId, mediaId, startTime, startTime, pageNo, pageSize);
            } else {
                return getProjectDailyCharges(accountIds, companyId, mediaId, startTime, endTime, pageNo, pageSize);
            }
        } else {
            throw new Exception("该用户角色权限不足！");
        }
    }

    private PageInfo getProjectDailyCharges(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(accountIds, startTime, endTime, companyId);
            PageHelper.startPage(pageNo, pageSize, false);
            List<JSONObject> list = baseMapper.queryTtHourProjectTop(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(accountIds, startTime, endTime, companyId);
            PageHelper.startPage(pageNo, pageSize, false);
            List<JSONObject> list = baseMapper.queryKsHourProjectTop(accountIds, startTime, endTime, days, hour, companyId);
            PageInfo pageInfo = new PageInfo(list);
            pageInfo.setTotal(total);
            return pageInfo;
        }
        return null;
    }
}
