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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.SysManagerCompany;
import org.jeecg.ctop.material.mapper.SysManagerCompanyMapper;
import org.jeecg.ctop.material.service.ISysManagerCompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

/**
 * 总经理&公司记录表
 *
 * @author jeecg-boot
 * 2022-02-22
 * @version V1.0
 */
@Service
public class SysManagerCompanyServiceImpl extends ServiceImpl<SysManagerCompanyMapper, SysManagerCompany> implements ISysManagerCompanyService {

    @Autowired
    private SysManagerCompanyMapper mapper;


    @Override
    public Result<Object> getMaterialProduce(String startTime, String endTime, String companyId, int mediaId) {

        if (Check.isNull(startTime) && Check.isNull(endTime)) {
            startTime = DateUtils.getDate(DateUtils.WEB_FORMAT);
            endTime = startTime;
        }
        SysManagerCompany company = this.getById(companyId);
        if (Check.isNull(company)) {
            return Result.ok("未查到公司:" + companyId);
        }

        //查询子集部门
        List<JSONObject> list = null;
        if (mediaId == 1) {
            list = mapper.queryDepartByParentId(company.getTtDesignId());
        } else if (mediaId == 2) {
            list = mapper.queryDepartByParentId(company.getKsDesignId());
        }
        if (Check.isNull(list) || list.isEmpty()) {
            return Result.ok("未查询到设计组");
        }
        //查询部门所有人员
        List<String> allPersonnel = mapper.queryAllPersonnel(list);
        if (Check.isNull(allPersonnel) || allPersonnel.isEmpty()) {
            return Result.ok("未查询到人员");
        }
        //查询数量
        Long total = mapper.queryMaterialNumber(allPersonnel, startTime, endTime);

        BigDecimal hundred = new BigDecimal(100 + "");
        for (JSONObject obj : list) {
            List<String> personnels = mapper.queryPersonnels(obj.getString("id"));
            if (Check.isNull(personnels)) {
                obj.put("count", 0);
                obj.put("ratio", 0.00);
                continue;
            }
            Long count = mapper.queryMaterialNumber(personnels, startTime, endTime);
            if (Check.isNull(count)) {
                obj.put("count", 0);
                obj.put("ratio", 0.00);
                continue;
            }
            obj.put("count", count);
            if (total != 0) {
                BigDecimal ratio = BigDecimal.valueOf(Double.valueOf(count) / total).multiply(hundred);
                String ratioStr = ratio.setScale(2, RoundingMode.HALF_UP).toString();
                obj.put("ratio", ratioStr);
            }
        }
        JSONObject result = new JSONObject();
        result.put("total", total);
        result.put("list", list);
        return Result.ok(result);
    }

    @Override
    public Result<Object> getMaterialProduceConsume(String startTime, String endTime, String companyId, int mediaId) {
        if (Check.isNull(startTime) && Check.isNull(endTime)) {
            startTime = DateUtils.getDate(DateUtils.WEB_FORMAT);
            endTime = startTime;
        }
        SysManagerCompany company = this.getById(companyId);
        if (Check.isNull(company)) {
            return Result.ok("未查到公司:" + companyId);
        }
        //查询子集部门
        List<JSONObject> list = null;
        //总消耗
        Double totalCharge = null;
        if (mediaId == 1) {
            list = mapper.queryDepartByParentId(company.getTtDesignId());
            if (Check.isNull(list) || list.isEmpty()) {
                return Result.ok("未查询到设计组");
            }
            //查询部门所有人员
            List<String> clipIds = mapper.queryAllPersonnel(list);
            if (Check.isNull(clipIds)) {
                return Result.ok("未查询到人员");
            }
            //总消耗
            totalCharge = mapper.queryTtMaterialCharge(clipIds, startTime, endTime, null);
            BigDecimal hundred = new BigDecimal(100 + "");
            for (JSONObject obj : list) {
                if (Check.isNull(totalCharge) || totalCharge == 0.0) {
                    obj.put("charge", 0);
                    obj.put("ratio", 0.0);
                    continue;
                } else {
                    List<String> clipids = mapper.queryPersonnels(obj.getString("id"));
                    if (Check.isNull(clipids)) {
                        obj.put("charge", 0);
                        obj.put("ratio", 0.0);
                        continue;
                    }
                    Double charge = mapper.queryTtMaterialCharge(clipids, startTime, endTime, null);
                    if (Check.isNull(charge)) {
                        obj.put("charge", 0);
                        obj.put("ratio", 0.0);
                        continue;
                    }
                    BigDecimal ratio = BigDecimal.valueOf(Double.valueOf(charge) / totalCharge).multiply(hundred);
                    String ratioStr = ratio.setScale(2, RoundingMode.HALF_UP).toString();
                    obj.put("ratio", ratioStr);
                    obj.put("charge", charge);
                }
            }
        } else if (mediaId == 2) {
            list = mapper.queryDepartByParentId(company.getKsDesignId());
            if (Check.isNull(list) || list.isEmpty()) {
                return Result.ok("未查询到设计组");
            }
            //查询部门所有人员
            List<String> clipIds = mapper.queryAllPersonnel(list);
            if (Check.isNull(clipIds)) {
                return Result.ok("未查询到人员");
            }
            //总消耗
            totalCharge = mapper.queryKsMaterialCharge(clipIds, startTime, endTime, null);
            BigDecimal hundred = new BigDecimal(100 + "");
            for (JSONObject obj : list) {
                if (Check.isNull(totalCharge) || totalCharge == 0.0) {
                    obj.put("charge", 0);
                    obj.put("ratio", 0.0);
                    continue;
                } else {
                    List<String> clipids = mapper.queryPersonnels(obj.getString("id"));
                    if (Check.isNull(clipids)) {
                        obj.put("charge", 0);
                        obj.put("ratio", 0.0);
                        continue;
                    }
                    Double charge = mapper.queryKsMaterialCharge(clipids, startTime, endTime, null);
                    if (Check.isNull(charge)) {
                        obj.put("charge", 0);
                        obj.put("ratio", 0.0);
                        continue;
                    }
                    BigDecimal ratio = BigDecimal.valueOf(Double.valueOf(charge) / totalCharge).multiply(hundred);
                    String ratioStr = ratio.setScale(2, RoundingMode.HALF_UP).toString();
                    obj.put("ratio", ratioStr);
                    obj.put("charge", charge);
                }
            }
        }
        JSONObject result = new JSONObject();
        result.put("totalCharge", totalCharge);
        result.put("list", list);
        return Result.ok(result);
    }

    @Override
    public Result<Object> getOperaterConsume(String startTime, String endTime, String companyId, int mediaId) {
        if (Check.isNull(startTime) && Check.isNull(endTime)) {
            startTime = DateUtils.getDate(DateUtils.WEB_FORMAT);
            endTime = startTime;
        }
        SysManagerCompany company = this.getById(companyId);
        if (Check.isNull(company)) {
            return Result.ok("未查到公司:" + companyId);
        }
        //查询子集部门
        List<JSONObject> list = null;
        //总消耗
        Double totalCharge = null;
        if (mediaId == 1) {
            list = mapper.queryDepartByParentId(company.getTtOperateId());
            if (Check.isNull(list) || list.isEmpty()) {
                return Result.ok("未查询到销售组");
            }
            //查询部门所有人员
            List<String> userIds = mapper.queryAllPersonnel(list);
            if (Check.isNull(userIds)) {
                return Result.ok("未查询到人员");
            }
            //总消耗
            totalCharge = mapper.queryTtMaterialCharge(null, startTime, endTime, userIds);
            BigDecimal hundred = new BigDecimal(100 + "");
            for (JSONObject obj : list) {
                if (Check.isNull(totalCharge) || totalCharge == 0.0) {
                    obj.put("charge", 0);
                    obj.put("ratio", 0.0);
                    continue;
                } else {
                    List<String> userids = mapper.queryPersonnels(obj.getString("id"));
                    if (Check.isNull(userids)) {
                        obj.put("charge", 0);
                        obj.put("ratio", 0.0);
                        continue;
                    }
                    Double charge = mapper.queryTtMaterialCharge(null, startTime, endTime, userids);
                    if (Check.isNull(charge)) {
                        obj.put("charge", 0);
                        obj.put("ratio", 0.0);
                        continue;
                    }
                    BigDecimal ratio = BigDecimal.valueOf(Double.valueOf(charge) / totalCharge).multiply(hundred);
                    String ratioStr = ratio.setScale(2, RoundingMode.HALF_UP).toString();
                    obj.put("ratio", ratioStr);
                    obj.put("charge", charge);
                }
            }
        } else if (mediaId == 2) {
            list = mapper.queryDepartByParentId(company.getKsOperateId());
            if (Check.isNull(list) || list.isEmpty()) {
                return Result.ok("未查询到销售组");
            }
            //查询部门所有人员
            List<String> userIds = mapper.queryAllPersonnel(list);
            if (Check.isNull(userIds)) {
                return Result.ok("未查询到人员");
            }
            //总消耗
            totalCharge = mapper.queryKsMaterialCharge(null, startTime, endTime, userIds);
            BigDecimal hundred = new BigDecimal(100 + "");
            for (JSONObject obj : list) {
                if (Check.isNull(totalCharge) || totalCharge == 0.0) {
                    obj.put("charge", 0);
                    obj.put("ratio", 0.0);
                    continue;
                } else {
                    List<String> userids = mapper.queryPersonnels(obj.getString("id"));
                    if (Check.isNull(userids)) {
                        obj.put("charge", 0);
                        obj.put("ratio", 0.0);
                        continue;
                    }
                    Double charge = mapper.queryKsMaterialCharge(null, startTime, endTime, userids);
                    if (Check.isNull(charge)) {
                        obj.put("charge", 0);
                        obj.put("ratio", 0.0);
                        continue;
                    }
                    BigDecimal ratio = BigDecimal.valueOf(Double.valueOf(charge) / totalCharge).multiply(hundred);
                    String ratioStr = ratio.setScale(2, RoundingMode.HALF_UP).toString();
                    obj.put("ratio", ratioStr);
                    obj.put("charge", charge);
                }
            }
        }

        JSONObject result = new JSONObject();
        result.put("totalCharge", totalCharge);
        result.put("list", list);
        return Result.ok(result);
    }

    @Override
    public void setConsumeValue(String companyId, String targetValue, int mediaId) throws Exception {
        SysManagerCompany company = this.getById(companyId);
        if (Check.isNull(company)) {
            throw new Exception("未查询到公司");
        }
        if (mediaId == 1) {
            company.setTtTargetValue(targetValue);
        } else if (mediaId == 2) {
            company.setKsTargetValue(targetValue);
        }
        this.updateById(company);
    }

    @Override
    public Result<Object> getProjectConsumeTop(String startTime, String endTime, String companyId, int mediaId) {
        if (Check.isNull(startTime) && Check.isNull(endTime)) {
            startTime = DateUtils.getDate(DateUtils.WEB_FORMAT);
            endTime = startTime;
        }
        List<JSONObject> list = null;
        if (mediaId == 1) {
            list = mapper.queryTtProjectConsumeTop(companyId, startTime, endTime);
        } else if (mediaId == 2) {
            list = mapper.queryKsProjectConsumeTop(companyId, startTime, endTime);
        }
        return Result.ok(list);
    }

    @Override
    public Result<Object> getMediaData(String companyId) {
        Integer startTime = DateUtils.getFirstDayByMonth();
        String endTime = DateUtils.getDate(DateUtils.SHORT_FORMAT);
        List<Map<String, String>> ksdata = mapper.getKsMonthlyData(companyId, startTime, endTime);
        List<Map<String, String>> ttdate = mapper.getTtMonthlyData(companyId, startTime, endTime);
        JSONObject obj = new JSONObject();
        obj.put("ksdata", ksdata);
        obj.put("ttdate", ttdate);
        return Result.ok(obj);
    }

    @Override
    public Result<Object> getRealTimeData(String companyId, int mediaId) throws ParseException {
        String today = DateUtils.getDate(DateUtils.WEB_FORMAT);
        String lastDay = DateUtils.getLastDay(today, 1);
        Integer hour = DateUtils.getNowHour();
        SysManagerCompany company = this.getById(companyId);
        JSONObject result = new JSONObject();
        if (Check.isNull(company)) {
            return Result.ok("未查到公司:" + companyId);
        }
        BigDecimal hundred = new BigDecimal(100 + "");
        if (mediaId == 1) {
            List<JSONObject> list = mapper.queryDepartByParentId(company.getTtDesignId());
            if (Check.isNull(list) || list.isEmpty()) {
                return Result.ok("未查询到销售组");
            }
            //查询部门所有人员
            List<String> userIds = mapper.queryAllPersonnel(list);
            if (Check.isNull(userIds)) {
                return Result.ok("未查询到人员");
            }

            //查询消耗
            JSONObject cost = mapper.queryTtRealTimeCost(companyId, today, lastDay, hour);
            Double todayCost = cost.getDouble("todayCost");
            Double yesCost = cost.getDouble("yesCost");
            String costRatioStr = null;
            if (checkNumberIsNull(yesCost)) {
                BigDecimal costRatio = BigDecimal.valueOf((todayCost - yesCost) / yesCost).multiply(hundred);
                costRatioStr = costRatio.setScale(2, RoundingMode.HALF_UP).toString();
            }
            //查询广告组数
            JSONObject group = mapper.queryTtRealTimeGroupNum(companyId, today, lastDay);
            Long groupNum = group.getLong("todayNum");
            Double yesNum = group.getDouble("yesNum");
            String unitRatioStr = null;
            if (checkNumberIsNull(yesNum)) {
                BigDecimal unitRatio = BigDecimal.valueOf((groupNum - yesNum) / yesNum).multiply(hundred);
                unitRatioStr = unitRatio.setScale(2, RoundingMode.HALF_UP).toString();
            }

            //查询素材数
            JSONObject material = mapper.queryTtRealTimeMaterialNum(companyId, userIds, today, lastDay);
            Long materialNum = material.getLong("todayCount");
            Double yesCount = material.getDouble("yesCount");
            String materialRatioStr = null;
            if (checkNumberIsNull(yesCount)) {
                BigDecimal materialRatio = BigDecimal.valueOf((materialNum - yesCount) / yesCount).multiply(hundred);
                materialRatioStr = materialRatio.setScale(2, RoundingMode.HALF_UP).toString();
            }

            List<JSONObject> operateList = mapper.queryDepartByParentId(company.getTtOperateId());
            if (Check.isNull(list) || list.isEmpty()) {
                return Result.ok("未查询到技术组");
            }
            //查询运营部门所有人员
            List<String> operateUserIds = mapper.queryAllPersonnel(operateList);
            //人效比：公式=该分公司今日消耗/该分公司运营人数
            if (Check.isNull(operateUserIds)) {
                result.put("renXiao", 0);
            } else {
                BigDecimal renXiaoRatio = BigDecimal.valueOf(todayCost / operateUserIds.size());
                String renXiaoRatioStr = renXiaoRatio.setScale(2, RoundingMode.HALF_UP).toString();
                result.put("renXiao", renXiaoRatioStr);
            }
            result.put("cost", todayCost);
            result.put("costRatio", costRatioStr);
            result.put("groupNum", groupNum);
            result.put("unitRatio", unitRatioStr);
            result.put("materialNum", materialNum);
            result.put("materialRatio", materialRatioStr);
        } else if (mediaId == 2) {
            List<JSONObject> list = mapper.queryDepartByParentId(company.getKsDesignId());
            if (Check.isNull(list) || list.isEmpty()) {
                return Result.ok("未查询到技术组");
            }
            //查询技术部门所有人员
            List<String> userIds = mapper.queryAllPersonnel(list);
            if (Check.isNull(userIds)) {
                return Result.ok("未查询到人员");
            }

            //查询消耗
            JSONObject cost = mapper.queryKsRealTimeCost(companyId, today, lastDay, hour);
            Double todayCost = cost.getDouble("todayCost");
            Double yesCost = cost.getDouble("yesCost");
            String costRatioStr = null;
            if (checkNumberIsNull(yesCost)) {
                BigDecimal costRatio = BigDecimal.valueOf((todayCost - yesCost) / yesCost).multiply(hundred);
                costRatioStr = costRatio.setScale(2, RoundingMode.HALF_UP).toString();
            }
            //查询广告组数
            JSONObject group = mapper.queryKsRealTimeGroupNum(companyId, today, lastDay);
            Long groupNum = group.getLong("todayNum");
            Double yesNum = group.getDouble("yesNum");
            String unitRatioStr = null;
            if (checkNumberIsNull(yesNum)) {
                BigDecimal unitRatio = BigDecimal.valueOf((groupNum - yesNum) / yesNum).multiply(hundred);
                unitRatioStr = unitRatio.setScale(2, RoundingMode.HALF_UP).toString();
            }
            //查询素材数
            JSONObject material = mapper.queryKsRealTimeMaterialNum(companyId, userIds, today, lastDay);
            Long materialNum = material.getLong("todayCount");
            Double yesCount = material.getDouble("yesCount");
            String materialRatioStr = null;
            if (checkNumberIsNull(yesCount)) {
                BigDecimal materialRatio = BigDecimal.valueOf((materialNum - yesCount) / yesCount).multiply(hundred);
                materialRatioStr = materialRatio.setScale(2, RoundingMode.HALF_UP).toString();
            }

            List<JSONObject> operateList = mapper.queryDepartByParentId(company.getKsOperateId());
            if (Check.isNull(list) || list.isEmpty()) {
                return Result.ok("未查询到技术组");
            }
            //查询运营部门所有人员
            List<String> operateUserIds = mapper.queryAllPersonnel(operateList);
            //人效比：公式=该分公司今日消耗/该分公司运营人数
            if (Check.isNull(operateUserIds)) {
                result.put("renXiao", 0);
            } else {
                BigDecimal renXiaoRatio = BigDecimal.valueOf(todayCost / operateUserIds.size());
                String renXiaoRatioStr = renXiaoRatio.setScale(2, RoundingMode.HALF_UP).toString();
                result.put("renXiao", renXiaoRatioStr);
            }
            result.put("cost", todayCost);
            result.put("costRatio", costRatioStr);
            result.put("groupNum", groupNum);
            result.put("unitRatio", unitRatioStr);
            result.put("materialNum", materialNum);
            result.put("materialRatio", materialRatioStr);
        }
        return Result.ok(result);
    }

    @Override
    public Result<Object> getTotalConsume(String companyId, int mediaId) {
        Integer startTime = DateUtils.getFirstDayByMonth();
        String endTime = DateUtils.getDate(DateUtils.SHORT_FORMAT);
        JSONObject obj = new JSONObject();
        SysManagerCompany company = this.getById(companyId);
        if (Check.isNull(company)) {
            return Result.error("未查询到公司");
        }
        String totalConsume = null;
        if (mediaId == 1) {
            totalConsume = mapper.getTtTotalConsume(companyId, startTime, endTime);
            obj.put("targetValue", company.getTtTargetValue());
        } else if (mediaId == 2) {
            totalConsume = mapper.getKsTotalConsume(companyId, startTime, endTime);
            obj.put("targetValue", company.getKsTargetValue());
        }
        obj.put("totalConsume", totalConsume);
        return Result.ok(obj);
    }

    private boolean checkNumberIsNull(Double number) {
        if (Check.isNull(number)) {
            return false;
        }
        double b = 0.0;
        BigDecimal number1 = new BigDecimal(number);
        BigDecimal number2 = new BigDecimal(b);
        int result = number1.compareTo(number2);
        if (result == 0) {
            return false;
        }
        return true;
    }

}
