package com.ruoyi.system.service.impl;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.base64.Base64DecodedMultipartFile;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.ChargeDetails;
import com.ruoyi.system.domain.OperationRecord;
import com.ruoyi.system.domain.WorkOrderFj;
import com.ruoyi.system.domain.vo.WordVo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IOperationRecordService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.WorkOrderInfo;
import com.ruoyi.system.service.IWorkOrderInfoService;
import org.springframework.web.multipart.MultipartFile;

import static com.ruoyi.common.constant.UserConstants.*;
import static com.ruoyi.common.utils.DateUtils.*;

/**
 * 工单信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-12
 */
@Service
public class WorkOrderInfoServiceImpl implements IWorkOrderInfoService {
    @Autowired
    private WorkOrderInfoMapper workOrderInfoMapper;

    @Autowired
    private WorkOrderFjMapper workOrderFjMapper;

    @Autowired
    private ChargeDetailsMapper chargeDetailsMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;
    @Autowired
    private IOperationRecordService operationRecordService;
    @Autowired
    private SysUserMapper userMapper;


    /**
     * 查询工单信息
     *
     * @param orderId 工单信息主键
     * @return 工单信息
     */
    @Override
    public WorkOrderInfo selectWorkOrderInfoByOrderId(String orderId) {
        WorkOrderInfo workOrderInfo = workOrderInfoMapper.selectWorkOrderInfoByOrderId(orderId);
        if (workOrderInfo != null) {
            //查询附件
            WorkOrderFj workOrderFj = new WorkOrderFj();
            workOrderFj.setOrderId(orderId);
            //workOrderFj.setType(USER_DISABLE);
            List<WorkOrderFj> workOrderFjs = workOrderFjMapper.selectWorkOrderFjList(workOrderFj);
            if (workOrderFjs != null && !workOrderFjs.isEmpty()) {
                Map<String, List<WorkOrderFj>> map = workOrderFjs.stream().collect(Collectors.groupingBy(WorkOrderFj::getType));
                workOrderInfo.setWorkOrderFjXqList(map.get(ONE));
                workOrderInfo.setWorkOrderFjQmList(map.get(TWO));
                if (map.get(THR) != null && !map.get(THR).isEmpty()) {
                    workOrderInfo.setWorkOrderFjgd(map.get(THR).get(0));
                }
            }
            //查询工单收费详情
            ChargeDetails chargeDetails = new ChargeDetails();
            chargeDetails.setOrderId(orderId);
            List<ChargeDetails> chargeDetails1 = chargeDetailsMapper.selectChargeDetailsList(chargeDetails);
            if (chargeDetails1 != null && !chargeDetails1.isEmpty()) {
                workOrderInfo.setChargeDetailsList(chargeDetails1);
            }

        }
        return workOrderInfo;
    }

    /**
     * 查询工单信息列表
     *
     * @param workOrderInfo 工单信息
     * @return 工单信息
     */
    @Override
    public List<WorkOrderInfo> selectWorkOrderInfoList(WorkOrderInfo workOrderInfo) {
        return workOrderInfoMapper.selectWorkOrderInfoList(workOrderInfo);
    }

    /**
     * 新增工单信息
     *
     * @param workOrderInfo 工单信息
     * @return 结果
     */
    @Override
    public int insertWorkOrderInfo(WorkOrderInfo workOrderInfo) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        workOrderInfo.setUserId(user.getUserId());
        workOrderInfo.setUserName(user.getUserName());
        //生成工单编号（时间戳+4位随机数）
        workOrderInfo.setOrderId(DateUtils.getOrderId());
        workOrderInfo.setCreateTime(DateUtils.getNowDate());
        int i = workOrderInfoMapper.insertWorkOrderInfo(workOrderInfo);
        if (workOrderInfo.getWorkOrderFjXqList() != null && !workOrderInfo.getWorkOrderFjXqList().isEmpty()) {
            for (WorkOrderFj workOrderFj : workOrderInfo.getWorkOrderFjXqList()) {
                workOrderFj.setOrderId(workOrderInfo.getOrderId());
                workOrderFjMapper.insertWorkOrderFj(workOrderFj);
            }
        }

        OperationRecord operationRecord = new OperationRecord();
        operationRecord.setOrderId(workOrderInfo.getOrderId());
        String type = dictDataMapper.selectDictLabel("service_progress", workOrderInfo.getType());
        StringBuilder recod = new StringBuilder();
        recod.append(workOrderInfo.getUnitName()).append("发起了一个").append(type).append(",联系方式").append(workOrderInfo.getPhonenumber());
        operationRecord.setRecord(recod.toString());
        operationRecordService.insertOperationRecord(operationRecord);
        return i;
    }

    /**
     * 修改工单信息
     *
     * @param workOrderInfo 工单信息
     * @return 结果
     */
    @Override
    public int updateWorkOrderInfo(WorkOrderInfo workOrderInfo) {

        if(NO.equals(workOrderInfo.getIsCharge())){
            chargeDetailsMapper.deleteChargeDetailsByOrderId(workOrderInfo.getOrderId());
        }
        if (!THR.equals(workOrderInfo.getServiceProgress())) {
            if (workOrderInfo.getChargeDetailsList() != null && !workOrderInfo.getChargeDetailsList().isEmpty()) {
                //删除收费信息重新保存
                chargeDetailsMapper.deleteChargeDetailsByOrderId(workOrderInfo.getOrderId());
                //删除之后重新保存
                for (ChargeDetails chargeDetails : workOrderInfo.getChargeDetailsList()) {
                    chargeDetails.setOrderId(workOrderInfo.getOrderId());
                    chargeDetailsMapper.insertChargeDetails(chargeDetails);
                }
            }

            if (workOrderInfo.getWorkOrderFjXqList() != null && !workOrderInfo.getWorkOrderFjXqList().isEmpty()) {
                WorkOrderFj orderFj = new WorkOrderFj();
                orderFj.setOrderId(workOrderInfo.getOrderId());
                orderFj.setType(ONE);
                workOrderFjMapper.deleteWorkOrderFj(orderFj);
                for (WorkOrderFj workOrderFj : workOrderInfo.getWorkOrderFjXqList()) {
                    workOrderFj.setOrderId(workOrderInfo.getOrderId());
                    workOrderFjMapper.insertWorkOrderFj(workOrderFj);
                }
            }
            if (workOrderInfo.getWorkOrderFjQmList() != null && !workOrderInfo.getWorkOrderFjQmList().isEmpty()) {
                WorkOrderFj orderFj = new WorkOrderFj();
                orderFj.setOrderId(workOrderInfo.getOrderId());
                orderFj.setType(TWO);
                workOrderFjMapper.deleteWorkOrderFj(orderFj);
                for (WorkOrderFj workOrderFj : workOrderInfo.getWorkOrderFjQmList()) {
                    workOrderFj.setOrderId(workOrderInfo.getOrderId());
                    workOrderFjMapper.insertWorkOrderFj(workOrderFj);
                }
            }
            if (workOrderInfo.getWorkOrderFjgd() != null) {
                WorkOrderFj orderFj = new WorkOrderFj();
                orderFj.setOrderId(workOrderInfo.getOrderId());
                orderFj.setType(THR);
                workOrderFjMapper.deleteWorkOrderFj(orderFj);
                workOrderInfo.getWorkOrderFjgd().setOrderId(workOrderInfo.getOrderId());
                workOrderFjMapper.insertWorkOrderFj(workOrderInfo.getWorkOrderFjgd());
            }
        }
        if (TWO.equals(workOrderInfo.getServiceProgress())) {
            workOrderInfo.setAgency(TWO);

            //操作记录
            OperationRecord operationRecord = new OperationRecord();
            operationRecord.setOrderId(workOrderInfo.getOrderId());
            String type = dictDataMapper.selectDictLabel("service_progress", workOrderInfo.getType());
            StringBuilder recod = new StringBuilder();
            recod.append(workOrderInfo.getUnitName()).append("的").append(type).append("已结束；客户暂无评价");
            operationRecord.setRecord(recod.toString());
            operationRecordService.insertOperationRecord(operationRecord);
        }
        if (THR.equals(workOrderInfo.getServiceProgress())) {
            WorkOrderInfo orderInfo = workOrderInfoMapper.selectWorkOrderInfoByOrderId(workOrderInfo.getOrderId());
            //操作记录
            OperationRecord operationRecord = new OperationRecord();
            operationRecord.setOrderId(workOrderInfo.getOrderId());
            String type = dictDataMapper.selectDictLabel("service_progress", orderInfo.getType());
            StringBuilder recod = new StringBuilder();
            recod.append(orderInfo.getUnitName()).append("的").append(type).append("已结束；客户评价:").append(workOrderInfo.getEvaluationContent());
            operationRecord.setRecord(recod.toString());
            operationRecordService.insertOperationRecord(operationRecord);
        }
        workOrderInfo.setUpdateTime(DateUtils.getNowDate());
        return workOrderInfoMapper.updateWorkOrderInfo(workOrderInfo);
    }

    /**
     * 批量删除工单信息
     *
     * @param orderIds 需要删除的工单信息主键
     * @return 结果
     */
    @Override
    public int deleteWorkOrderInfoByOrderIds(String[] orderIds) {
        return workOrderInfoMapper.deleteWorkOrderInfoByOrderIds(orderIds);
    }

    /**
     * 删除工单信息信息
     *
     * @param orderId 工单信息主键
     * @return 结果
     */
    @Override
    public int deleteWorkOrderInfoByOrderId(String orderId) {
        return workOrderInfoMapper.deleteWorkOrderInfoByOrderId(orderId);
    }

    @Override
    public int jd(WorkOrderInfo workOrderInfo) {
        //操作记录
        WorkOrderInfo orderInfo = workOrderInfoMapper.selectWorkOrderInfoByOrderId(workOrderInfo.getOrderId());
        OperationRecord operationRecord = new OperationRecord();
        operationRecord.setOrderId(workOrderInfo.getOrderId());
        String type = dictDataMapper.selectDictLabel("service_progress", workOrderInfo.getType());
        StringBuilder recod = new StringBuilder();
        recod.append(workOrderInfo.getResponsibleName()).append("接下了").append(orderInfo.getUnitName()).append("的");
        recod.append(type).append("工单：工单编号").append(orderInfo.getOrderId());

        workOrderInfo.setServiceProgress(ONE);
        workOrderInfo.setTakeTime(DateUtils.getNowDate());
        workOrderInfo.setAgency(ONE);

        //自主接单
        if (TWO.equals(workOrderInfo.getOrderPlacement())) {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            workOrderInfo.setResponsibleId(user.getUserId());
            workOrderInfo.setResponsibleName(user.getNickName());
            workOrderInfo.setResponsiblePhone(user.getPhonenumber());
            workOrderInfo.setAgency(TWO);
            recod = new StringBuilder();
            recod.append(workOrderInfo.getResponsibleName()).append("被分派了").append(orderInfo.getUnitName()).append("的");
            recod.append(type).append("工单：工单编号").append(orderInfo.getOrderId());
        }
        operationRecord.setRecord(recod.toString());
        operationRecordService.insertOperationRecord(operationRecord);
        return workOrderInfoMapper.updateWorkOrderInfo(workOrderInfo);
    }

    @Override
    public AjaxResult dzgd(String orderId) {
        //查询工单信息
        WorkOrderInfo workOrderInfo = workOrderInfoMapper.selectWorkOrderInfoByOrderId(orderId);
        //查询工单收费详情
        ChargeDetails chargeDetails = new ChargeDetails();
        chargeDetails.setOrderId(orderId);
        List<ChargeDetails> chargeDetails1 = chargeDetailsMapper.selectChargeDetailsList(chargeDetails);
        if (chargeDetails1 != null && !chargeDetails1.isEmpty()) {
            workOrderInfo.setChargeDetailsList(chargeDetails1);
        }


        HashMap<String, Object> finalMap = new HashMap<>();
        finalMap.put("khmc", workOrderInfo.getUnitName());
        finalMap.put("xmmc", workOrderInfo.getProjectName());
        if (ONE.equals(workOrderInfo.getShelfLife())) {
            finalMap.put("bzqn", true);
            finalMap.put("bzqw", false);
        } else {
            finalMap.put("bzqn", false);
            finalMap.put("bzqw", true);
        }

        if (YES.equals(workOrderInfo.getIsCharge())) {
            finalMap.put("sfs", true);
            finalMap.put("sff", false);
        } else {
            finalMap.put("sfs", false);
            finalMap.put("sff", true);
        }
        finalMap.put("rmbdx", workOrderInfo.getTotalCostDx());
        finalMap.put("rmb", workOrderInfo.getTotalCost());
        finalMap.put("bz", workOrderInfo.getRemark());
        finalMap.put("lxfs", workOrderInfo.getPhonenumber());
        finalMap.put("rq", DateUtils.getDate());
        finalMap.put("bz", workOrderInfo.getRemark());
        finalMap.put("qm", "{{@qm}}");

        List<Object> workList = new ArrayList<>();
        if (chargeDetails1 != null && !chargeDetails1.isEmpty()) {
            for (int i = 0; i < chargeDetails1.size(); i++) {
                HashMap<String, Object> workItem = new HashMap<>();
                workItem.put("xh", i + 1);
                workItem.put("cpmc", chargeDetails1.get(i).getProductName());
                workItem.put("sl", chargeDetails1.get(i).getProductNum());
                workItem.put("dw", chargeDetails1.get(i).getProductUnit());
                workItem.put("dj", chargeDetails1.get(i).getUnitPrice());
                workItem.put("zj", chargeDetails1.get(i).getTotalPrice());
                workList.add(workItem);
            }
        }
        finalMap.put("workList", workList);


        // 插入图片
        /*try {
            //这里也可以是用文件服务器返回的网络文件流
            String pictureUrl = "http://5b0988e595225.cdn.sohucs.com/images/20171013/fec49f59b98041a4a16886893447f746.jpeg";
            pictureUrl = "D:\\xx\\Java项目\\xx\\sxsoft_expert\\staticfile\\下载.png";
            // 从网络流读取图片，置入word模板，等待编译
            if (StringUtils.isNotEmpty(pictureUrl)) {
                //PictureRenderData picture = Pictures.ofUrl(pictureUrl).size(40, 30).create();//网络图片地址
                PictureRenderData picture = Pictures.ofLocal(pictureUrl).size(40, 30).create();//本地图片地址
                finalMap.put("signPicture", picture);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/


        // 从网络url 下载word模板到指定文件夹
        File wordTemplate = new File("D:\\ruoyi\\uploadPath\\gongdan\\muban\\工单模板.docx");
        // 此处使用了poi-tl的<表格行循环插件>，此处一定要进行参数bind，方便word模板参数替换
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure build = Configure.builder().bind(policy, "workList").build();
        XWPFTemplate render = XWPFTemplate.compile(wordTemplate, build).render(finalMap);
        // 此处是利用File，直接在本地创建文件，将参数替换后的文件流写入到该文件，word就是最终的结果
        String fileName = workOrderInfo.getUnitName() + "-" + workOrderInfo.getProjectName() + "项目工单.docx";
        String templatePath = "/profile/upload/" + fileName;
        String path = RuoYiConfig.getUploadPath() + "/" + fileName;
        ;
        File word = new File(path);
        try {
            render.writeToFile(word.getAbsolutePath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //将文件路径存入数据库
        WorkOrderFj workOrderFj = new WorkOrderFj();
        workOrderFj.setOrderId(orderId);
        workOrderFj.setName(fileName);
        workOrderFj.setUrl(templatePath);
        workOrderFj.setType(THR);
        //删除之前生成的文件
        workOrderFjMapper.deleteWorkOrderFj(workOrderFj);
        workOrderFjMapper.insertWorkOrderFj(workOrderFj);
        return AjaxResult.success("成功", templatePath);
    }

    @SneakyThrows
    @Override
    public AjaxResult qm(WordVo wordVo) {
        //查询工单信息
        WorkOrderInfo workOrderInfo = workOrderInfoMapper.selectWorkOrderInfoByOrderId(wordVo.getOrderId());

        String base64String = wordVo.getImage();
        if (base64String.contains("data:")) {
            int start = base64String.indexOf(",");
            base64String = base64String.substring(start + 1);
        }
        base64String = base64String.replaceAll("\r|\n", "");
        base64String = base64String.trim();

        int s = wordVo.getImage().indexOf(",");
        String head = wordVo.getImage().substring(0, s + 1);

        MultipartFile file = Base64DecodedMultipartFile.base64Convert(base64String, head, workOrderInfo.getOrderId() + "签字");
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        //将文件路径存入数据库
        WorkOrderFj workOrderFj = new WorkOrderFj();
        workOrderFj.setOrderId(wordVo.getOrderId());
        workOrderFj.setName(FileUtils.getName(fileName));
        workOrderFj.setUrl(fileName);
        workOrderFj.setType(TWO);
        //删除之前生成的文件
        workOrderFjMapper.deleteWorkOrderFj(workOrderFj);
        workOrderFjMapper.insertWorkOrderFj(workOrderFj);
        //将文件写入word
        WorkOrderFj workFj = new WorkOrderFj();
        workFj.setOrderId(wordVo.getOrderId());
        workFj.setType(THR);
        List<WorkOrderFj> workOrderFjs = workOrderFjMapper.selectWorkOrderFjList(workFj);

        HashMap<String, Object> finalMap = new HashMap<>();
        //这里也可以是用文件服务器返回的网络文件流
        String pictureUrl = fileName.replace("/profile", RuoYiConfig.getProfile());
        // 从网络流读取图片，置入word模板，等待编译
        if (StringUtils.isNotEmpty(pictureUrl)) {
            //PictureRenderData picture = Pictures.ofUrl(pictureUrl).size(100, 60).create();//网络图片地址
            PictureRenderData picture = Pictures.ofLocal(pictureUrl).size(100, 60).create();//本地图片地址
            finalMap.put("qm", picture);
        }
        // 从网络url 下载word模板到指定文件夹
        //http://192.168.101.86:8077 "D:\\ruoyi\\uploadPath\\gongdan\\muban\\工单模板.docx"
        File wordTemplate = new File(RuoYiConfig.getUploadPath() + "/" + workOrderFjs.get(0).getName());
        // 此处使用了poi-tl的<表格行循环插件>，此处一定要进行参数bind，方便word模板参数替换
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure build = Configure.builder().bind(policy, "workList").build();
        XWPFTemplate render = XWPFTemplate.compile(wordTemplate, build).render(finalMap);
        // 此处是利用File，直接在本地创建文件，将参数替换后的文件流写入到该文件，word就是最终的结果
        String name = workOrderInfo.getUnitName() + "-" + workOrderInfo.getProjectName() + "项目工单.docx";
        String templatePath = "/profile/upload/" + name;
        String path = RuoYiConfig.getUploadPath() + "/" + name;
        ;
        File word = new File(path);
        try {
            render.writeToFile(word.getAbsolutePath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        workOrderInfo.setServiceProgress(TWO);
        workOrderInfo.setAgency(TWO);
        workOrderInfoMapper.updateWorkOrderInfo(workOrderInfo);

        //操作记录
        OperationRecord operationRecord = new OperationRecord();
        operationRecord.setOrderId(workOrderInfo.getOrderId());
        String type = dictDataMapper.selectDictLabel("service_progress", workOrderInfo.getType());
        StringBuilder recod = new StringBuilder();
        recod.append(workOrderInfo.getUnitName()).append("的").append(type).append("已结束；客户暂无评价");
        operationRecord.setRecord(recod.toString());
        operationRecordService.insertOperationRecord(operationRecord);

        return AjaxResult.success("成功");
    }

    @Override
    public AjaxResult lc() {

        Map<String, Object> map = new HashMap<>();
        int zs = 0;
        int djd = 0;
        int jxz = 0;
        int ywc = 0;
        int dpj = 0;
        int ypj = 0;
        int szs = 0;
        String zz = "0%";
        //获取当前月
        String month = DateUtils.dateTimeNow(YYYY_MM_DD);
        //获取上个月
        String lastMonth = DateUtils.lastMonth();
        //本月单量
        List<WorkOrderInfo> workOrderInfoList = workOrderInfoMapper.selectWorkOrderInfoListBymonth(month);
        //上个月单量
        List<WorkOrderInfo> lastWorkOrderInfoList = workOrderInfoMapper.selectWorkOrderInfoListBymonth(lastMonth);
        if (lastWorkOrderInfoList != null && !lastWorkOrderInfoList.isEmpty()) {
            szs = lastWorkOrderInfoList.size();
        }
        if (workOrderInfoList != null && !workOrderInfoList.isEmpty()) {
            zs = workOrderInfoList.size();
            Map<String, List<WorkOrderInfo>> workOrderInfomap = workOrderInfoList.stream().collect(Collectors.groupingBy(WorkOrderInfo::getServiceProgress));
            if (workOrderInfomap.get(NORMAL) != null && !workOrderInfomap.get(NORMAL).isEmpty()) {
                djd = workOrderInfomap.get(NORMAL).size();
            }
            if (workOrderInfomap.get(ONE) != null && !workOrderInfomap.get(ONE).isEmpty()) {
                jxz = workOrderInfomap.get(ONE).size();
            }
            if (workOrderInfomap.get(TWO) != null && !workOrderInfomap.get(TWO).isEmpty()) {
                ywc = workOrderInfomap.get(TWO).size();
            }
            if (workOrderInfomap.get(THR) != null && !workOrderInfomap.get(THR).isEmpty()) {
                ypj = workOrderInfomap.get(THR).size();
            }
            BigDecimal bzs = new BigDecimal(zs);
            BigDecimal bszs = new BigDecimal(szs);
            BigDecimal fz = bzs.subtract(bszs);
            BigDecimal percentage = fz.multiply(new BigDecimal("100"))
                    .divide(bzs, 3, RoundingMode.HALF_UP) // 先计算百分比并保留三位小数以处理可能的精度问题
                    .setScale(1, RoundingMode.HALF_UP);     // 再设置为一位小数
            zz = percentage.toString() + "%";

        }
        map.put("zs", zs);
        map.put("djd", djd);
        map.put("jxz", jxz);
        map.put("ywc", ywc);
        map.put("dpj", ypj);
        map.put("zz", zz);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult fw() {
        Map<String, Object> map = new HashMap<>();
        int zs = 0;
        int wlfw = 0;
        int sbfw = 0;
        int rjfw = 0;
        int kffw = 0;
        int sjfw = 0;
        int qtfw = 0;
        //获取当前月
        String month = DateUtils.dateTimeNow(YYYY_MM_DD);
        //本月单量
        List<WorkOrderInfo> workOrderInfoList = workOrderInfoMapper.selectWorkOrderInfoListBymonth(month);
        if (workOrderInfoList != null && !workOrderInfoList.isEmpty()) {
            zs = workOrderInfoList.size();
            Map<String, List<WorkOrderInfo>> workOrderInfomap = workOrderInfoList.stream().collect(Collectors.groupingBy(WorkOrderInfo::getType));

            if (workOrderInfomap.get(ONE) != null && !workOrderInfomap.get(ONE).isEmpty()) {
                wlfw = workOrderInfomap.get(ONE).size();
            }
            if (workOrderInfomap.get(TWO) != null && !workOrderInfomap.get(TWO).isEmpty()) {
                sbfw = workOrderInfomap.get(TWO).size();
            }
            if (workOrderInfomap.get(THR) != null && !workOrderInfomap.get(THR).isEmpty()) {
                rjfw = workOrderInfomap.get(THR).size();
            }
            if (workOrderInfomap.get(FOR) != null && !workOrderInfomap.get(FOR).isEmpty()) {
                kffw = workOrderInfomap.get(FOR).size();
            }
            if (workOrderInfomap.get(FIV) != null && !workOrderInfomap.get(FIV).isEmpty()) {
                sjfw = workOrderInfomap.get(FIV).size();
            }
            if (workOrderInfomap.get(SIX) != null && !workOrderInfomap.get(SIX).isEmpty()) {
                qtfw = workOrderInfomap.get(SIX).size();
            }
        }
        map.put("zs", zs);
        map.put("wlfw", wlfw);
        map.put("sbfw", sbfw);
        map.put("rjfw", rjfw);
        map.put("kffw", kffw);
        map.put("sjfw", sjfw);
        map.put("qtfw", qtfw);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult bj() {
        Map<String, Object> map = new HashMap<>();
        //获取当前月
        String month = DateUtils.dateTimeNow(YYYY_MM_DD);
        //获取上个月
        String lastMonth = DateUtils.lastMonth()+"-01";
        //本月单量
        List<WorkOrderInfo> workOrderInfoList = workOrderInfoMapper.selectWorkOrderInfoListBymonth(month);
        //上个月单量
        List<WorkOrderInfo> lastWorkOrderInfoList = workOrderInfoMapper.selectWorkOrderInfoListBymonth(lastMonth);
        List<String> y = new ArrayList<>();
        List<Integer> x1 = new ArrayList<>();
        List<Integer> x2 = new ArrayList<>();
        y.add("网络服务");
        y.add("设备服务");
        y.add("软件服务");
        y.add("开发服务");
        y.add("设计服务");
        y.add("其他服务");
        //本月
        int wlfw = 0;
        int sbfw = 0;
        int rjfw = 0;
        int kffw = 0;
        int sjfw = 0;
        int qtfw = 0;
        //上月
        int swlfw = 0;
        int ssbfw = 0;
        int srjfw = 0;
        int skffw = 0;
        int ssjfw = 0;
        int sqtfw = 0;
        if (workOrderInfoList != null && !workOrderInfoList.isEmpty()) {
            Map<String, List<WorkOrderInfo>> workOrderInfomap = workOrderInfoList.stream().collect(Collectors.groupingBy(WorkOrderInfo::getType));

            if (workOrderInfomap.get(ONE) != null && !workOrderInfomap.get(ONE).isEmpty()) {
                wlfw = workOrderInfomap.get(ONE).size();
            }
            if (workOrderInfomap.get(TWO) != null && !workOrderInfomap.get(TWO).isEmpty()) {
                sbfw = workOrderInfomap.get(TWO).size();
            }
            if (workOrderInfomap.get(THR) != null && !workOrderInfomap.get(THR).isEmpty()) {
                rjfw = workOrderInfomap.get(THR).size();
            }
            if (workOrderInfomap.get(FOR) != null && !workOrderInfomap.get(FOR).isEmpty()) {
                kffw = workOrderInfomap.get(FOR).size();
            }
            if (workOrderInfomap.get(FIV) != null && !workOrderInfomap.get(FIV).isEmpty()) {
                sjfw = workOrderInfomap.get(FIV).size();
            }
            if (workOrderInfomap.get(SIX) != null && !workOrderInfomap.get(SIX).isEmpty()) {
                qtfw = workOrderInfomap.get(SIX).size();
            }
        }
        if (lastWorkOrderInfoList != null && !lastWorkOrderInfoList.isEmpty()) {
            Map<String, List<WorkOrderInfo>> workOrderInfomap = lastWorkOrderInfoList.stream().collect(Collectors.groupingBy(WorkOrderInfo::getType));

            if (workOrderInfomap.get(ONE) != null && !workOrderInfomap.get(ONE).isEmpty()) {
                swlfw = workOrderInfomap.get(ONE).size();
            }
            if (workOrderInfomap.get(TWO) != null && !workOrderInfomap.get(TWO).isEmpty()) {
                ssbfw = workOrderInfomap.get(TWO).size();
            }
            if (workOrderInfomap.get(THR) != null && !workOrderInfomap.get(THR).isEmpty()) {
                srjfw = workOrderInfomap.get(THR).size();
            }
            if (workOrderInfomap.get(FOR) != null && !workOrderInfomap.get(FOR).isEmpty()) {
                skffw = workOrderInfomap.get(FOR).size();
            }
            if (workOrderInfomap.get(FIV) != null && !workOrderInfomap.get(FIV).isEmpty()) {
                ssjfw = workOrderInfomap.get(FIV).size();
            }
            if (workOrderInfomap.get(SIX) != null && !workOrderInfomap.get(SIX).isEmpty()) {
                sqtfw = workOrderInfomap.get(SIX).size();
            }
        }
        x1.add(wlfw);
        x1.add(sbfw);
        x1.add(rjfw);
        x1.add(kffw);
        x1.add(sjfw);
        x1.add(qtfw);

        x2.add(swlfw);
        x2.add(ssbfw);
        x2.add(srjfw);
        x2.add(skffw);
        x2.add(ssjfw);
        x2.add(sqtfw);
        map.put("y", y);
        map.put("x1", x1);
        map.put("x2", x2);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult statisticsJd() {
        Map<String, Object> map = new HashMap<>();
        int zs = 0;
        int zzjd = 0;
        int zdfp = 0;
        String zzbfb = "0%";
        String zpbfb = "0%";
        //获取季度的开始时间和结束时间
        String startDate = DateUtils.startQuarterly() + " 00:00:00";
        String endDate = DateUtils.endQuarterly() + " 23:59:59";
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<WorkOrderInfo> workOrderInfoList = workOrderInfoMapper.selectWorkOrderInfoListByTime(startDate, endDate, user.getUserId());
        if (workOrderInfoList != null && !workOrderInfoList.isEmpty()) {
            zs = workOrderInfoList.size();
            BigDecimal bzs = new BigDecimal(zs);
            Map<String, List<WorkOrderInfo>> workOrderInfomap = workOrderInfoList.stream().collect(Collectors.groupingBy(WorkOrderInfo::getOrderPlacement));
            if (workOrderInfomap.get(TWO) != null && !workOrderInfomap.get(TWO).isEmpty()) {
                zzjd = workOrderInfomap.get(TWO).size();
                BigDecimal bzhjd = new BigDecimal(zzjd);
                BigDecimal percentage = bzhjd.multiply(new BigDecimal("100"))
                        .divide(bzs, 3, RoundingMode.HALF_UP) // 先计算百分比并保留三位小数以处理可能的精度问题
                        .setScale(1, RoundingMode.HALF_UP);     // 再设置为一位小数
                zzbfb = percentage.toString() + "%";
            }
            if (workOrderInfomap.get(ONE) != null && !workOrderInfomap.get(ONE).isEmpty()) {
                zdfp = workOrderInfomap.get(ONE).size();
                BigDecimal bzdfp = new BigDecimal(zdfp);
                BigDecimal percentage = bzdfp.multiply(new BigDecimal("100"))
                        .divide(bzs, 3, RoundingMode.HALF_UP) // 先计算百分比并保留三位小数以处理可能的精度问题
                        .setScale(1, RoundingMode.HALF_UP);     // 再设置为一位小数
                zpbfb = percentage.toString() + "%";
            }
        }
        map.put("zs", zs);
        map.put("zzjd", zzjd);
        map.put("zdfp", zdfp);
        map.put("zpbfb", zpbfb);
        map.put("zzbfb", zzbfb);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult dbNum() {
        int num = 0;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        WorkOrderInfo workOrderInfo = new WorkOrderInfo();
        workOrderInfo.setDelFlag(NO);
        workOrderInfo.setAgency(ONE);
        workOrderInfo.setResponsibleId(user.getUserId());
        List<WorkOrderInfo> workOrderInfos = workOrderInfoMapper.selectWorkOrderInfoList(workOrderInfo);
        if (workOrderInfos != null && !workOrderInfos.isEmpty()) {
            num = workOrderInfos.size();
        }
        return AjaxResult.success(num);
    }

    @Override
    public AjaxResult monthPx(String time) {
        if (StringUtils.isEmpty(time)) {
            time = DateUtils.dateTimeNow(YYYY_MM_DD);
        }else{
            time = time +"-01";
        }
        //本月单量
        List<WorkOrderInfo> workOrderInfoList = workOrderInfoMapper.selectWorkOrderInfoListBymonthOne(time);
        Map<Long, Integer> map = new HashMap<>();
        if (workOrderInfoList != null && !workOrderInfoList.isEmpty()) {
            Map<Long, List<WorkOrderInfo>> workOrderInfomap = workOrderInfoList.stream().collect(Collectors.groupingBy(WorkOrderInfo::getResponsibleId));
            for (Long s : workOrderInfomap.keySet()) {
                map.put(s, workOrderInfomap.get(s).size());
            }
        }
        // 使用Stream API和Collectors.toList()将entries转换为List
        List<Map.Entry<Long, Integer>> entries = new ArrayList<>(map.entrySet());

        // 根据value排序，这里是升序
        //entries.sort(Map.Entry.comparingByValue());
        // 如果你需要降序，可以这样做：
        entries.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));
        //取前6个
        List<Map<String, Object>> listMap = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            if (entries.size() < i + 1) {
                break;
            }
            Map<String, Object> mapPx = new HashMap<>();
            SysUser sysUser = userMapper.selectUserById(entries.get(i).getKey());
            mapPx.put("xh", i + 1);
            mapPx.put("name", sysUser.getNickName());
            mapPx.put("deptName", sysUser.getDept().getDeptName());
            mapPx.put("num", entries.get(i).getValue());
            listMap.add(mapPx);
        }

        return AjaxResult.success(listMap);
    }

    @Override
    public AjaxResult yearPx(String time) {
        if (StringUtils.isEmpty(time)) {
            time = DateUtils.dateTimeNow(YYYY_MM_DD);
        }else{
            time = time +"-01-01";
        }
        //本年单量
        List<WorkOrderInfo> workOrderInfoList = workOrderInfoMapper.selectWorkOrderInfoListByYearOne(time);
        Map<Long, Integer> map = new HashMap<>();
        if (workOrderInfoList != null && !workOrderInfoList.isEmpty()) {
            Map<Long, List<WorkOrderInfo>> workOrderInfomap = workOrderInfoList.stream().collect(Collectors.groupingBy(WorkOrderInfo::getResponsibleId));
            for (Long s : workOrderInfomap.keySet()) {
                map.put(s, workOrderInfomap.get(s).size());
            }
        }
        // 使用Stream API和Collectors.toList()将entries转换为List
        List<Map.Entry<Long, Integer>> entries = new ArrayList<>(map.entrySet());

        // 根据value排序，这里是升序
        //entries.sort(Map.Entry.comparingByValue());
        // 如果你需要降序，可以这样做：
        entries.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));
        //取前6个
        List<Map<String, Object>> listMap = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            if (entries.size() < i + 1) {
                break;
            }
            Map<String, Object> mapPx = new HashMap<>();
            SysUser sysUser = userMapper.selectUserById(entries.get(i).getKey());
            mapPx.put("xh", i + 1);
            mapPx.put("name", sysUser.getNickName());
            mapPx.put("deptName", sysUser.getDept().getDeptName());
            mapPx.put("num", entries.get(i).getValue());
            listMap.add(mapPx);
        }

        return AjaxResult.success(listMap);
    }

    @Override
    public AjaxResult yearFwlx(String time) {
        if (StringUtils.isEmpty(time)) {
            time = DateUtils.dateTimeNow(YYYY_MM_DD);
        }else{
            time = time +"-01-01";
        }
        Map<String, Object> map = new HashMap<>();
        int zs = 0;
        int wlfw = 0;
        int sbfw = 0;
        int rjfw = 0;
        int kffw = 0;
        int sjfw = 0;
        int qtfw = 0;

        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = 0L;
        //判断角色是不是业务员
        List<SysRole> roles = user.getRoles();
        Boolean bl = false;
        for (SysRole role : roles) {
            if (WORK_USER.equals(role.getRoleKey())) {
                bl = true;
            }
        }
        if (bl) {
            userId = user.getUserId();
        }
        //本年单量
        List<WorkOrderInfo> workOrderInfoList = workOrderInfoMapper.selectWorkOrderInfoListByYear(time, userId);
        if (workOrderInfoList != null && !workOrderInfoList.isEmpty()) {
            zs = workOrderInfoList.size();
            Map<String, List<WorkOrderInfo>> workOrderInfomap = workOrderInfoList.stream().collect(Collectors.groupingBy(WorkOrderInfo::getType));

            if (workOrderInfomap.get(ONE) != null && !workOrderInfomap.get(ONE).isEmpty()) {
                wlfw = workOrderInfomap.get(ONE).size();
            }
            if (workOrderInfomap.get(TWO) != null && !workOrderInfomap.get(TWO).isEmpty()) {
                sbfw = workOrderInfomap.get(TWO).size();
            }
            if (workOrderInfomap.get(THR) != null && !workOrderInfomap.get(THR).isEmpty()) {
                rjfw = workOrderInfomap.get(THR).size();
            }
            if (workOrderInfomap.get(FOR) != null && !workOrderInfomap.get(FOR).isEmpty()) {
                kffw = workOrderInfomap.get(FOR).size();
            }
            if (workOrderInfomap.get(FIV) != null && !workOrderInfomap.get(FIV).isEmpty()) {
                sjfw = workOrderInfomap.get(FIV).size();
            }
            if (workOrderInfomap.get(SIX) != null && !workOrderInfomap.get(SIX).isEmpty()) {
                qtfw = workOrderInfomap.get(SIX).size();
            }
        }
        map.put("zs", zs);
        map.put("wlfw", wlfw);
        map.put("sbfw", sbfw);
        map.put("rjfw", rjfw);
        map.put("kffw", kffw);
        map.put("sjfw", sjfw);
        map.put("qtfw", qtfw);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult yearLc(String time) {
        if (StringUtils.isEmpty(time)) {
            time = DateUtils.dateTimeNow(YYYY_MM_DD);
        }else{
            time = time +"-01-01";
        }
        Map<String, Object> map = new HashMap<>();
        int zs = 0;
        int djd = 0;
        int jxz = 0;
        int ywc = 0;
        int dpj = 0;
        int ypj = 0;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //本年单量
        List<WorkOrderInfo> workOrderInfoList = workOrderInfoMapper.selectWorkOrderInfoListByYear(time, user.getUserId());
        if (workOrderInfoList != null && !workOrderInfoList.isEmpty()) {
            zs = workOrderInfoList.size();
            Map<String, List<WorkOrderInfo>> workOrderInfomap = workOrderInfoList.stream().collect(Collectors.groupingBy(WorkOrderInfo::getServiceProgress));
            if (workOrderInfomap.get(NORMAL) != null && !workOrderInfomap.get(NORMAL).isEmpty()) {
                djd = workOrderInfomap.get(NORMAL).size();
            }
            if (workOrderInfomap.get(ONE) != null && !workOrderInfomap.get(ONE).isEmpty()) {
                jxz = workOrderInfomap.get(ONE).size();
            }
            if (workOrderInfomap.get(TWO) != null && !workOrderInfomap.get(TWO).isEmpty()) {
                ywc = workOrderInfomap.get(TWO).size();
            }
            if (workOrderInfomap.get(THR) != null && !workOrderInfomap.get(THR).isEmpty()) {
                ypj = workOrderInfomap.get(THR).size();
            }

        }
        map.put("zs", zs);
        map.put("djd", djd);
        map.put("jxz", jxz);
        map.put("ywc", ywc);
        map.put("dpj", ypj);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult yearMonth(String time) {
        Map<String, Object> map = new HashMap<>();
        String year = time;
        if (StringUtils.isEmpty(time)) {
            time = DateUtils.dateTimeNow(YYYY_MM_DD);
            year = DateUtils.dateTimeNow(YYYY);
        }else{
            time = time +"-01-01";
        }
        List<String> months = DateUtils.yearMonth(year);
        List<String> monthhz = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            monthhz.add(i+1+"月");
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = 0L;
        //判断角色是不是业务员
        List<SysRole> roles = user.getRoles();
        Boolean bl = false;
        for (SysRole role : roles) {
            if (WORK_USER.equals(role.getRoleKey())) {
                bl = true;
            }
        }
        if (bl) {
            userId = user.getUserId();
        }

        //本年单量
        List<WorkOrderInfo> workOrderInfoList = workOrderInfoMapper.selectWorkOrderInfoListByYear(time, userId);
        List<Integer> numList = new ArrayList<>();

        for (String month : months) {
            int num = 0;
            if (workOrderInfoList != null && !workOrderInfoList.isEmpty()) {
                for (WorkOrderInfo workOrderInfo : workOrderInfoList) {
                    if (DateUtils.dateTime(workOrderInfo.getCreateTime()).contains(month)) {
                        num++;
                    }
                }
            }
            numList.add(num);
        }
        map.put("x", monthhz);
        map.put("y", numList);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult deptLc(String time) {

        if (StringUtils.isEmpty(time)) {
            time = DateUtils.dateTimeNow(YYYY_MM_DD);
        }else{
            time = time +"-01-01";
        }

        Map<String, Object> map = new HashMap<>();
        int zs = 0;
        int djd = 0;
        int jxz = 0;
        int ywc = 0;
        int ypj = 0;

        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysUser use = new SysUser();
        use.setDeptId(user.getDeptId());
        //查询同一部门下的所有人(包括子部门)
        List<SysUser> userList = userMapper.selectUserList(use);
        List<Long> userIds = userList.stream().map(SysUser::getUserId).collect(Collectors.toList());
        List<WorkOrderInfo> workOrderInfoList = workOrderInfoMapper.selectWorkOrderInfoListByUserList(time,userIds);
        if (workOrderInfoList != null && !workOrderInfoList.isEmpty()) {
            zs = workOrderInfoList.size();
            Map<String, List<WorkOrderInfo>> workOrderInfomap = workOrderInfoList.stream().collect(Collectors.groupingBy(WorkOrderInfo::getServiceProgress));
            if (workOrderInfomap.get(NORMAL) != null && !workOrderInfomap.get(NORMAL).isEmpty()) {
                djd = workOrderInfomap.get(NORMAL).size();
            }
            if (workOrderInfomap.get(ONE) != null && !workOrderInfomap.get(ONE).isEmpty()) {
                jxz = workOrderInfomap.get(ONE).size();
            }
            if (workOrderInfomap.get(TWO) != null && !workOrderInfomap.get(TWO).isEmpty()) {
                ywc = workOrderInfomap.get(TWO).size();
            }
            if (workOrderInfomap.get(THR) != null && !workOrderInfomap.get(THR).isEmpty()) {
                ypj = workOrderInfomap.get(THR).size();
            }

        }
        map.put("zs", zs);
        map.put("djd", djd);
        map.put("jxz", jxz);
        map.put("ywc", ywc);
        map.put("dpj", ypj);
        return AjaxResult.success(map);
    }


}
