/*
 * Author: Zev
 * 生成ServiceImpl
 */
package com.tofly.gpsboot.service.build.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.build.dto.BulidclearDto;
import com.tofly.pojo.build.vo.BulidclearVo;
import com.tofly.pojo.plan.dto.ReportAuditDto;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.mapper.build.BulidclearMapper;
import com.tofly.gpsboot.service.build.BuildService;
import com.tofly.gpsboot.service.build.BuildtypeService;
import com.tofly.gpsboot.service.build.BulidclearService;
import com.tofly.gpsboot.service.comm.IDisposeDateService;
import com.tofly.gpsboot.service.comm.IFileInfoService;
import com.tofly.gpsboot.service.report.IReportConstructionSiteEliminationServer;
import com.tofly.pojo.User;
import com.tofly.pojo.build.Build;
import com.tofly.pojo.build.Bulidclear;
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;


/**
 * 工地监护结束记录表
 *
 * @author admin
 * @date Thu Mar 18 00:00:00 CST 2021
 */
@Service("bulidclearService")
public class BulidclearServiceImpl extends ServiceImpl<BulidclearMapper, Bulidclear> implements BulidclearService {
    @Autowired
    private UserClent userClent;
    @Autowired
    private IFileInfoService iFileInfoService;
    @Value("${xrty.ftp.buildClear}")
    private String buildClearFilePath;
    @Autowired
    private IReportConstructionSiteEliminationServer iReportConstructionSiteEliminationServer;
    @Autowired
    private DepartmentClient departmentClient;
    @Autowired
    private BuildService buildService;
    @Autowired
    private BuildtypeService buildtypeService;
    @Autowired
    private IDisposeDateService iDisposeDateService;
    @Override
    public List<BulidclearVo> viewConversion(List<Bulidclear> infoList) {
        List<BulidclearVo> infoVoList = new ArrayList<>();
        infoList.forEach(info -> {
            BulidclearVo baseInfo = JSONObject.parseObject(JSON.toJSONString(info), BulidclearVo.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())));
            }
            // 增加工地类型/地址/施工单位名称/施工负责人/联系电话
            Build byId = buildService.getById(info.getBuildId());
            baseInfo.setAddress(byId.getAddress());
            Long typeId = byId.getTypeId();
            baseInfo.setTypeId(typeId);
            if (null != typeId && 0 != typeId) {
                baseInfo.setTypeName(buildtypeService.getById(typeId).getName());
            }
            baseInfo.setSgdw(byId.getSgdw());
            baseInfo.setGdfzr(byId.getGdfzr());
            baseInfo.setPhone(byId.getPhone());
            infoVoList.add(baseInfo);
        });
        return infoVoList;

    }


    @Override
    public Page<BulidclearVo> getBuildClearPage(Page page, BulidclearDto parDto) {
        Bulidclear bulidclear = JSONObject.parseObject(JSON.toJSONString(parDto), Bulidclear.class);

        QueryWrapper<Bulidclear> wrapper = new QueryWrapper();

        // 当前部门下用户才有权限
        Long departmentId = SecurityUtils.getUser().getDepartmentId();
        List<Long> userIdList = departmentClient.getDeptUserList(String.valueOf(departmentId)).getResult().stream().map(User::getId).collect(Collectors.toList());
        if(!StringUtils.isEmpty(parDto.getAuditResult())){
            List<String> stringList = Arrays.asList(parDto.getAuditResult().split(Constant.CSV));
            wrapper.in("AUDIT_RESULT",stringList);
            parDto.setAuditResult(null);
        }
        wrapper.in("SUBMIT_USER",userIdList);
        wrapper.setEntity(bulidclear);
        wrapper.orderByDesc("AUDIT_TIME");
        Page infoPageList = this.page(page, wrapper);
        infoPageList.setRecords(this.viewConversion(infoPageList.getRecords()));
        return infoPageList;
    }

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

        }
        // 根据文件id反射填充对象
        Bulidclear build = JSONObject.parseObject(JSON.toJSONString(parDto), Bulidclear.class);
        build.setClearFileids(fileIdList.toString());
        // 对象入库
        this.save(build);
        // 自动上报
        ReportAuditDto dto = new ReportAuditDto();
        dto.setId(build.getId());
        dto.setBuildClearNotes(build.getNotes());
        dto.setAuditId(build.getAuditUser());
        iReportConstructionSiteEliminationServer.report(dto);
    }

    @Override
    public void updateBulidClearInfo(List<MultipartFile> fileList, BulidclearDto parDto) throws BusinessException {
        if(!iDisposeDateService.isDisposePermissions(parDto.getSubmitUser())){
            throw new BusinessException(Constant.IS_DISPOSE_PERMISSIONS_NULL_CODE, Constant.IS_DISPOSE_PERMISSIONS_NULL);

        }
        Bulidclear updateRecord = JSONObject.parseObject(JSON.toJSONString(parDto), Bulidclear.class);
        List<Long> fileIdLongList = new ArrayList<>();
        if (null != fileList && fileList.size() > 0) {
            StringBuilder fileIdList = iFileInfoService.saveFileList(fileList, buildClearFilePath, FileTableEnum.TF_YWPN_BULIDCLEAR_W.getTableName());
            fileIdLongList = Arrays.stream(fileIdList.toString().split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                    .collect(Collectors.toList());
        }
        Bulidclear 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
    public void deleteBulidClearInfo(List<Long> idList) throws BusinessException {
        List<Long> removeFileIdList = new ArrayList<>();
        idList.forEach(info ->{
            Bulidclear record = this.getById(info);
            if(!iDisposeDateService.isDisposePermissions(record.getSubmitUser())){
                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);
    }
}
