/*
 * Author: Zev
 * 生成ServiceImpl
 */
package com.tofly.gpsboot.service.trouble.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.api.DepartmentClient;
import com.tofly.api.UserClent;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.common.system.FileTableEnum;
import com.tofly.gpsboot.common.system.IsAuditEnum;
import com.tofly.gpsboot.common.system.IsReadEnum;
import com.tofly.gpsboot.common.system.IsSubmitEnum;
import com.tofly.pojo.plan.dto.ReportAuditDto;
import com.tofly.pojo.trouble.dto.ToubleclearDto;
import com.tofly.pojo.trouble.vo.ToubleclearVo;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.mapper.trouble.ToubleclearMapper;
import com.tofly.gpsboot.service.comm.IDisposeDateService;
import com.tofly.gpsboot.service.comm.IFileInfoService;
import com.tofly.gpsboot.service.report.IReportHiddenTroubleEliminationServer;
import com.tofly.gpsboot.service.trouble.ToubleclearService;
import com.tofly.gpsboot.service.trouble.TroubleService;
import com.tofly.pojo.User;
import com.tofly.pojo.trouble.Toubleclear;
import com.tofly.pojo.trouble.Trouble;
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.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 隐患消除记录表
 *
 * @author admin
 * @date Thu Mar 18 00:00:00 CST 2021
 */
@Service("toubleclearService")
public class ToubleclearServiceImpl extends ServiceImpl<ToubleclearMapper, Toubleclear> implements ToubleclearService {
    @Autowired
    private UserClent userClent;
    @Autowired
    private IFileInfoService iFileInfoService;
    @Value("${xrty.ftp.troubleClear}")
    private String troubleClearFilePath;
    @Autowired
    private IReportHiddenTroubleEliminationServer iReportHiddenTroubleEliminationServer;
    @Autowired
    private TroubleService troubleService;
    @Autowired
    private DepartmentClient departmentClient;
    @Autowired
    private IDisposeDateService iDisposeDateService;
    @Override
    public List<ToubleclearVo> viewConversion(List<Toubleclear> infoList) {
        List<ToubleclearVo> infoVoList = new ArrayList<>();
        infoList.forEach(info -> {
            ToubleclearVo baseInfo = JSONObject.parseObject(JSON.toJSONString(info), ToubleclearVo.class);
            // 转换 是否读取 上报状态 审核状态
            baseInfo.setIsread(IsReadEnum.getCodeForValue(info.getIsread() + ""));
            baseInfo.setIsSubmit(IsSubmitEnum.getCodeForValue(info.getIsSubmit()));
            baseInfo.setAuditResult(IsAuditEnum.getCodeForValue(info.getAuditResult()));
            // 添加审核人 上报人
            // 添加审核人名称/上报人名称
            Long auditUser = info.getAuditUser();
            Long submitUser = info.getSubmitUser();
            if (null != auditUser && 0 != auditUser) {
                User userAudit = userClent.getById(auditUser).getResult();
                if(null!=userAudit){
                    baseInfo.setAuditUserName(userAudit.getRealName());
                }

            }
            if (null != submitUser && 0 != submitUser) {
                User userSubmit = userClent.getById(submitUser).getResult();
                if(null!=userSubmit){
                    baseInfo.setSubmitUserName(userSubmit.getRealName());
                }

            }
            if(!StringUtils.isEmpty(info.getClearFileids())){
                baseInfo.setFilePathList(iFileInfoService.getFilePathList(Arrays.stream(info.getClearFileids().split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList())));
            }
            // 增加 隐患主计划中的管线名称/地址/状态
            Trouble byId = troubleService.getById(info.getToubleId());
            baseInfo.setAddress(byId.getAddress());
            baseInfo.setTuobleState(byId.getState());
            baseInfo.setPipeName(byId.getPipeName());

            infoVoList.add(baseInfo);
        });
        return infoVoList;
    }


    @Override
    public Page<Toubleclear> getToubleclearPage(Page page, ToubleclearDto parDto) {
        // 当前部门下用户才有权限
        // 获取前端传入部门id
        Long deptId = parDto.getDeptId();
        // 是否跨部门
        Set<Long> userIdList = departmentClient.getDeptUserList(null==deptId?SecurityUtils.getUser().getDepartmentId():deptId).getResult().stream().map(User::getId).collect(Collectors.toSet());
        parDto.setUserIdList(userIdList);
       return baseMapper.getToubleClearPage(page,parDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savaBuildInfo(List<MultipartFile> fileList, ToubleclearDto parDto) {
        StringBuilder fileIdList = new StringBuilder("");
        // 判断当前是否有文件,则存入返回文件id
        if(null!=fileList && fileList.size()>0){
            fileIdList = iFileInfoService.saveFileList(fileList, troubleClearFilePath, FileTableEnum.TF_YWPN_TOUBLECLEAR_W.getTableName());

        }
        // 根据文件id反射填充对象
        Toubleclear build = JSONObject.parseObject(JSON.toJSONString(parDto), Toubleclear.class);
        build.setClearFileids(fileIdList.toString());
        // 对象入库
        this.save(build);

        // 自动上报
        ReportAuditDto dto = new ReportAuditDto();
        dto.setId(build.getId());
        dto.setTroubleClearNotes(build.getNotes());
        dto.setAuditId(build.getAuditUser());
        iReportHiddenTroubleEliminationServer.report(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateToubleclearInfo(List<MultipartFile> fileList, ToubleclearDto parDto) throws BusinessException {
        if(!iDisposeDateService.isDisposePermissions(parDto.getCreateUser())){
            throw new BusinessException(Constant.IS_DISPOSE_PERMISSIONS_NULL_CODE, Constant.IS_DISPOSE_PERMISSIONS_NULL);

        }
        Toubleclear updateRecord = JSONObject.parseObject(JSON.toJSONString(parDto),Toubleclear.class);
        List<Long> fileIdLongList = new ArrayList<>();
        if (null != fileList && fileList.size() > 0) {
            StringBuilder fileIdList = iFileInfoService.saveFileList(fileList, troubleClearFilePath, FileTableEnum.TF_YWPN_TOUBLECLEAR_W.getTableName());
            fileIdLongList = Arrays.stream(fileIdList.toString().split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                    .collect(Collectors.toList());
        }
        Toubleclear record = this.getById(parDto.getId());
        String lostFileIds = record.getClearFileids();
        String fileIds = parDto.getClearFileids();
        List<Long> removeFileId = new ArrayList<>();
        List<Long> fileIdLongs = new ArrayList<>();
        if(!StringUtils.isEmpty(fileIds)){
            fileIdLongs = Arrays.stream(fileIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                    .collect(Collectors.toList());
        }
        // 判断当前文件是否有更新
        if(!StringUtils.isEmpty(lostFileIds)&&lostFileIds.equals(fileIds)){
            List<Long> lostFileIdLongs = Arrays.stream(lostFileIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList());

            List<Long> finalFileIdLongs = fileIdLongs;
            lostFileIdLongs.forEach(lost->{
                if(!finalFileIdLongs.contains(lost)){
                    removeFileId.add(lost);
                }
            });
            // 删除对应文件数据
            if(removeFileId.size()>0){
                // 删除远程文件
                iFileInfoService.removeFileList(removeFileId);
            }
            if(lostFileIdLongs.size()>0){
                // 删除远程文件
                iFileInfoService.removeFileList(lostFileIdLongs);
            }

        }
        // 更新数据信息
        fileIdLongList.addAll(fileIdLongs);
        if(fileIdLongList.size()>0){
            StringBuilder stringBuilder = new StringBuilder("");
            fileIdLongList.forEach(info -> {
                stringBuilder.append(info).append(Constant.CSV);
            });
            updateRecord.setClearFileids(stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString());
            this.updateById(updateRecord);
            return;
        }
        this.updateById(updateRecord);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteToubleclearInfo(List<Long> idList) throws BusinessException {
        List<Long> removeFileIdList = new ArrayList<>();
        idList.forEach(info ->{
            Toubleclear record = this.getById(info);
            if(!iDisposeDateService.isDisposePermissions(record.getCreateUser())){
                throw new BusinessException(Constant.IS_DISPOSE_PERMISSIONS_NULL_CODE, Constant.IS_DISPOSE_PERMISSIONS_NULL);

            }
            String fileIds = record.getClearFileids();
            if(!StringUtils.isEmpty(fileIds)){
                List<Long> fileIdLongs = Arrays.stream(fileIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList());
                removeFileIdList.addAll(fileIdLongs);
            }
        });
        if(removeFileIdList.size()>0){
            // 删除远程文件
            iFileInfoService.removeFileList(removeFileIdList);
        }
        this.removeByIds(idList);
    }

    @Override
    public void clearTroubleUserTaskPlan(Long troubleId) {
        baseMapper.clearTroubleUserTaskPlan(troubleId);
    }
}
