package com.ozs.plan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ozs.base.domain.BaseAgency;
import com.ozs.base.domain.BaseNoticeType;
import com.ozs.base.vo.BaseNoticeVo;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.core.domain.entity.SysDept;
import com.ozs.common.core.domain.entity.SysDictData;
import com.ozs.common.core.domain.entity.SysProcurementStandard;
import com.ozs.common.core.domain.entity.SysRole;
import com.ozs.common.core.domain.entity.SysUser;
import com.ozs.common.core.domain.model.LoginUser;
import com.ozs.common.enums.IsExcess;
import com.ozs.common.enums.PmProjectStatus;
import com.ozs.common.enums.ProjectStatus;
import com.ozs.common.enums.ProjectTypes;
import com.ozs.common.enums.SysFileRefEnum;
import com.ozs.common.exception.ServiceException;
import com.ozs.common.utils.SecurityUtils;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.bean.BeanUtils;
import com.ozs.plan.doman.PlanQuarter;
import com.ozs.plan.doman.PlanYears;
import com.ozs.plan.doman.vo.requestVo.PlanYearsStandardVo;
import com.ozs.plan.doman.vo.responseVo.PlanYearsResponseVo;
import com.ozs.plan.mapper.PlanQuarterMapper;
import com.ozs.plan.mapper.PlanYearsMapper;
import com.ozs.plan.service.PlanYearsService;
import com.ozs.pm.doman.PmDemand;
import com.ozs.pm.mapper.PmDemandMapper;
import com.ozs.system.domain.SysFileInfo;
import com.ozs.system.domain.SysFileRef;
import com.ozs.system.domain.SysOperLog;
import com.ozs.system.domain.SysUserRole;
import com.ozs.system.domain.vo.responseVo.SysDeptResponseVo;
import com.ozs.system.mapper.SysDeptMapper;
import com.ozs.system.mapper.SysFileRefMapper;
import com.ozs.system.mapper.SysOperLogMapper;
import com.ozs.system.mapper.SysProcurementStandardMapper;
import com.ozs.system.mapper.SysRoleMapper;
import com.ozs.system.mapper.SysUserRoleMapper;
import com.ozs.system.service.ISysDeptService;
import com.ozs.system.service.ISysDictTypeService;
import com.ozs.system.service.ISysRoleService;
import com.ozs.system.service.ISysUserService;
import com.ozs.system.service.SysFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.validation.Validator;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * @author buzhanyi
 */
@Service
@Slf4j
public class PlanYearsServiceImpl extends ServiceImpl<PlanYearsMapper, PlanYears> implements PlanYearsService {

    @Autowired
    PlanYearsMapper planYearsMapper;
    @Autowired
    PlanQuarterMapper planQuarterMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    SysFileRefMapper sysFileRefMapper;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private SysFileService fileService;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysProcurementStandardMapper sysProcurementStandardMapper;
    @Autowired
    private PmDemandMapper pmDemandMapper;
    @Override
    public PageInfo<PlanYears> selectPlanYearsList(PlanYearsStandardVo vo) {
        PlanYears ofYears = new PlanYears();
        List<PlanYears> planYears;
        List<PlanYears> planYearsList = new ArrayList<>();
        PageHelper.startPage(vo.getPageNum().intValue(), vo.getPageSize().intValue());
        try {
            BeanUtils.copyProperties(vo, ofYears);
            planYears = planYearsMapper.selectPlanYearsList(ofYears);
            planYearsList = changeTo(planYears);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PageInfo<PlanYears> pageInfo = new PageInfo<PlanYears>(planYearsList);
        return pageInfo;
    }

    @Override
    public List<PlanYears> selectPlanYearsListEXP(PlanYearsStandardVo vo) {
        List<PlanYears> list = new ArrayList<>();
        List<PlanYears> planYearsList = new ArrayList<>();
        try {
            int num = 1;
            int size = 200;
            while (size == 200) {
                LambdaQueryWrapper<PlanYears> lw = new LambdaQueryWrapper<PlanYears>();
                if (!ObjectUtils.isEmpty(vo.getProjectName())) {
                    lw.like(PlanYears::getProjectName, vo.getProjectName());
                }
                if (!ObjectUtils.isEmpty(vo.getPurchaseServices())) {
                    lw.eq(PlanYears::getPurchaseServices, vo.getPurchaseServices());
                }
                if (!ObjectUtils.isEmpty(vo.getIsExcess())) {
                    lw.eq(PlanYears::getIsExcess, vo.getIsExcess());
                }
                if (!ObjectUtils.isEmpty(vo.getProjectStatus())) {
                    lw.eq(PlanYears::getProjectStatus, vo.getProjectStatus());
                }
                if (!ObjectUtils.isEmpty(vo.getBeginTime())) {
                    lw.ge(PlanYears::getPlanDemandSubTime, vo.getBeginTime());
                }
                if (!ObjectUtils.isEmpty(vo.getEndTime())) {
                    lw.le(PlanYears::getPlanDemandSubTime, vo.getEndTime());
                }
                Page<PlanYears> page = planYearsMapper.selectPage(new Page<PlanYears>(num, size, false), lw);
                list.addAll(page.getRecords());
                size = page.getRecords().size();
                num++;
            }
            planYearsList = changeTo(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return planYearsList;
    }

    @Override
    public PageInfo<PlanYears> selectPlanYearsExamineList(PlanYearsStandardVo vo) {
        PlanYears ofYears = new PlanYears();
        PageHelper.startPage(vo.getPageNum().intValue(), vo.getPageSize().intValue());
        List<PlanYears> planYears;
        List<PlanYears> planYearsList = new ArrayList<>();
        try {
            BeanUtils.copyProperties(vo, ofYears);
            planYears = planYearsMapper.selectPlanYearsExamineList(ofYears);
            planYearsList = changeTo(planYears);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PageInfo<PlanYears> pageInfo = new PageInfo<PlanYears>(planYearsList);
        return pageInfo;
    }

    @Override
    public List<PlanYears> selectPlanYearsExamineListEXP(PlanYearsStandardVo vo) {
        List<PlanYears> list = new ArrayList<>();
        List<PlanYears> planYearsList = new ArrayList<>();
        try {
            int num = 1;
            int size = 200;
            while (size == 200) {
                LambdaQueryWrapper<PlanYears> lw = new LambdaQueryWrapper<PlanYears>();
                if (!ObjectUtils.isEmpty(vo.getProjectName())) {
                    lw.like(PlanYears::getProjectName, vo.getProjectName());
                }
                if (!ObjectUtils.isEmpty(vo.getPurchaseServices())) {
                    lw.eq(PlanYears::getPurchaseServices, vo.getPurchaseServices());
                }
                if (!ObjectUtils.isEmpty(vo.getIsExcess())) {
                    lw.eq(PlanYears::getIsExcess, vo.getIsExcess());
                }
                if (!ObjectUtils.isEmpty(vo.getProjectStatus())) {
                    lw.eq(PlanYears::getProjectStatus, vo.getProjectStatus());
                } else {
                    lw.in(PlanYears::getProjectStatus, "1,3");
                }
                if (!ObjectUtils.isEmpty(vo.getBeginTime())) {
                    lw.ge(PlanYears::getPlanDemandSubTime, vo.getBeginTime());
                }
                if (!ObjectUtils.isEmpty(vo.getEndTime())) {
                    lw.le(PlanYears::getPlanDemandSubTime, vo.getEndTime());
                }
                Page<PlanYears> page = planYearsMapper.selectPage(new Page<PlanYears>(num, size, false), lw);
                list.addAll(page.getRecords());
                size = page.getRecords().size();
                num++;
            }
            planYearsList = changeTo(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return planYearsList;
    }

    @Transactional
    @Override
    public AjaxResult insertPlanYears(PlanYearsStandardVo yearsStandardVo) {
        if (planYearsMapper.countProjectName(yearsStandardVo.getProjectName()) > 0) {
            return AjaxResult.error("该项目名称已经存在");
        }
        PlanYears ofYears = new PlanYears();
        try {
            BeanUtils.copyProperties(yearsStandardVo, ofYears);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //判断是否为超额计划
        ofYears.setIsExcess(isExcessOrNo(ofYears.getProjectType(), ofYears.getEvaluation()));
        ofYears.setProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode());
        ofYears.setCreateTime(new Date());
        planYearsMapper.insertPlanYears(ofYears);
        log.info("id:{}", ofYears.getPlanYearId());
        List<SysFileRef> sysFileRefs = yearsStandardVo.getSysFileRefs();
        if (!ObjectUtils.isEmpty(sysFileRefs)) {
            for (SysFileRef ref : sysFileRefs) {
                ref.setRedId(ofYears.getPlanYearId());
                ref.setType(SysFileRefEnum.PLAN_YEAR.getType());
                ref.setCreated(ofYears.getCreated());
                ref.setCreateTime(new Date());
                ref.setUpdated(ofYears.getCreated());
                ref.setUpdateTime(new Date());
                sysFileRefMapper.insert(ref);
            }
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deletePlanYearsByIds(Long[] planIds) {
        planYearsMapper.deletePlanYearsByIds(planIds);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deletePlanYearsById(Long planId) {
        planYearsMapper.deletePlanYearsById(planId);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult view(PlanYearsStandardVo yearsStandardVo) {

        PlanYearsResponseVo responseVo = new PlanYearsResponseVo();
        PlanYears byId = planYearsMapper.getById(yearsStandardVo.getPlanYearId());
        byId.getPlanYearId();
        if (byId == null) {
            return AjaxResult.error("数据查询失败");
        }
        SysDeptResponseVo sysDeptResponseVo = (SysDeptResponseVo) deptService.selectDeptById(byId.getPurchaseDeptId()).get("sysDept");
        byId.setPurchaseDeptName(sysDeptResponseVo.getDeptName());
        HashMap<String, Object> map = new HashMap<>();
        map.put("red_id", byId.getPlanYearId());
        map.put("type", SysFileRefEnum.PLAN_YEAR.getType());
        List<SysFileRef> fileRefs = sysFileRefMapper.selectByMap(map);
        List<SysFileInfo> fileInfos = new ArrayList<>();
        BeanUtils.copyProperties(byId, responseVo);
        if (!ObjectUtils.isEmpty(fileRefs)) {
            for (SysFileRef ref : fileRefs) {
                SysFileInfo fileInfo = fileService.getById(ref.getFileId());
                fileInfos.add(fileInfo);
            }
            responseVo.setFileInfos(fileInfos);
        }
        return AjaxResult.success(responseVo);
    }

    @Transactional
    @Override
    public AjaxResult update(PlanYearsStandardVo yearsStandardVo) {
        if (planYearsMapper.countProjectNameOther(yearsStandardVo.getProjectName(), String.valueOf(yearsStandardVo.getPlanYearId())) > 0) {
            return AjaxResult.error("该项目名称已经存在");
        }
        PlanYears ofYears = new PlanYears();
        try {
            BeanUtils.copyProperties(yearsStandardVo, ofYears);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ofYears.setIsExcess(isExcessOrNo(ofYears.getProjectType(), ofYears.getEvaluation()));
        ofYears.setUpdateTime(new Date());
        planYearsMapper.updateInfoById(ofYears);
        List<SysFileRef> sysFileRefs = yearsStandardVo.getSysFileRefs();
        HashMap<String, Object> map = new HashMap<>();
        map.put("red_id", ofYears.getPlanYearId());
        map.put("type", "1");
        sysFileRefMapper.deleteByMap(map);
        if (!ObjectUtils.isEmpty(sysFileRefs)) {
            for (SysFileRef ref : sysFileRefs) {
                ref.setRedId(ofYears.getPlanYearId());
                ref.setType(SysFileRefEnum.PLAN_YEAR.getType());
                ref.setCreated(yearsStandardVo.getUpdated());
                ref.setCreateTime(new Date());
                ref.setUpdated(yearsStandardVo.getUpdated());
                ref.setUpdateTime(new Date());
                sysFileRefMapper.insert(ref);
            }
        }
        return AjaxResult.success();
    }

    @Transactional
    @Override
    public String importPlanYears(List<PlanYearsStandardVo> planYears, boolean isUpdateSupport, LoginUser loginUser) {
        if (StringUtils.isNull(planYears) || planYears.size() == 0) {
            throw new ServiceException("导入年度计划数据不能为空！");
        }
        List<PlanYears> plans = new ArrayList<>();
        for (PlanYearsStandardVo yearsStandardVo : planYears) {
            PlanYears ofYears = new PlanYears();
            BeanUtils.copyProperties(yearsStandardVo, ofYears);
            ofYears.setPurchaseDeptName(yearsStandardVo.getPurchaseDeptId());
            plans.add(ofYears);
        }
        HashMap<String, HashMap<String, String>> planEnums = dictTypeService.getAboutEnums();
        HashMap<String, String> projectTypesMap = planEnums.get("projectTypes");
        HashMap<String, String> planPurchaseModesMap = planEnums.get("planPurchaseModes");
        HashMap<String, String> projectAttributes = planEnums.get("projectAttributes");
        HashMap<String, String> purchaseServices = planEnums.get("purchaseServices");

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        //deptService
        for (PlanYears ofYear : plans) {
            try {
                //验证项目名称是否重复导入
                //将录入信息中的值更改为要保存的数据
                if (planYearsMapper.countProjectName(ofYear.getProjectName()) == 0) {
                    //采购单位
                    SysDept info = deptMapper.checkDeptNameOnlyOne(ofYear.getPurchaseDeptName());
                    if (!ObjectUtils.isEmpty(info)) {
                        ofYear.setPurchaseDeptId(info.getDeptId());
                    } else {
                        ++failureNum;
                        failureMsg.append("*" + failureNum + "*采购单位“" + ofYear.getPurchaseDeptName() + "”不存在");
                    }
                    ofYear.setProjectType(projectTypesMap.get(ofYear.getProjectType()));
                    ofYear.setProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode());
                    ofYear.setPurchaseMode(planPurchaseModesMap.get(ofYear.getPurchaseMode()));
                    //项目属性是多选字段
                    StringBuilder builder = new StringBuilder();
                    if (ofYear.getProjectAttr().contains(",")) {
                        String[] split = ofYear.getProjectAttr().split(",");
                        for (String s : split) {
                            builder.append(projectAttributes.get(s) + ",");
                        }
                    } else {
                        builder.append(projectAttributes.get(ofYear.getProjectAttr()));
                    }
                    ofYear.setProjectAttr(builder.toString());
                    ofYear.setPurchaseServices(purchaseServices.get(ofYear.getPurchaseServices()));
                    ofYear.setIsExcess(isExcessOrNo(ofYear.getProjectType(), ofYear.getEvaluation()));
                    ofYear.setCreated(String.valueOf(loginUser.getUserId()));
                    ofYear.setCreateTime(new Date());
                    planYearsMapper.insertPlanYears(ofYear);
                    successNum++;
                    successMsg.append("*" + successNum + "、项目 " + ofYear.getProjectName() + " 导入成功!");
                    //} else if (isUpdateSupport) {
                    //    PlanYears years = plan.get(0);
                    //    BeanValidators.validateWithException(validator, ofYear);
                    //    years.setCreateTime(new Date());
                    //    years.setProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode());
                    //    planYearsMapper.updateById(years);
                    //    successNum++;
                    //    successMsg.append("<br/>" + successNum + "、项目 " + ofYear.getProjectName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append(failureNum + "*项目 " + ofYear.getProjectName() + " 已存在！/n");
                }
            } catch (Exception exc) {
                failureNum++;
                String msg = "*" + successNum + "*项目 " + ofYear.getProjectName() + " 导入失败";
                failureMsg.append(msg + exc.getMessage());
                log.error(msg, exc);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "导入失败！共 " + failureNum + " 条数据格式不正确：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "导入成功！共 " + successNum + " 条。");
        }
        return successMsg.toString();
    }

    @Override
    public AjaxResult commit(PlanYearsStandardVo yearsStandardVo) {
        //PlanYears byId = PlanYearsMapper.getById(yearsStandardVo.getPlanYearId());
        //BigDecimal evaluation = byId.getEvaluation();
        //BigDecimal threshold = new BigDecimal(0);
        ////获取各个项目类型设定的概算金额阈值
        //List<SysDictData> data = dictTypeService.selectDictDataByType("sys_over_limit_threshold");
        //HashMap<String, String> thresholdMap = new LinkedHashMap<>();
        ////各个类型的概算金额阈值
        //for (SysDictData dictData : data) {
        //    //    类型----阈值
        //    thresholdMap.put(dictData.getDictLabel(), dictData.getDictValue());
        //}
        ////项目类型
        //for (ProjectTypes value : ProjectTypes.values()) {
        //    if (byId.getProjectType().equals(value.getCode())) {
        //        threshold = BigDecimal.valueOf(Long.parseLong(thresholdMap.get(value.getInfo())));
        //    }
        //    break;
        //}
        //
        //if (evaluation.compareTo(threshold) == 1) {
        //    //是超额项目
        //}

        int commit = planYearsMapper.commit(yearsStandardVo.getPlanYearId());
        if (commit != 1) {
            return AjaxResult.error("项目状态数据异常");
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult reviewTo(PlanYearsStandardVo vo) {
        PlanYears ofYears = new PlanYears();
        BeanUtils.copyProperties(vo, ofYears);
        //年度计划审核通过后同步到季度计划
        PlanYears byId = planYearsMapper.getById(vo.getPlanYearId());
        PlanQuarter quarters = new PlanQuarter();
        BeanUtils.copyProperties(byId, quarters);
        planQuarterMapper.insertPlanQuarter(quarters);
        ofYears.setPlanYearId(vo.getPlanYearId());
        ofYears.setProjectStatus(ProjectStatus.PLANTOEXAMINE.getCode());
        return review(vo, ofYears);
    }

    @Override
    @Transactional
    public AjaxResult reviewReturn(PlanYearsStandardVo vo) {
        PlanYears ofYears = new PlanYears();
        BeanUtils.copyProperties(vo, ofYears);
        ofYears.setProjectStatus(ProjectStatus.PLANTOBACK.getCode());
        return review(vo, ofYears);
    }

    private AjaxResult review(PlanYearsStandardVo vo, PlanYears ofYears) {
        List<SysFileRef> sysFileRefs = vo.getSysFileRefs();
        if (!ObjectUtils.isEmpty(sysFileRefs)) {
            for (SysFileRef ref : sysFileRefs) {
                ref.setRedId(vo.getPlanYearId());
                ref.setType(SysFileRefEnum.PLAN_YEAR_EXAMINE.getType());
                ref.setCreated(vo.getUpdated());
                ref.setCreateTime(new Date());
                ref.setUpdated(vo.getUpdated());
                ref.setUpdateTime(new Date());
                sysFileRefMapper.insert(ref);
            }
        }
        int review = planYearsMapper.review(ofYears);
        if (review != 1) {
            return AjaxResult.error("项目状态数据异常");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult appUpdate(PlanYearsStandardVo vo) {
        PlanYears ofYears = new PlanYears();
        BeanUtils.copyProperties(vo, ofYears);
        //申请后会成为未提交的状态，可以进行修改
        ofYears.setProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode());
        int review = planYearsMapper.review(ofYears);
        if (review != 1) {
            return AjaxResult.error("项目状态数据异常");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult sendLetter(PlanYearsStandardVo yearsStandardVo) {
        int review = planYearsMapper.sendLetter(yearsStandardVo.getPlanYearId());
        if (review != 1) {
            return AjaxResult.error("项目状态数据异常");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult upLoadPlanFile(PlanYearsStandardVo yearsStandardVo) {
        List<SysFileRef> sysFileRefs = yearsStandardVo.getSysFileRefs();
        if (!ObjectUtils.isEmpty(sysFileRefs)) {
            for (SysFileRef ref : sysFileRefs) {
                ref.setRedId(yearsStandardVo.getPlanYearId());
                ref.setType(SysFileRefEnum.PLAN_YEAR.getType());
                sysFileRefMapper.insert(ref);
            }
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult downLoadPlanFile(PlanYearsStandardVo yearsStandardVo) {

        return AjaxResult.success();
    }

    @Override
    public AjaxResult demandUnitPlanManagementTotal() {
        List<PlanYears> planYears = new ArrayList<>();
        try {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("demand_unit")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                QueryWrapper<PlanYears> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("purchase_dept_id", sysDept.getDeptId());
                planYears = planYearsMapper.selectList(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(planYears.size());
    }

    @Override
    public AjaxResult purchasingManagementPurchasingManagementTotal() {
        List<PlanYears> planYears = new ArrayList<>();
        try {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("demand_unit")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                List<SysDept> sysDepts = deptMapper.selectChildrenDeptById(sysDept.getDeptId());
                List<Long> collect = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
                if (collect.size()==0){
                    collect.add(-1L);
                }
                QueryWrapper<PlanYears> queryWrapper = new QueryWrapper<>();
                queryWrapper
                        .or(wrapper -> wrapper.lambda().eq(PlanYears::getPurchaseDeptId, sysDept.getDeptId())
                        .eq(PlanYears::getIsExcess, IsExcess.NO_EXCESS.getCode()))
                        .or(wrapper -> wrapper.lambda().in(PlanYears::getPurchaseDeptId, collect)
                        .eq(PlanYears::getIsExcess, IsExcess.EXCESS.getCode()))
                        .in("project_status",ProjectStatus.PLANWAIEXAMINE.getCode(),ProjectStatus.PLANTOEXAMINE.getCode());
                planYears = planYearsMapper.selectList(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(planYears.size());
    }

    @Override
    public AjaxResult demandUnitDemandManagementTotal() {
        List<PmDemand> pmDemands = new ArrayList<>();
        try {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("purchasing_management")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                QueryWrapper<PmDemand> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("purchase_dept_id", sysDept.getDeptId());
                pmDemands =pmDemandMapper.selectList(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(pmDemands.size());
    }

    @Override
    public AjaxResult purchasingManagementDemandManagementTotal() {
        List<PmDemand> pmDemands = new ArrayList<>();
        try {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("demand_unit")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                List<SysDept> sysDepts = deptMapper.selectChildrenDeptById(sysDept.getDeptId());
                List<Long> collect = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
                if (collect.size()==0){
                    collect.add(-1L);
                }
                QueryWrapper<PmDemand> queryWrapper = new QueryWrapper<>();
                queryWrapper
                        .or(wrapper -> wrapper.lambda().eq(PmDemand::getPurchaseDeptId, sysDept.getDeptId())
                                .eq(PmDemand::getIsExcess, IsExcess.NO_EXCESS.getCode()))
                        .or(wrapper -> wrapper.lambda().in(PmDemand::getPurchaseDeptId, collect)
                                .eq(PmDemand::getIsExcess, IsExcess.EXCESS.getCode()))
                        .in("project_status",PmProjectStatus.DEMAND_WAIT_AUDIT.getCode(),PmProjectStatus.DEMAND_AUDIT_RETURN.getCode());
                pmDemands = pmDemandMapper.selectList(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(pmDemands.size());
    }

    @Override
    public AjaxResult demandUnitContractManagementTotal() {
        List<PmDemand> pmDemands = new ArrayList<>();
        try {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("purchasing_management")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                QueryWrapper<PmDemand> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("purchase_dept_id", sysDept.getDeptId());
                queryWrapper.in("project_status",PmProjectStatus.CONTRACT_WAIT_FILL.getCode(),PmProjectStatus.UNDER_CONSTRUCTION.getCode());
                pmDemands =pmDemandMapper.selectList(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(pmDemands.size());
    }

    @Override
    public AjaxResult demandUnitConstructionManagementTotal() {
        List<PmDemand> pmDemands = new ArrayList<>();
        try {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("purchasing_management")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                QueryWrapper<PmDemand> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("purchase_dept_id", sysDept.getDeptId());
                queryWrapper.in("project_status",PmProjectStatus.UNDER_CONSTRUCTION.getCode(),PmProjectStatus.COMPLETION_CONSTRUCTION.getCode());
                pmDemands =pmDemandMapper.selectList(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(pmDemands.size());
    }

    @Override
    public AjaxResult purchasingManagementTaskReleaseTotal() {
        List<PmDemand> pmDemands = new ArrayList<>();
        try {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("demand_unit")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                List<SysDept> sysDepts = deptMapper.selectChildrenDeptById(sysDept.getDeptId());
                List<Long> collect = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
                if (collect.size()==0){
                    collect.add(-1L);
                }
                QueryWrapper<PmDemand> queryWrapper = new QueryWrapper<>();
                queryWrapper
                        .or(wrapper -> wrapper.lambda().eq(PmDemand::getPurchaseDeptId, sysDept.getDeptId())
                                .eq(PmDemand::getIsExcess, IsExcess.NO_EXCESS.getCode()))
                        .or(wrapper -> wrapper.lambda().in(PmDemand::getPurchaseDeptId, collect)
                                .eq(PmDemand::getIsExcess, IsExcess.EXCESS.getCode()))
                        .in("project_status",PmProjectStatus.TASK_WAIT_RELEASE.getCode(),
                                PmProjectStatus.WAIT_SELECT_AGENT.getCode(),
                                PmProjectStatus.WAIT_UPLOAD_BID_FILE.getCode(),
                                PmProjectStatus.WAIT_ANNOUNCEMENT.getCode(),
                                PmProjectStatus.WAIT_OPEN_BID.getCode(),
                                PmProjectStatus.WAIT_BID_ANNOUNCEMENT.getCode(),
                                PmProjectStatus.BIDDING_PUBLICITY.getCode()
                        );
                pmDemands = pmDemandMapper.selectList(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(pmDemands.size());
    }

    @Override
    public AjaxResult procurementOfficeProcurementExecutionTotal() {
        List<PmDemand> pmDemands = new ArrayList<>();
        try {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("demand_unit")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                List<SysDept> sysDepts = deptMapper.selectChildrenDeptById(sysDept.getDeptId());
                List<Long> collect = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
                if (collect.size()==0){
                    collect.add(-1L);
                }
                QueryWrapper<PmDemand> queryWrapper = new QueryWrapper<>();
                queryWrapper
                        .or(wrapper -> wrapper.lambda().eq(PmDemand::getPurchaseDeptId, sysDept.getDeptId())
                                .eq(PmDemand::getIsExcess, IsExcess.NO_EXCESS.getCode()))
                        .or(wrapper -> wrapper.lambda().in(PmDemand::getPurchaseDeptId, collect)
                                .eq(PmDemand::getIsExcess, IsExcess.EXCESS.getCode()))
                        .in("project_status",
                                PmProjectStatus.WAIT_SELECT_AGENT.getCode(),
                                PmProjectStatus.WAIT_UPLOAD_BID_FILE.getCode(),
                                PmProjectStatus.WAIT_ANNOUNCEMENT.getCode(),
                                PmProjectStatus.WAIT_OPEN_BID.getCode(),
                                PmProjectStatus.WAIT_BID_ANNOUNCEMENT.getCode(),
                                PmProjectStatus.BIDDING_PUBLICITY.getCode(),
                                PmProjectStatus.CONTRACT_WAIT_FILL.getCode());
                pmDemands = pmDemandMapper.selectList(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(pmDemands.size());
    }

    @Override
    public AjaxResult procurementOfficeWinningTheBidTotal() {
        List<PmDemand> pmDemands = new ArrayList<>();
        try {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("demand_unit")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                List<SysDept> sysDepts = deptMapper.selectChildrenDeptById(sysDept.getDeptId());
                List<Long> collect = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
                if (collect.size()==0){
                    collect.add(-1L);
                }
                QueryWrapper<PmDemand> queryWrapper = new QueryWrapper<>();
                queryWrapper
                        .or(wrapper -> wrapper.lambda().eq(PmDemand::getPurchaseDeptId, sysDept.getDeptId())
                                .eq(PmDemand::getIsExcess, IsExcess.NO_EXCESS.getCode()))
                        .or(wrapper -> wrapper.lambda().in(PmDemand::getPurchaseDeptId, collect)
                                .eq(PmDemand::getIsExcess, IsExcess.EXCESS.getCode()))
                        .lt("project_status",PmProjectStatus.CONTRACT_WAIT_FILL.getCode());
                pmDemands = pmDemandMapper.selectList(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(pmDemands.size());
    }

    @Override
    public AjaxResult procurementOfficeFailureToWinTheBidTotal() {
        List<PmDemand> pmDemands = new ArrayList<>();
        try {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("demand_unit")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                List<SysDept> sysDepts = deptMapper.selectChildrenDeptById(sysDept.getDeptId());
                List<Long> collect = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
                if (collect.size()==0){
                    collect.add(-1L);
                }
                QueryWrapper<PmDemand> queryWrapper = new QueryWrapper<>();
                queryWrapper
                        .or(wrapper -> wrapper.lambda().eq(PmDemand::getPurchaseDeptId, sysDept.getDeptId())
                                .eq(PmDemand::getIsExcess, IsExcess.NO_EXCESS.getCode()))
                        .or(wrapper -> wrapper.lambda().in(PmDemand::getPurchaseDeptId, collect)
                                .eq(PmDemand::getIsExcess, IsExcess.EXCESS.getCode()))
                        .gt("project_status",PmProjectStatus.CONTRACT_WAIT_FILL.getCode());
                pmDemands = pmDemandMapper.selectList(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(pmDemands.size());
    }

    //判断是否为超额计划
    public String isExcessOrNo(String projectType, BigDecimal evaluation) {
        BigDecimal threshold = new BigDecimal(0);
        //获取各个项目类型设定的概算金额阈值
        List<SysDictData> data = dictTypeService.selectDictDataByType("sys_over_limit_threshold");
        HashMap<String, String> thresholdMap = new LinkedHashMap<>();
        //各个类型的概算金额阈值
        for (SysDictData dictData : data) {
            //    类型----阈值
            thresholdMap.put(dictData.getDictLabel(), dictData.getDictValue());
        }
        //项目类型
        for (ProjectTypes value : ProjectTypes.values()) {
            if (projectType.equals(value.getCode())) {
                threshold = BigDecimal.valueOf(Long.parseLong(thresholdMap.get(value.getInfo())));
            }
            break;
        }
        if (evaluation.compareTo(threshold) == 1) {
            //是超额计划
            return ("1");
        } else {
            return ("0");
        }
    }

    //字段赋值对应的名称
    public List<PlanYears> changeTo(List<PlanYears> planYears) {

        HashMap<String, HashMap<String, String>> planEnums = dictTypeService.getAboutEnums();
        HashMap<String, String> projectTypesMap = planEnums.get("projectTypes");
        HashMap<String, String> planPurchaseModesMap = planEnums.get("planPurchaseModes");
        HashMap<String, String> projectAttributes = planEnums.get("projectAttributes");
        HashMap<String, String> purchaseServices = planEnums.get("purchaseServices");
        List<PlanYears> list = new ArrayList<PlanYears>();
        for (PlanYears planYear : planYears) {
            SysDeptResponseVo sysDeptResponseVo = (SysDeptResponseVo) deptService.selectDeptById(planYear.getPurchaseDeptId()).get("sysDept");
            planYear.setPurchaseDeptName(sysDeptResponseVo.getDeptName());

            for (Map.Entry<String, String> entry : projectTypesMap.entrySet()) {
                if (planYear.getProjectType().equals(entry.getValue())) {
                    planYear.setProjectTypeStr(entry.getKey());
                    break;
                }
            }
            for (Map.Entry<String, String> entry : planPurchaseModesMap.entrySet()) {
                if (planYear.getPurchaseMode().equals(entry.getValue())) {
                    planYear.setPurchaseModeStr(entry.getKey());
                    break;
                }
            }
            //项目属性是拼接的
            if (!ObjectUtils.isEmpty(planYear.getProjectAttr())) {
                if (planYear.getProjectAttr().length() > 1) {
                    StringBuilder builder = new StringBuilder();
                    String[] split = planYear.getProjectAttr().split(",");
                    for (String s : split) {
                        for (Map.Entry<String, String> entry : projectAttributes.entrySet()) {
                            if (s.equals(entry.getValue())) {
                                builder.append(entry.getKey() + ",");
                                break;
                            }
                        }
                    }
                    planYear.setProjectAttrStr(builder.toString());
                } else {
                    for (Map.Entry<String, String> entry : projectAttributes.entrySet()) {
                        if (planYear.getProjectAttr().equals(entry.getValue())) {
                            planYear.setProjectAttrStr(entry.getKey());
                            break;
                        }
                    }
                }
            }
            for (Map.Entry<String, String> entry : purchaseServices.entrySet()) {
                if (planYear.getPurchaseServices().equals(entry.getValue())) {
                    planYear.setPurchaseServicesStr(entry.getKey());
                    break;
                }
            }

            list.add(planYear);
        }
        return list;
    }
}
