package cn.wise.sc.cement.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.wise.sc.cement.business.entity.Entrust;
import cn.wise.sc.cement.business.entity.Handle;
import cn.wise.sc.cement.business.entity.NonStandardApply;
import cn.wise.sc.cement.business.entity.NonStandardValue;
import cn.wise.sc.cement.business.entity.NormProduction;
import cn.wise.sc.cement.business.entity.NormProductionStatistics;
import cn.wise.sc.cement.business.entity.Preciprice;
import cn.wise.sc.cement.business.entity.Sample;
import cn.wise.sc.cement.business.entity.SampleDistribution;
import cn.wise.sc.cement.business.entity.SysGroup;
import cn.wise.sc.cement.business.entity.SysPost;
import cn.wise.sc.cement.business.entity.SysUser;
import cn.wise.sc.cement.business.entity.TeamGroup;
import cn.wise.sc.cement.business.mapper.EntrustMapper;
import cn.wise.sc.cement.business.mapper.PrecipriceMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.model.vo.ProductionVo;
import cn.wise.sc.cement.business.model.vo.WorkloadStatisticsVo;
import cn.wise.sc.cement.business.service.IEntrustService;
import cn.wise.sc.cement.business.service.IHandleService;
import cn.wise.sc.cement.business.service.INonStandardApplyService;
import cn.wise.sc.cement.business.service.INonStandardValueService;
import cn.wise.sc.cement.business.service.INormProductionService;
import cn.wise.sc.cement.business.service.IPrecipriceService;
import cn.wise.sc.cement.business.service.ISampleDistributionService;
import cn.wise.sc.cement.business.service.ISampleService;
import cn.wise.sc.cement.business.service.ISysGroupService;
import cn.wise.sc.cement.business.service.ISysPostService;
import cn.wise.sc.cement.business.service.ISysUserService;
import cn.wise.sc.cement.business.service.ITeamGroupService;
import cn.wise.sc.cement.business.util.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ztw
 * @since 2020-11-02
 */
@Service
public class PrecipriceServiceImpl extends ServiceImpl<PrecipriceMapper, Preciprice> implements IPrecipriceService {


    final
    EntrustMapper iEntrustService;
    final
    ISampleService iSampleService;
    final
    INormProductionService iNormProductionService;
    final
    ISysUserService iSysUserService;
    final
    ISysGroupService iSysGroupService;
    final
    ITeamGroupService iTeamGroupService;
    final
    IHandleService iHandleService;
    final
    ISysPostService iSysPostService;
    final
    INonStandardValueService iNonStandardValueService;
    final
    INonStandardApplyService iNonStandardApplyService;
    final
    ISampleDistributionService iSampleDistributionService;
    @Resource
    PrecipriceMapper precipriceMapper;

    public PrecipriceServiceImpl(EntrustMapper iEntrustService,
                                 ISampleService iSampleService,
                                 INormProductionService iNormProductionService,
                                 ISysUserService iSysUserService,
                                 ISysGroupService iSysGroupService,
                                 ITeamGroupService iTeamGroupService,
                                 IHandleService iHandleService,
                                 ISysPostService iSysPostService,
                                 INonStandardValueService iNonStandardValueService,
                                 INonStandardApplyService iNonStandardApplyService,
                                 ISampleDistributionService iSampleDistributionService) {
        this.iEntrustService = iEntrustService;
        this.iSampleService = iSampleService;
        this.iNormProductionService = iNormProductionService;
        this.iSysUserService = iSysUserService;
        this.iSysGroupService = iSysGroupService;
        this.iTeamGroupService = iTeamGroupService;
        this.iHandleService = iHandleService;
        this.iSysPostService = iSysPostService;
        this.iNonStandardValueService = iNonStandardValueService;
        this.iNonStandardApplyService = iNonStandardApplyService;
        this.iSampleDistributionService = iSampleDistributionService;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NESTED)
    public boolean createPreciprice(final Integer userId, final Integer entrustId,
                                    final Integer targetId, final Integer type,
                                    final Integer sampleId, boolean isUrgent) {

        Assert.notNull(userId, "用户id不能为空！");
        Assert.notNull(entrustId, "项目id不能为空！");
        Assert.notNull(targetId, "处理项id不能为空！");
        Assert.notNull(sampleId, "样品id不能为空！");
        Assert.notNull(type, "处理项类型不能为空！");
        //获取项目编号和名字
        Entrust entrust = iEntrustService.selectById(entrustId);
        if (BeanUtil.isEmpty(entrust)) {
            log.debug("产值记录新增失败,项目没找到!");
            throw new IllegalArgumentException("无效的项目id!");
        }
        Preciprice preciprice = new Preciprice();
        preciprice.setEntrustId(entrust.getId());
        preciprice.setEntrustCode(entrust.getEntrustCode());
        preciprice.setEntrustName(entrust.getProjectName());
        preciprice.setIsUrgent(isUrgent ? 1 : 0);
        //获取样品信息
        Sample sample = iSampleService.getById(sampleId);
        if (BeanUtil.isEmpty(sample)) {
            log.debug("产值记录新增失败,项目没找到!");
            throw new IllegalArgumentException("无效的项目id!");
        }
        preciprice.setSampleId(sample.getId());
        preciprice.setSampleName(sample.getName());

        //获取产值信息
        QueryWrapper<NormProduction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("assess_id", targetId);
        queryWrapper.eq("type", type);
        queryWrapper.eq("status", 1);
        NormProduction normProduction = iNormProductionService.getOne(queryWrapper);

        if (BeanUtil.isEmpty(normProduction)) {
            log.debug("产值记录新增失败,产值信息没找到!");
            throw new IllegalArgumentException("联系管理员.配置产值信息!");
        }
        preciprice.setAnalyseRate(BigDecimal.valueOf(normProduction.getAnalyseRate()));
        preciprice.setAssessRate(BigDecimal.valueOf(normProduction.getAssessId()));
        preciprice.setAssessValue(BigDecimal.valueOf(normProduction.getAssessValue()));
        preciprice.setReportedAnalyseResult(BigDecimal.valueOf(normProduction.getReportedAnalyseResult()));
        preciprice.setReportedResultRate(BigDecimal.valueOf(normProduction.getReportedResultRate()));
        preciprice.setCoefficient(BigDecimal.valueOf(normProduction.getCoefficient()));
        preciprice.setCreateTime(DateUtil.date().getTime());
        preciprice.setSeparateRate(BigDecimal.valueOf(normProduction.getSeparateRate()));
        preciprice.setQuotaDay(BigDecimal.valueOf(normProduction.getQuotaDay()));
        if (type == 1) {
            if (isUrgent) {
                preciprice.setPreciprice(new BigDecimal(3).subtract(calculateWorkTimeCoefficient(normProduction, normProduction.getAnalyseRate())));
            } else {
                preciprice.setPreciprice(calculateWorkTimeCoefficient(normProduction, normProduction.getAnalyseRate()));
            }
        } else {
            if (isUrgent) {
                preciprice.setPreciprice(new BigDecimal(3).subtract(calculateWorkTimeCoefficient(normProduction, normProduction.getAnalyseRate())));
            } else {
                preciprice.setPreciprice(calculateWorkTimeCoefficient(normProduction, normProduction.getAnalyseRate()));
            }
        }
        //获取用户职位和账号
        SysUser sysUser = iSysUserService.getById(userId);
        if (BeanUtil.isEmpty(sysUser)) {
            log.debug("产值记录新增失败,用户没找到!");
            throw new IllegalArgumentException("无效的用户id!");
        }
        preciprice.setUserId(sysUser.getId());
        preciprice.setUserName(sysUser.getName());
        preciprice.setSex(sysUser.getSex());
        SysGroup sysGroup = iSysGroupService.getById(sysUser.getGroupId());
        if (BeanUtil.isEmpty(sysGroup)) {
            log.debug("产值记录新增失败,用户所在部门未找到!");
            throw new IllegalArgumentException("用户所在部门需要设置!");
        }
        preciprice.setPosition(sysGroup.getName());
        preciprice.setGroupId(sysGroup.getId());

        //获取检测组名
        if (type == 1) {
            TeamGroup teamGroup = iTeamGroupService.getById(targetId);
            preciprice.setGroupTeamName(teamGroup.getName());
        } else {
            Handle handle = iHandleService.getById(targetId);
            preciprice.setGroupTeamName(handle.getName());
        }
        preciprice.setTargetId(targetId);
        preciprice.setType(type);

        try {
            return this.save(preciprice);
        } catch (Exception e) {
            log.error("添加产值记录失败!");
            return false;
        }
    }


    @Override
    public BaseResponse<List<NormProductionStatistics>> normProductionStatistics(Long start, Long end, String name, Integer groupId) {
        //统计分样处理的详情
        List<NormProduction.NormProductionDetail> normProductionDetails =
                normProductionDetails(null, start, end);

        if (normProductionDetails.size() == 0) {
            BaseResponse<List<NormProductionStatistics>> rts = BaseResponse.okData(null);
            rts.setData(new ArrayList<>());
            return rts;
        }
        //
        Map<Integer, BigDecimal> coefficientMap = new HashMap<>(normProductionDetails.size());
        normProductionDetails
                .forEach(arg -> {
                    Integer userId = arg.getUserId();
                    //不存在 添加
                    if (!coefficientMap.containsKey(userId)) {
                        coefficientMap.put(userId, arg.getWorkTimeCoefficient());
                    } else {
                        BigDecimal bigDecimal = coefficientMap.get(userId);
                        BigDecimal newWorkTime = arg.getWorkTimeCoefficient().add(bigDecimal);
                        coefficientMap.put(userId, newWorkTime);
                    }
                });
        List<NormProductionStatistics> rts = new ArrayList<>();
        Set<Integer> userIds = coefficientMap.keySet();
        QueryWrapper<SysUser> qw = new QueryWrapper<>();
        qw.in("id", userIds);
        List<SysUser> users = iSysUserService.list(qw);
        List<SysPost> sysPosts = iSysPostService.list();
        List<SysGroup> sysGroups = iSysGroupService.list();
        for (Integer userId : coefficientMap.keySet()) {
            SysUser sysUser = users.stream()
                    .filter(arg -> arg.getId().intValue() == userId)
                    .findFirst().orElse(null);
            SysGroup sysGroup = sysGroups.stream().filter(arg -> arg.getId().intValue() == sysUser.getGroupId())
                    .findFirst().orElse(null);
            if (sysUser == null) {
                continue;
            }
            if (sysGroup == null) {
                log.debug("用户分组未设置!关联用户部门失败!");
                continue;
            }
            NormProductionStatistics productionStatistics = new NormProductionStatistics();
            productionStatistics.setAccount(sysUser.getUsername());
            productionStatistics.setCoefficient(coefficientMap.get(userId).doubleValue());
            productionStatistics.setTime("/");
            productionStatistics.setCount(normProductionDetails.stream()
                    .filter(arg -> arg.getUserId().intValue() == sysUser.getId())
                    .count());
            productionStatistics.setPosition(sysUser.getQualifications());
            if (start != null && end != null) {
                DateTime startTime = DateUtil.date(start);
                DateTime endTime = DateUtil.date(end);
                productionStatistics.setTime(startTime.toDateStr() + "-" + endTime.toDateStr());
            }
            productionStatistics.setSex(sysUser.getSex() == 0 ? "女" : "男");
            productionStatistics.setUserId(sysUser.getId() + "");
            productionStatistics.setUserName(sysUser.getName());
            productionStatistics.setGroupId(sysUser.getGroupId());
            productionStatistics.setGroupName(sysGroup.getName());

            SysPost sysPost = sysPosts.stream()
                    .filter(arg -> arg.getId().intValue() == sysUser.getPostId()).
                            findFirst().orElse(null);

            productionStatistics.setPosition(sysPost == null ? "职务一" : sysPost.getName());
            productionStatistics.setGroupName(sysGroup.getName());
            rts.add(productionStatistics);
        }

        //过滤名字
        if (StrUtil.isNotBlank(name)) {
            List<NormProductionStatistics> collect = rts.stream().filter(arg -> arg.getUserName().contains(name)).collect(Collectors.toList());
            return BaseResponse.okData(collect);
        }

        //过滤部门id
        if (groupId != null) {
            List<NormProductionStatistics> collect = rts.stream().filter(arg -> arg.getGroupId().equals(groupId)).collect(Collectors.toList());
            return BaseResponse.okData(collect);
        }

        return BaseResponse.okData(rts);
    }


    @Override
    public List<NormProduction.NormProductionDetail>
    normProductionDetails(Integer userId, Long startTime, Long endTime) {
        QueryWrapper<Preciprice> qw = new QueryWrapper<>();
        if (!BeanUtil.isEmpty(startTime)) {
            qw.gt("create_time", startTime);
        }
        if (!BeanUtil.isEmpty(endTime)) {
            qw.le("create_time", endTime);
        }
        if (!BeanUtil.isEmpty(userId)) {
            qw.like("user_id", userId);
        }
        qw.eq("status", 1);
        qw.orderByDesc("create_time");
        List<Preciprice> list = this.list(qw);
        List<NormProduction.NormProductionDetail> rts = new ArrayList<>(list.size());
        for (Preciprice preciprice : list) {
            NormProduction.NormProductionDetail detail = preciprice2NormDetail(preciprice);
            rts.add(detail);
        }
        return rts;
    }


    @Override
    public List<ProductionVo> production(String name, Long start, Long end, Integer groupId) {
        Date startDate = null;
        Date endDate = new Date();
        if (start != null && start != 0) {
            startDate = DateUtil.date(start);
        }
        if (end != null && end != 0) {
            endDate = DateUtil.date(end);
        }

        //非标准产值
        List<NonStandardValue> nonStandardValues = iNonStandardValueService.nonValue(startDate, endDate, groupId, name).getData();
        //标准产值
        List<NormProductionStatistics> productionStatistics = this.normProductionStatistics(start, end, name, groupId).getData();
        //以userId找关系
        Set<String> userIds = new HashSet<>();
        nonStandardValues.forEach(arg -> userIds.add(arg.getUserId() + ""));
        productionStatistics.forEach(arg -> userIds.add(arg.getUserId()));
        List<ProductionVo> rts = new ArrayList<>(userIds.size());
        userIds.forEach(arg -> {
            ProductionVo productionVo = new ProductionVo();
            productionVo.setUserId(arg);
            //找到标准准产值里面的数据
            productionStatistics.forEach(opt -> {
                if (opt.getUserId().equals(arg)) {
                    productionVo.setProductionValue(opt.getCoefficient());
                    productionVo.setUserName(opt.getUserName());
                    productionVo.setPosition(opt.getPosition());
                    productionVo.setAccount(opt.getAccount());
                    productionVo.setGroupId(opt.getGroupId());
                    productionVo.setGroupName(opt.getGroupName());
                }
            });
            //找到标准产值里面的数据
            nonStandardValues.forEach(opt -> {
                if (arg.equals(opt.getUserId() + "")) {
                    productionVo.setNonProductionValue(opt.getFinalValue());
                }
            });
            rts.add(productionVo);
        });
        //处理非标准产值没有用名职位信息
        QueryWrapper<SysUser> qw = new QueryWrapper<>();
        qw.in("id", userIds);
        if (CollectionUtil.isEmpty(userIds)) {
            return null;
        }
        List<SysUser> users = iSysUserService.list(qw);
        List<SysPost> sysPosts = iSysPostService.list();
        List<SysGroup> sysGroups = iSysGroupService.list();
        Date finalStartDate = startDate;
        Date finalEndDate = endDate;
        rts.forEach(arg -> {
            arg.setTime(finalStartDate == null ? "/" : DateUtil.format(finalStartDate, "yyyy-MM-dd") + "--" + DateUtil.format(finalEndDate, "yyyy-MM-dd"));
            if (StrUtil.isBlank(arg.getUserName())) {
                //关联用户信息
                users.stream().filter(opt -> arg.getUserId().equals(opt.getId() + "")).findFirst()
                        .ifPresent(opt -> {
                            arg.setUserName(opt.getName());
                            arg.setAccount(opt.getUsername());
                            arg.setPositionId(opt.getPostId());
                            arg.setGroupId(opt.getGroupId());
                        });
                //关联职务
                sysPosts.stream().filter(opt -> arg.getPositionId().intValue() == opt.getId())
                        .findFirst()
                        .ifPresent(opt -> arg.setPosition(opt.getName()));

                sysGroups.stream().filter(opt -> arg.getGroupId().intValue() == opt.getId())
                        .findFirst()
                        .ifPresent(opt -> arg.setGroupName(opt.getName()));
            }
            arg.setProductionTotalValue(arg.getNonProductionValue() + arg.getProductionValue());
        });
        //过滤名字
        if (StrUtil.isNotBlank(name)) {
            return rts.stream().filter(arg -> arg.getUserName().contains(name))
                    .collect(Collectors.toList());
        }

        //过滤部门id
        if (groupId != null) {
            return rts.stream().filter(arg -> arg.getGroupId().equals(groupId))
                    .collect(Collectors.toList());
        }
        return rts;
    }

    @Override
    public void exportNormProductionStatistics(Long start, Long end, String name, Integer groupId, HttpServletResponse response) {
        BaseResponse<List<NormProductionStatistics>> listBaseResponse = normProductionStatistics(start, end, name, groupId);
        if (listBaseResponse.getCode() == 200) {
            List<NormProductionStatistics> data = listBaseResponse.getData();
            if (CollectionUtil.isNotEmpty(data)) {
                String[] headers = new String[10];
                headers[0] = "用户编号";
                headers[1] = "用户名";
                headers[2] = "账号";
                headers[3] = "性别";
                headers[4] = "职务";
                headers[5] = "统计时间";
                headers[6] = "检测项目数";
                headers[7] = "产值绩效";
                headers[8] = "部门id";
                headers[9] = "部门名";

                List<Object[]> exportData = new ArrayList<>(data.size());
                for (NormProductionStatistics productionStatistics : data) {
                    Object[] objs = new Object[10];
                    objs[0] = productionStatistics.getUserId();
                    objs[1] = productionStatistics.getUserName();
                    objs[2] = productionStatistics.getAccount();
                    objs[3] = productionStatistics.getSex();
                    objs[4] = productionStatistics.getPosition();
                    objs[5] = productionStatistics.getTime();
                    objs[6] = productionStatistics.getCount();
                    objs[7] = productionStatistics.getCoefficient();
                    objs[8] = productionStatistics.getGroupId();
                    objs[9] = productionStatistics.getGroupName();
                    exportData.add(objs);
                }
                ExcelUtil.excelExport(
                        "标准产值统计", headers,
                        exportData, response);
            }
        }
    }

    @Override
    public void exportNormProductionDetail(Integer userId, Long startTime, Long endTime, HttpServletResponse response) {
        List<NormProduction.NormProductionDetail> normProductionDetails = normProductionDetails(userId, startTime, endTime);
        if (CollectionUtil.isNotEmpty(normProductionDetails)) {
            String[] headers = new String[13];
            headers[0] = "序号";
            headers[1] = "名字";
            headers[2] = "检测项目";
            headers[3] = "所属项目";
            headers[4] = "项目编号";
            headers[5] = "检测时间";
            headers[6] = "分析占比";
            headers[7] = "分样占比";
            headers[8] = "校核占比";
            headers[9] = "报结果占比";
            headers[10] = "合计";
            List<Object[]> exportData = new ArrayList<>(normProductionDetails.size());
            int count = 0;
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 hh:mm:ss");
            for (NormProduction.NormProductionDetail target : normProductionDetails) {
                Object[] objs = new Object[13];
                objs[0] = count++;
                objs[1] = target.getUserName();
                objs[2] = target.getGroupTeamName();
                objs[3] = target.getProjectName();
                objs[4] = target.getEntrustCode();
                objs[5] = target.getCheckTime() == null ? "/" : target.getCheckTime().format(timeFormatter);
                objs[6] = target.getAnalyseRate();
                objs[7] = target.getSeparateRate();
                objs[8] = target.getAssessRate();
                objs[9] = target.getReportedResultRate();
                objs[10] = target.getWorkTimeCoefficient();
                exportData.add(objs);
            }
            ExcelUtil.excelExport("标准产值详情—" + normProductionDetails.get(0).getUserName(), headers, exportData, response);
        }
    }

    @Override
    public void exportProduction(String name, Long startTime, Long endTime, Integer groupId, HttpServletResponse response) {
        List<ProductionVo> data = production(name, startTime, endTime, groupId);
        if (CollectionUtil.isNotEmpty(data)) {
            String[] headers = new String[10];
            headers[0] = "序号";
            headers[1] = "姓名";
            headers[2] = "账户";
            headers[3] = "职务";
            headers[4] = "统计时间";
            headers[5] = "标准产值";
            headers[6] = "非标准产值";
            headers[7] = "产值统计";
            headers[8] = "部门id";
            headers[9] = "部门名";
            List<Object[]> exportData = new ArrayList<>(data.size());
            int count = 0;
            for (ProductionVo target : data) {
                Object[] objs = new Object[10];
                objs[0] = count++;
                objs[1] = target.getUserName();
                objs[2] = target.getAccount();
                objs[3] = target.getPosition();
                objs[4] = target.getTime();
                objs[5] = target.getProductionValue();
                objs[6] = target.getNonProductionValue();
                objs[7] = target.getProductionTotalValue();
                objs[8] = target.getGroupId();
                objs[9] = target.getGroupName();
                exportData.add(objs);
            }
            ExcelUtil.excelExport("产值统计", headers, exportData, response);
        }
    }

    @Override
    public List<WorkloadStatisticsVo> workloadStatistics(Date startTime, Date endTime, Integer userId) {


        long start = getDefaultStart(startTime == null ? 0 : startTime.getTime());
        long end = getDefaultEnd(endTime.getTime());
        Map<String, Integer> map1 = initMonthMoneyMap(start, end);
        Map<String, Integer> map2 = initMonthMoneyMap(start, end);

        QueryWrapper<SampleDistribution> qw = new QueryWrapper<>();
        if (startTime != null) {
            qw.ge("finish_time", DateUtil.format(DateUtil.date(start), "yyyy-MM-dd"));
        }
        if (userId != null && userId != 0) {
            qw.eq("user_id", userId);
        }
        qw.le("finish_time", DateUtil.format(DateUtil.date(end), "yyyy-MM-dd"));
        qw.eq("status", 2);
        List<SampleDistribution> sampleDistributions = iSampleDistributionService.list(qw);

        QueryWrapper<NonStandardApply> qwA = new QueryWrapper<>();
        if (startTime != null) {
            qwA.ge("start_time", DateUtil.format(DateUtil.date(start), "yyyy-MM-dd"));
        }
        if (userId != null && userId != 0) {
            qwA.eq("user_id", userId);
        }
        qwA.le("start_time", DateUtil.format(DateUtil.date(end), "yyyy-MM-dd"));
        qwA.eq("status", 2);
        List<NonStandardApply> nonStandardApplies = iNonStandardApplyService.list(qwA);

        for (SampleDistribution sampleDistribution : sampleDistributions) {
            addCount(sampleDistribution.getFinishTime(), map1);
        }
        for (NonStandardApply nonStandardApply : nonStandardApplies) {
            addCount(nonStandardApply.getStartTime(), map2);
        }
        WorkloadStatisticsVo workloadStatisticsVo = new WorkloadStatisticsVo();
        workloadStatisticsVo.setType(0);
        workloadStatisticsVo.setMap(map1);
        WorkloadStatisticsVo workloadStatisticsVo2 = new WorkloadStatisticsVo();
        workloadStatisticsVo2.setType(1);
        workloadStatisticsVo2.setMap(map2);
        List<WorkloadStatisticsVo> rts = new ArrayList<>(2);
        rts.add(workloadStatisticsVo);
        rts.add(workloadStatisticsVo2);
        return rts;
    }

    @Override
    public boolean updateStatusByEntrustId(Integer entrustId) {
        cn.hutool.core.lang.Assert.notNull(entrustId, "报告id不能为空!");

        try {
            precipriceMapper.updateStatusByEntrustId(entrustId);
            return true;
        } catch (Exception e) {
            log.error("更新产值状态失败!");
            return false;
        }

    }

    private NormProduction.NormProductionDetail preciprice2NormDetail(Preciprice preciprice) {

        NormProduction.NormProductionDetail rts = new NormProduction.NormProductionDetail();
        BeanUtil.copyProperties(preciprice, rts);
        rts.setAssessId(preciprice.getTargetId());
        rts.setWorkTimeCoefficient(preciprice.getPreciprice());
        rts.setCheckTime(getDateTimeOfTimestamp(preciprice.getCreateTime()));
        return rts;
    }

    public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        ZoneId zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zone);
    }

    private NormProductionStatistics preciprice2NormProductionStatistics(Preciprice preciprice) {

        NormProductionStatistics rts = new NormProductionStatistics();
        rts.setPosition(preciprice.getPosition());
        rts.setUserName(preciprice.getUserName());
        rts.setUserId(preciprice.getUserId() + "");
        rts.setSex(preciprice.getSex() == 1 ? "男" : "女");
        rts.setAccount(preciprice.getAccount());
        rts.setCoefficient(preciprice.getCoefficient().doubleValue());
        rts.setGroupId(preciprice.getGroupId());
        rts.setGroupName(preciprice.getPosition());
        return rts;
    }

    private <M, T> IPage<T> copyPage(IPage<M> page, List<T> target) {

        IPage<T> rts = new Page<>();
        rts.setCurrent(page.getCurrent());
        rts.setRecords(target);
        rts.setSize(page.getSize());
        rts.setPages(page.getPages());
        rts.setTotal(page.getTotal());
        return rts;
    }

    private void addCount(LocalDateTime date, Map<String, Integer> map) {
        Date nextDate = DateUtil.endOfMonth(asDate(date));
        map.put(nextDate.getMonth() + 1 + "", map.get(nextDate.getMonth() + 1 + "") + 1);
    }

    private void addCount(LocalDate date, Map<String, Integer> map) {
        Date nextDate = DateUtil.endOfMonth(asDate(date));
        map.put(nextDate.getMonth() + 1 + "", map.get(nextDate.getMonth() + 1 + "") + 1);
    }

    private static Date asDate(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    }

    private static Date asDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    private Map<String, Integer> initMonthMoneyMap(long start, long end) {

        Map<String, Integer> map = new LinkedHashMap();
        for (long i = start; i <= end; i = DateUtil.offsetMonth(DateUtil.date(i), 1).getTime()) {
            map.put(DateUtil.endOfMonth(DateUtil.date(i)).getMonth() + 1 + "", 0);
        }
        return map;
    }

    private static long getDefaultStart(long start) {
        //如果没传时间进来   默认开始时间是今天开始时间
        if (start == 0) {
            start = System.currentTimeMillis();
            start = DateUtil.beginOfYear(DateUtil.date(start)).getTime();
        }
        return start;
    }

    private static long getDefaultEnd(long end) {
        //如果没传时间进来   默认开始时间是今天开始时间
        if (end == 0) {
            end = System.currentTimeMillis();
            end = DateUtil.endOfYear(DateUtil.date(end)).getTime();
        }
        return end;
    }

    /**
     * 计算标准产值的工时标准系数 plan
     * 额定工日*建议系数/报出对应分析结果*考核工值*分析占比
     *
     * @param normProduction 标准产值配置对象  如:六元素
     * @param rate           具体的操作占比   如:统计分析  85%
     * @return BigDecimal
     */
    private BigDecimal calculateWorkTimeCoefficient(NormProduction normProduction, Double rate) {
        //计算出工时标准系数:
        //额定工日*建议系数/报出对应分析结果*考核工值*分析占比
        BigDecimal quotaDayBig = BigDecimal.valueOf(normProduction.getQuotaDay());
        BigDecimal coefficientBig = BigDecimal.valueOf(normProduction.getCoefficient());
        BigDecimal reportedAnalyseRtsBig = BigDecimal.valueOf(normProduction.getReportedAnalyseResult());
        BigDecimal assessValueBig = BigDecimal.valueOf(normProduction.getAssessValue());
        BigDecimal analyseRateBig = BigDecimal.valueOf(rate);
        return quotaDayBig.multiply(coefficientBig)
                .divide(reportedAnalyseRtsBig, 6, RoundingMode.HALF_DOWN)
                .multiply(assessValueBig).multiply(analyseRateBig)
                .setScale(6, RoundingMode.HALF_DOWN);
    }
}
