/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.gpsboot.service.paln.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.common.system.AuditSateEnum;
import com.tofly.gpsboot.common.system.FileTableEnum;
import com.tofly.gpsboot.common.system.IsValidEnum;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.mapper.plan.PlanMtMapper;
import com.tofly.gpsboot.service.comm.IFileInfoService;
import com.tofly.gpsboot.service.paln.PlanMtRelService;
import com.tofly.gpsboot.service.paln.PlanMtService;
import com.tofly.gpsboot.service.paln.PlanchildtypeService;
import com.tofly.gpsboot.service.paln.PlantypeService;
import com.tofly.gpsboot.service.paln.task.PlanService;
import com.tofly.gpsboot.service.paln.task.PlanchildService;
import com.tofly.gpsboot.service.report.IReportPlanMtServer;
import com.tofly.pojo.plan.*;
import com.tofly.pojo.plan.dto.ReportAuditDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 计划维护记录表
 *
 * @author admin
 * @date Tue Jan 25 00:00:00 CST 2022
 */
@Service("planMtService")
public class PlanMtServiceImpl extends ServiceImpl<PlanMtMapper, PlanMt> implements PlanMtService {

    @Autowired
    private PlanService planService;
    @Autowired
    private PlanchildService planchildService;
    @Autowired
    private IFileInfoService iFileInfoService;

    @Value("${xrty.ftp.planMtFilePath}")
    private String planMtFilePath;

    @Autowired
    private PlanMtRelService planMtRelService;
    @Autowired
    private IReportPlanMtServer iReportPlanMtServer;

    @Autowired
    private PlantypeService plantypeService;

    @Autowired
    private PlanchildtypeService planchildtypeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveInfo(List<MultipartFile> fileList, PlanMt planMt) {
        // 获取当前计划下设备上传数
        Long planId = planMt.getPlanId();
        Plan plan = planService.getById(planId);
        int planNum = plan.getTotalCount().intValue();
        // 判断当前上传设备记录有效数是否超出计划数
        List<String> auditList = new ArrayList<>();
        auditList.add(AuditSateEnum.AUDIT_UNCOMMITTED.getCode());
        auditList.add(AuditSateEnum.AUDIT_YES.getCode());
        int count = this.list(new QueryWrapper<PlanMt>().lambda()
                .eq(PlanMt::getPlanId, planId)
                .in(PlanMt::getAuditResult, auditList)
        ).size();
        if (planNum <= count) {
            throw new BusinessException(Constant.PLAN_MAINTAIN_ADD_ERROR_CODE, Constant.PLAN_MAINTAIN_ADD_ERROR);
        }
        // 原文件
        String fileIdsOne = planMt.getFileIdsOne();
        String fileIdsTow = planMt.getFileIdsTow();
        String fileIdsThree = planMt.getFileIdsThree();

        if (null != fileList && fileList.size() > 0) {
            Map<String, String> stringListMap = new HashMap<>(12);
            Map<String, List<MultipartFile>> fileMap = new HashMap<>(12);
            String key1 = "1";
            String key2 = "2";
            String key3 = "3";
            fileList.forEach(file -> {
                // 分层 前/中/后 文件名称前缀分别新增1 2 3
                String originalFilename = file.getOriginalFilename();
                assert originalFilename != null;
                String[] split = originalFilename.split(Constant.DATE_TILDE);
                String flag = split[0];
                if (key1.equals(flag)) {
                    disposeFile(fileMap, key1, file);
                } else if (key2.equals(flag)) {
                    disposeFile(fileMap, key2, file);
                } else {
                    disposeFile(fileMap, key3, file);
                }

            });
            fileMap.forEach((k, v) -> {
                StringBuilder builder = iFileInfoService.saveFileList(v, planMtFilePath, FileTableEnum.TF_YMPN_PLAN_MT_W.getTableName());
                stringListMap.put(k, builder.toString());
            });
            String one = stringListMap.get(key1);
            String tow = stringListMap.get(key2);
            String three = stringListMap.get(key3);
            if(!StringUtils.isEmpty(one)){
               if(!StringUtils.isEmpty(fileIdsOne)){
                   fileIdsOne = fileIdsOne + Constant.CSV + one;
               }else {
                   fileIdsOne = one;
               }
            }
            if(!StringUtils.isEmpty(tow)){
                if(!StringUtils.isEmpty(fileIdsTow)){
                    fileIdsTow = fileIdsTow + Constant.CSV + tow;
                }else {
                    fileIdsTow = tow;
                }
            }
            if(!StringUtils.isEmpty(three)){
                if(!StringUtils.isEmpty(fileIdsThree)){
                    fileIdsThree = fileIdsThree + Constant.CSV + three;
                }else {
                    fileIdsThree = three;
                }
            }


        }
        planMt.setFileIdsOne(fileIdsOne);
        planMt.setFileIdsTow(fileIdsTow);
        planMt.setFileIdsThree(fileIdsThree);
        boolean save = this.save(planMt);
        // 处理计划维护处理关联信息
        List<PlanMtRel> contentList = planMt.getContentList();
        contentList.forEach(info -> {
            info.setMaintainId(planMt.getId());
            planMtRelService.save(info);
        });
        int sum = count + 1;
        // 计算当前设备完成率
        List<Plantype> planTypeList = plantypeService.list(new QueryWrapper<Plantype>().lambda().eq(Plantype::getPlanId, planId));
        // 一个计划一个类型
        Plantype plantype = planTypeList.get(0);
        BigDecimal totalCount = plantype.getTotalCount();
        plantype.setOverEquipmentCount(BigDecimal.valueOf(sum));
        BigDecimal multiply = BigDecimal.valueOf(sum).divide(totalCount, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
        plantype.setEquipmentRate(multiply);
        plantype.setLossEquipmentRate((totalCount.subtract(BigDecimal.valueOf(sum))).divide(totalCount, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
        plantypeService.updateById(plantype);
        // 计算个人完成率
        Long userId = SecurityUtils.getUserId();
        List<Planchild> list = planchildService.list(new QueryWrapper<Planchild>().lambda()
                .eq(Planchild::getPlanId, planId).eq(Planchild::getRespUser, userId));
        Planchild planchild = list.get(0);
        List<Planchildtype> planChildTypeList = planchildtypeService.list(new QueryWrapper<Planchildtype>().lambda()
                .eq(Planchildtype::getPlanChildId, planchild.getId())
                .eq(Planchildtype::getUserId, userId));
        if (null != planChildTypeList && planChildTypeList.size() > 0) {
            Planchildtype planchildtype = planChildTypeList.get(0);
            BigDecimal add = BigDecimal.ONE.add(planchildtype.getOverEquipmentCount()==null?BigDecimal.ZERO:planchildtype.getOverEquipmentCount());
            planchildtype.setOverEquipmentCount(add);
            planchildtype.setEquipmentRate(add.divide(totalCount, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
            planchildtypeService.updateById(planchildtype);
        } else {
            Planchildtype planchildtype = new Planchildtype();
            planchildtype.setPlanChildId(planchild.getId());
            planchildtype.setUserId(planchild.getRespUser());
            planchildtype.setTotalCount(totalCount);
            planchildtype.setTotalLength(plantype.getTotalLength());
            planchildtype.setTypeId(plantype.getTypeId());
            planchildtype.setOverEquipmentCount(BigDecimal.valueOf(sum));
            planchildtype.setEquipmentRate(multiply);
            planchildtypeService.save(planchildtype);
        }

        // 判断当前维护计划上传数量是否达标
        if (planNum == sum) {
            // 对当前计划派工人 发送审核消息/代办信息/当前计划状态设置为待审核
            ReportAuditDto dto = new ReportAuditDto();
            dto.setAuditId(plan.getCreateUser());
            dto.setId(planId);
            iReportPlanMtServer.report(dto);
        }
        return save;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateInfo(List<MultipartFile> fileList, PlanMt planMt) {
        String isHis = planMt.getIsHis();
        // 判断是否为驳回后的数据
        if ("1".equals(isHis)) {
            // 设置无效
            planMt.setFlag("0");
            this.updateById(planMt);
            // id设置为null isHis设置为0 有效设置为1 审核信息清空
            planMt.setIsHis("0");
            planMt.setFlag("1");
            planMt.setAuditResult(null);
            planMt.setAuditNote(null);
            planMt.setAuditTime(null);
            planMt.setAuditUser(null);
        } else {
            planMtRelService.remove(Wrappers.<PlanMtRel>lambdaQuery().eq(PlanMtRel::getMaintainId,planMt.getId()));
            this.removeById(planMt);
        }
        planMt.setId(null);
        this.saveInfo(fileList, planMt);

        return true;
    }

    private void disposeFile(Map<String, List<MultipartFile>> fileMap, String key, MultipartFile file) {
        List<MultipartFile> multipartFiles;
        if (fileMap.containsKey(key)) {
            multipartFiles = fileMap.get(key);
        } else {
            multipartFiles = new ArrayList<>();
        }
        multipartFiles.add(file);
        fileMap.put(key, multipartFiles);
    }
}
