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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.*;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.mapper.maintain.PipeMfRecordMapper;
import com.tofly.gpsboot.service.comm.IFileInfoService;
import com.tofly.gpsboot.service.maintain.*;
import com.tofly.gpsboot.service.report.IReportRepairRecordServer;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.comm.dto.AuditDto;
import com.tofly.pojo.maintain.*;
import com.tofly.pojo.maintain.dto.RepairorderDto;
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.time.LocalDateTime;
import java.util.*;

/**
 * 管网设施维护保养记录
 *
 * @author admin
 * @date Tue Oct 26 00:00:00 CST 2021
 */
@Service("pipeMfRecordService")
public class PipeMfRecordServiceImpl extends ServiceImpl<PipeMfRecordMapper, PipeMfRecord> implements PipeMfRecordService {

    @Autowired
    private PipeMfContentService pipeMfContentService;

    @Autowired
    private PipeMfEvaluateService pipeMfEvaluateService;

    @Autowired
    private IFileInfoService iFileInfoService;

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

    @Autowired
    private RepairuserService repairuserService;
    @Autowired
    private RepairorderService repairorderService;

    @Autowired
    private IReportRepairRecordServer iReportRepairRecordServer;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveInfoPipeMfRecord(List<MultipartFile> fileList, PipeMfRecord pipeMfRecord) {
        // 判断当前过程上报是否达到维修数量,若大于则不允许新增
        Long userPlanId = pipeMfRecord.getRepairUserId();
        if(null == userPlanId){
            throw new BusinessException(Constant.REPAIR_MAINTAIN_ORDER_NULL_ERROR_CODE, Constant.REPAIR_MAINTAIN_ORDER_NULL_ERROR);

        }
        Repairuser repairuser = repairuserService.getById(userPlanId);
        Long planNum = repairuser.getPlanNum();
        // 当前个人任务下 未失效的数据
        long count = this.list(new QueryWrapper<PipeMfRecord>().lambda().in(PipeMfRecord::getRepairUserId, userPlanId).eq(PipeMfRecord::getFlag, IsValidEnum.IS_VALID_YES.getCode())).size();
        if (planNum <= count) {
            throw new BusinessException(Constant.REPAIR_MAINTAIN_ADD_ERROR_CODE, Constant.REPAIR_MAINTAIN_ADD_ERROR);
        }

        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, pipeMfRecordFilePath, FileTableEnum.TF_YMPN_PIPE_MF_RECORD_W.getTableName());
                stringListMap.put(k, builder.toString());
            });
            pipeMfRecord.setFileIdsOne(stringListMap.get(key1));
            pipeMfRecord.setFileIdsTow(stringListMap.get(key2));
            pipeMfRecord.setFileIdsThree(stringListMap.get(key3));
        }
        boolean save = this.save(pipeMfRecord);

        if (save) {
            Long id = pipeMfRecord.getId();
            List<PipeMfContent> pipeMfContentList = pipeMfRecord.getPipeMfContentList();
            if (null != pipeMfContentList && pipeMfContentList.size() > 0) {
                pipeMfContentList.forEach(info -> {
                    info.setMfId(id);
                    pipeMfContentService.save(info);
                });
            }
            List<PipeMfEvaluate> pipeMfEvaluateList = pipeMfRecord.getPipeMfEvaluateList();
            if (null != pipeMfEvaluateList && pipeMfEvaluateList.size() > 0) {
                pipeMfEvaluateList.forEach(info -> {
                    info.setMfId(id);
                    pipeMfEvaluateService.save(info);
                });
            }

            // 个人任务数量完成+1
            BigDecimal overNum = repairuser.getOverNum() == null ? BigDecimal.ZERO : BigDecimal.valueOf(repairuser.getOverNum());
            // 完成+1
            repairuser.setOverNum(overNum.add(BigDecimal.ONE).longValue());
            long end = count + 1;
            Repairorder repairOrder = repairorderService.getById(repairuser.getRepairId());
            if (planNum <= end) {
                // 修改用户的处理完成上报时间为现在/状态为未审核
                repairuser.setOverTime(DateTimeUtil.convertLDTToDate(LocalDateTime.now()));
                repairuser.setState(OrderStateEnum.ORDER_STATE_NOT_AUDIT.getCode());
                // 计算实际处理用时
                repairuser.setRealTime(Double.valueOf(DateTimeUtil.differHours(DateTimeUtil.fromLong2LocalDateTime(repairOrder.getStartTime().getTime()), LocalDateTime.now())));
            }
            repairuserService.updateById(repairuser);
            // 主体完成率

            repairOrder.setOverNum(repairuser.getOverNum());
            repairOrder.setPercent(BigDecimal.valueOf(repairOrder.getOverNum()).divide(BigDecimal.valueOf(repairOrder.getNum()), 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).floatValue());
            repairOrder.setState(OrderStateEnum.ORDER_STATE_BEING_PERFORMED.getCode());
            repairorderService.updateById(repairOrder);
            Long num = repairOrder.getNum();
            // 判断当前养护记录是否为最后的维修数量提交
            if (num <= end) {
                // 自动上报
                ReportAuditDto reportAuditDto = new ReportAuditDto();
                reportAuditDto.setId(repairOrder.getId());
                reportAuditDto.setReportId(SecurityUtils.getUserId());


                // 若月份不为空则获取派发人id,否则获取创建工单用户id
                Long dispatchingId = null;
                String orderSource = repairOrder.getOrderSource();
                // 判断当前工单是否是热线工单
                if (OrderSourceEnum.ORDER_SOURCE_HOTLINE.getCode().equals(orderSource)) {
                    dispatchingId = repairOrder.getCreateUser();
                } else {
                    if (!StringUtils.isEmpty(repairOrder.getMonth())) {
                        dispatchingId = repairorderService.getDispatchingId(repairOrder.getYearId(), repairOrder.getMonth());
                    } else {
                        dispatchingId = repairOrder.getCreateUser();
                    }
                }


                reportAuditDto.setRepairorderDto(JSONObject.parseObject(JSON.toJSONString(repairOrder), RepairorderDto.class));
                reportAuditDto.setAuditId(dispatchingId);

                // 塞审核链
                AuditDto auditDto = new AuditDto();
                auditDto.setAuditPlanId(repairOrder.getId());
                auditDto.setAuditType(AuditTypeEnum.AUDIT_TYPE_REPAIR_RECORD.getCode());
                auditDto.setAuditLevel(0);
                auditDto.setAuditUser(dispatchingId);
                auditDto.setAuditState(AuditSateEnum.AUDIT_UNCOMMITTED.getCode());
                List<AuditDto> auditDtoList = new ArrayList<>();
                auditDtoList.add(auditDto);
                reportAuditDto.setAuditDtoList(auditDtoList);
                iReportRepairRecordServer.report(reportAuditDto);

            }

        } else {
            return false;
        }
        return true;

    }

    @Override
    public Page<PipeMfRecord> getPage(Page page, PipeMfRecord pipeMfRecord) {

        QueryWrapper<PipeMfRecord> wrapper = new QueryWrapper();
        if (!StringUtils.isEmpty(pipeMfRecord.getStartDate())) {

            wrapper.ge("MAINTAIN_TIME", pipeMfRecord.getStartDate());

        }
        if (!StringUtils.isEmpty(pipeMfRecord.getEndDate())) {

            wrapper.le("MAINTAIN_TIME", pipeMfRecord.getEndDate());

        }
        pipeMfRecord.setMaintainTime(null);
        wrapper.setEntity(pipeMfRecord);

       return this.baseMapper.selectMapsPage(page,wrapper);
    }

    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);
    }

}
