/*
 * Author: Zev
 * 生成ServiceImpl
 */
package com.tofly.gpsboot.service.process.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.tofly.api.UserClent;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.common.system.*;
import com.tofly.pojo.User;
import com.tofly.pojo.plan.dto.PiperecordDto;
import com.tofly.pojo.plan.vo.PiperecordVo;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.mapper.plan.PiperecordMapper;
import com.tofly.gpsboot.service.comm.IFileInfoService;
import com.tofly.pojo.plan.Piperecord;
import com.tofly.gpsboot.service.process.PiperecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
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.stream.Collectors;


/**
 * 管线巡查记录上报表：TF_YWPN_PIPERECORD_W
 *
 * @author admin
 * @date Thu Mar 18 00:00:00 CST 2021
 */
@Service("piperecordService")
public class PiperecordServiceImpl extends ServiceImpl<PiperecordMapper, Piperecord> implements PiperecordService {
    @Autowired
    private IFileInfoService iFileInfoService;
    @Value("${xrty.ftp.pipeRecord}")
    private String pipeRecordFilePath;
    @Autowired
    private UserClent userClent;
    @Override
    public List<PiperecordVo> viewConversion(List<Piperecord> infoList) {
        List<PiperecordVo> infoVoList = new ArrayList<>();
        infoList.forEach(info ->{
            PiperecordVo baseInfo = JSONObject.parseObject(JSON.toJSONString(info),PiperecordVo.class);
            // 转换 井室情况,路面情况,井位情况,定位网络,设施类别,开启度
            baseInfo.setJsqkNote(WellChamberSituationEnum.getCodeForValue(info.getJsqkNote()));
            baseInfo.setRoadNote(RoadSituationEnum.getCodeForValue(info.getRoadNote()));
            baseInfo.setJwNote(WellSituationEnum.getCodeForValue(info.getJwNote()));
            baseInfo.setNetwork(NewWorkTypeEnum.getCodeForValue(info.getNetwork()));
            baseInfo.setSbType(FacilityCategoryEnum.getCodeForValue(info.getSbType()));
            baseInfo.setKqd(OpeningEnum.getCodeForValue(info.getKqd()));
            if (!StringUtils.isEmpty(info.getFileIds())) {
                baseInfo.setFilePathList(iFileInfoService.getFilePathList(Arrays.stream(info.getFileIds().split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList())));
            }
            Long submitUser = info.getCreateUser();
            if (null != submitUser && 0 != submitUser) {
                User userAudit = userClent.getById(submitUser).getResult();
                if(null!=userAudit){
                    baseInfo.setCreateUserName(userAudit.getRealName());
                }

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

    @Override
    public void savaPipeRecordInfo(List<MultipartFile> fileList, PiperecordDto parDto) throws BusinessException {
        StringBuilder fileIdList = new StringBuilder("");
        // 判断当前是否有文件,则存入返回文件id
        if (null != fileList && fileList.size() > 0) {
            fileIdList = iFileInfoService.saveFileList(fileList, pipeRecordFilePath, FileTableEnum.TF_YWPN_PIPERECORD_W.getTableName());

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

    @Override
    public void updatePipeRecordInfo(List<MultipartFile> fileList, PiperecordDto parDto) throws BusinessException {
        Piperecord updateRecord = JSONObject.parseObject(JSON.toJSONString(parDto),Piperecord.class);
        List<Long> fileIdLongList = new ArrayList<>();
        if (null != fileList && fileList.size() > 0) {
            StringBuilder fileIdList = iFileInfoService.saveFileList(fileList, pipeRecordFilePath, FileTableEnum.TF_YWPN_PIPERECORD_W.getTableName());
            fileIdLongList = Arrays.stream(fileIdList.toString().split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                    .collect(Collectors.toList());
        }
        Piperecord record = this.getById(parDto.getId());
        String lostFileIds = record.getFileIds();
        String fileIds = parDto.getFileIds();
        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.setFileIds(stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString());
            this.updateById(updateRecord);
            return;
        }
        this.updateById(updateRecord);
    }

    @Override
    public void deletePipeRecordInfo(List<Long> idList) throws BusinessException {
        List<Long> removeFileIdList = new ArrayList<>();
        idList.forEach(info ->{
            Piperecord record = this.getById(info);
            String fileIds = record.getFileIds();
            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);
    }
}
