package org.jeecg.modules.maintenanceWork.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.dynamicStaticAnalysis.dto.AnalysisBatchUnitDeviceDTO;
import org.jeecg.modules.dynamicStaticAnalysis.entity.AnalysisBatchUnitDevice;
import org.jeecg.modules.dynamicStaticAnalysis.mapper.AnalysisBatchUnitDeviceMapper;
import org.jeecg.modules.dynamicStaticAnalysis.mapper.AnalysisBatchUnitDeviceTransfiniteMapper;
import org.jeecg.modules.dynamicStaticAnalysis.vo.AnalysisBatchUnitDeviceTransfiniteVO;
import org.jeecg.modules.dynamicStaticAnalysis.vo.AnalysisBatchUnitDeviceVO;
import org.jeecg.modules.homePage.vo.ToDoDetailVO;
import org.jeecg.modules.maintenanceWork.dto.*;
import org.jeecg.modules.maintenanceWork.entity.WorkBatch;
import org.jeecg.modules.maintenanceWork.entity.WorkBatchDetail;
import org.jeecg.modules.maintenanceWork.entity.WorkBatchDetailModify;
import org.jeecg.modules.maintenanceWork.mapper.WorkBatchDetailMapper;
import org.jeecg.modules.maintenanceWork.mapper.WorkBatchDetailModifyMapper;
import org.jeecg.modules.maintenanceWork.mapper.WorkBatchMapper;
import org.jeecg.modules.maintenanceWork.service.IWorkBatchService;
import org.jeecg.modules.maintenanceWork.vo.WorkBatchDetailVO;
import org.jeecg.modules.maintenanceWork.vo.WorkBatchUserVO;
import org.jeecg.modules.maintenanceWork.vo.WorkBatchVO;
import org.jeecg.modules.unitDevice.dto.CaseReportWorkBatchDTO;
import org.jeecg.modules.unitDevice.vo.CaseReportWorkBatchVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 维修作业管理-作业计划批次管理表 服务实现类
 * </p>
 *
 * @author hkl
 * @since 2023-08-09
 */
@Service
public class WorkBatchServiceImpl extends ServiceImpl<WorkBatchMapper, WorkBatch> implements IWorkBatchService {
    @Resource
    private WorkBatchDetailMapper workBatchDetailMapper;

    @Resource
    private WorkBatchDetailModifyMapper workBatchDetailModifyMapper;

    @Resource
    private AnalysisBatchUnitDeviceMapper analysisBatchUnitDeviceMapper;


    @Resource
    private AnalysisBatchUnitDeviceTransfiniteMapper transfiniteMapper;

    @Override
    public Page<WorkBatchVO> listRecord(Page<WorkBatchVO> pageData, WorkBatchDTO dto) {
        Page<WorkBatchVO> page = this.baseMapper.listRecord(pageData, dto);

        // 作业批次明细,一次性讲当前列表的作业批次相关的详情查询出来通过筛选在重新组装数据
        if (ObjectUtil.isNotEmpty(page.getRecords())) {
            List<String> workBatchIds = page.getRecords().stream().map(WorkBatchVO::getId).collect(Collectors.toList());
            List<WorkBatchDetailVO> workBatchDetailAllList = workBatchDetailMapper.queryListByWorkBatchIds(workBatchIds);
            Map<String, List<WorkBatchDetailVO>> workBatchDetailMap = workBatchDetailAllList.stream().collect(Collectors.groupingBy(WorkBatchDetailVO::getWorkBatchId, LinkedHashMap::new, Collectors.toList()));

            page.getRecords().forEach(record -> {
                List<WorkBatchDetailVO> workBatchDetailList = workBatchDetailMap.get(record.getId());
                workBatchDetailList = workBatchDetailList == null ? new ArrayList<>() : workBatchDetailList;
                record.setDetailList(workBatchDetailList);
            });


            // 作业批次明细-超限列表
            List<String> analysisBatchUnitDeviceIds = workBatchDetailAllList.stream().filter(obj -> obj.getAnalysisBatchUnitDeviceId() != null).map(WorkBatchDetailVO::getAnalysisBatchUnitDeviceId).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(analysisBatchUnitDeviceIds)) {
                List<AnalysisBatchUnitDeviceTransfiniteVO> transfiniteListAll = transfiniteMapper.getTransfiniteListByIds(analysisBatchUnitDeviceIds);
                Map<String, List<AnalysisBatchUnitDeviceTransfiniteVO>> map = transfiniteListAll.stream().collect(Collectors.groupingBy(AnalysisBatchUnitDeviceTransfiniteVO::getAnalysisBatchUnitDeviceId, LinkedHashMap::new, Collectors.toList()));

                workBatchDetailAllList.forEach(record -> {
                    List<AnalysisBatchUnitDeviceTransfiniteVO> transfiniteList = map.get(record.getAnalysisBatchUnitDeviceId());
                    transfiniteList = transfiniteList == null ? new ArrayList<>() : transfiniteList;
                    record.setTransfiniteList(transfiniteList);
                });
            }
        }
        return page;
    }


    @Override
    @Transactional
    public void saveRecord(WorkBatchSaveOrUpdateDTO dto) {
        // 保存主信息
        WorkBatch workBatch = BeanUtil.copyProperties(dto, WorkBatch.class);
        if (ObjectUtil.isEmpty(dto.getId())) {
            workBatch.setId(UUIDGenerator.generate());
            workBatch.setWorkStatus(0);
        }

        this.saveOrUpdate(workBatch);


        // 保证明细信息
        // 先删除
        LambdaQueryWrapper<WorkBatchDetail> delWrapper = Wrappers.lambdaQuery();
        delWrapper.eq(WorkBatchDetail::getWorkBatchId, dto.getId());
        workBatchDetailMapper.delete(delWrapper);
        List<WorkBatchSaveOrUpdateDetailDTO> transfiniteList = dto.getDetailList();
        //获取当前登录人信息
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = user.getUsername();
        for (WorkBatchSaveOrUpdateDetailDTO detailDTO : transfiniteList) {
            WorkBatchDetail workBatchDetail = new WorkBatchDetail();
            workBatchDetail.setId(UUIDGenerator.generate());
            workBatchDetail.setWorkBatchId(workBatch.getId());
            workBatchDetail.setWorkBatchCode(workBatch.getWorkBatchCode());
            workBatchDetail.setUnitId(detailDTO.getUnitId());
            workBatchDetail.setUnitCode(detailDTO.getUnitCode());
            workBatchDetail.setUnitType(detailDTO.getType());
            workBatchDetail.setUnitTypeName(detailDTO.getUnitTypeName());
            workBatchDetail.setUnitDeviceCode(detailDTO.getUnitDeviceCode());
            workBatchDetail.setUnitStartMileage(detailDTO.getUnitStartMileage());
            workBatchDetail.setUnitEndMileage(detailDTO.getUnitEndMileage());
            workBatchDetail.setUnitCenterMileage(detailDTO.getUnitCenterMileage());
            workBatchDetail.setUnitScore(detailDTO.getUnitScore());
            workBatchDetail.setUnitScoreLevel(detailDTO.getUnitScoreLevel());
            workBatchDetail.setRemark(detailDTO.getRemark());
            workBatchDetail.setUpdateTime(new Date());
            workBatchDetail.setCreateTime(new Date());
            workBatchDetail.setCreateBy(username);
            workBatchDetail.setUpdateBy(username);
            workBatchDetail.setWorkStatus(0);
            workBatchDetailMapper.insert(workBatchDetail);
        }
    }

    @Override
    @Transactional
    public void deleteRecord(String workBatchId) {
        LambdaQueryWrapper<WorkBatchDetailModify> delModifyWrapper = Wrappers.lambdaQuery();
        delModifyWrapper.eq(WorkBatchDetailModify::getWorkBatchId, workBatchId);
        workBatchDetailModifyMapper.delete(delModifyWrapper);

        LambdaQueryWrapper<WorkBatchDetail> delWrapper = Wrappers.lambdaQuery();
        delWrapper.eq(WorkBatchDetail::getWorkBatchId, workBatchId);
        workBatchDetailMapper.delete(delWrapper);

        this.removeById(workBatchId);
    }

    @Override
    @Transactional
    public void transfiniteSaveRecord(WorkBatchTransfiniteSaveDTO dto) {
        WorkBatch workBatch = BeanUtil.copyProperties(dto, WorkBatch.class);
        workBatch.setId(UUIDGenerator.generate());
        workBatch.setWorkStatus(0);
        workBatch.setSource(2); // 超限页面
        this.save(workBatch);

        // 保存明细
        //获取当前登录人信息
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = user.getUsername();
        List<DispatchDTO> transfiniteList = dto.getDetailList();
        List<WorkBatchDetail> workBatchDetailList = new ArrayList<>();
        for (DispatchDTO transfiniteDTO : transfiniteList) {
            WorkBatchDetail workBatchDetail = new WorkBatchDetail();
            workBatchDetail.setId(UUIDGenerator.generate());
            workBatchDetail.setWorkBatchId(workBatch.getId());
            workBatchDetail.setWorkBatchCode(workBatch.getWorkBatchCode());
            workBatchDetail.setAnalysisBatchId(transfiniteDTO.getAnalysisBatchId());
            workBatchDetail.setAnalysisBatchCode(transfiniteDTO.getAnalysisBatchCode());
            workBatchDetail.setAnalysisBatchUnitDeviceId(transfiniteDTO.getId());
            workBatchDetail.setUnitId(transfiniteDTO.getUnitId());
            workBatchDetail.setUnitCode(transfiniteDTO.getUnitCode());
            workBatchDetail.setUnitType(transfiniteDTO.getUnitType());
            workBatchDetail.setUnitTypeName(transfiniteDTO.getUnitTypeName());
            workBatchDetail.setUnitDeviceCode(transfiniteDTO.getUnitDeviceCode());
            workBatchDetail.setUnitStartMileage(transfiniteDTO.getUnitStartingMileage());
            workBatchDetail.setUnitEndMileage(transfiniteDTO.getUnitEndMileage());
            workBatchDetail.setUnitCenterMileage(transfiniteDTO.getUnitCenterMileage());
            workBatchDetail.setUnitScore(transfiniteDTO.getUnitScore());
            workBatchDetail.setUnitScoreLevel(Integer.valueOf(transfiniteDTO.getUnitScoreLevel()));
            workBatchDetail.setUnitScoreLevelStr(transfiniteDTO.getUnitScoreLevelStr());
            workBatchDetail.setWorkStatus(0);
            workBatchDetail.setUpdateTime(new Date());
            workBatchDetail.setCreateTime(new Date());
            workBatchDetail.setCreateBy(username);
            workBatchDetail.setUpdateBy(username);

            workBatchDetailList.add(workBatchDetail);

        }
        workBatchDetailMapper.insertBatch(workBatchDetailList);
    }


    @Override
    public Page<Map<String, Object>> getUnitDevicePage(Page<Map<String, Object>> pageData, UnitDeviceDTO dto) {

        return this.baseMapper.getUnitDevicePage(pageData, dto);

    }

    @Override
    @Transactional
    public void batchSaveRecord(AnalysisBatchSaveDTO dto) {
        // 1.构建工单主信息
        WorkBatch workBatch = BeanUtil.copyProperties(dto, WorkBatch.class);
        workBatch.setId(UUIDGenerator.generate());
        workBatch.setWorkStatus(0); // 0-已作业
        workBatch.setSource(2); // 超限页面


        // 2.1 构建查询对象
        AnalysisBatchUnitDeviceDTO params = new AnalysisBatchUnitDeviceDTO();
        params.setAnalysisBatchId(dto.getAnalysisBatchId());
        params.setIsTransfinite(1); // 1-超限
        params.setWorkStatus(0);// 0-未派工

        // 2.1.1 一键全部派工按:照搜索条件来的
        if (dto.getSaveType() == 1) {
            params.setUnitCode(dto.getForm().getUnitCode());
            params.setUnitDeviceCode(dto.getForm().getUnitDeviceCode());
            params.setGradeJudgeList(dto.getForm().getGradeJudgeList());
            params.setUnitTypeList(dto.getForm().getUnitTypeList());
            params.setUnitStartingMileage(dto.getForm().getUnitStartingMileage());
            params.setUnitEndMileage(dto.getForm().getUnitEndMileage());
        }
        // 2.1.2 一键失格派工:只要单元质量评价为失格的
        if (dto.getSaveType() == 2) {
            List<String> gradeJudgeList = new ArrayList<>();
            gradeJudgeList.add("3");
            params.setGradeJudgeList(gradeJudgeList);
        }

        // 2.2 查询
        List<AnalysisBatchUnitDeviceVO> transfiniteList = analysisBatchUnitDeviceMapper.listRecord(params);
        if (ObjectUtil.isEmpty(transfiniteList)) {
            throw JeecgBootException.error("创建失败,没有对应的超限数据");
        }
        // 2.3 循环构建保存对象
        //获取当前登录人信息
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String realname = user.getRealname();
        List<WorkBatchDetail> workBatchDetailList = new ArrayList<>();
        for (AnalysisBatchUnitDeviceVO transfinite : transfiniteList) {
            WorkBatchDetail workBatchDetail = new WorkBatchDetail();
            workBatchDetail.setId(UUIDGenerator.generate());
            workBatchDetail.setWorkBatchId(workBatch.getId());
            workBatchDetail.setWorkBatchCode(workBatch.getWorkBatchCode());
            workBatchDetail.setAnalysisBatchUnitDeviceId(transfinite.getId());
            workBatchDetail.setAnalysisBatchId(transfinite.getAnalysisBatchId());
            workBatchDetail.setAnalysisBatchCode(transfinite.getAnalysisBatchCode());
            workBatchDetail.setUnitId(transfinite.getUnitId());
            workBatchDetail.setUnitCode(transfinite.getUnitCode());
            workBatchDetail.setUnitType(transfinite.getUnitType());
            workBatchDetail.setUnitTypeName(transfinite.getUnitTypeName());
            workBatchDetail.setUnitDeviceCode(transfinite.getUnitDeviceCode());
            workBatchDetail.setUnitStartMileage(transfinite.getUnitStartingMileage());
            workBatchDetail.setUnitEndMileage(transfinite.getUnitEndMileage());
            workBatchDetail.setUnitCenterMileage(transfinite.getUnitCenterMileage());
            workBatchDetail.setUnitScore(Convert.toBigDecimal(transfinite.getUnitScore()));
            workBatchDetail.setUnitScoreLevel(transfinite.getUnitScoreLevel());
            workBatchDetail.setUnitScoreLevelStr(transfinite.getUnitScoreLevelStr());
            workBatchDetail.setUpdateTime(new Date());
            workBatchDetail.setCreateTime(new Date());
            workBatchDetail.setCreateBy(realname);
            workBatchDetail.setUpdateBy(realname);
            workBatchDetail.setWorkStatus(0);
            workBatchDetailList.add(workBatchDetail);
        }


        // 3. 执行数据库保存
        this.save(workBatch);
        workBatchDetailMapper.insertBatch(workBatchDetailList);
    }

    @Override
    public Page<CaseReportWorkBatchVO> caseReportWorkBatch(Page<CaseReportWorkBatchVO> pageData, CaseReportWorkBatchDTO dto) {
        return this.baseMapper.caseReportWorkBatch(pageData, dto);
    }

    @Override
    public List<ToDoDetailVO> getTodoList(String currentUserId) {
        return this.baseMapper.getTodoList(currentUserId);
    }

    @Override
    public List<WorkBatchUserVO> listUser(String query) {
        return this.baseMapper.listUser(query);
    }


}
