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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.api.GdglinfoClient;
import com.tofly.api.audit.AuditClient;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.pojo.GdglinfoExtendDto;
import com.tofly.pojo.comm.Audit;
import com.tofly.pojo.plan.Checkhistory;
import com.tofly.xrtygis.commons.Constant;
import com.tofly.xrtygis.commons.system.FileTableEnum;
import com.tofly.xrtygis.custom.util.service.FileInfoService;
import com.tofly.xrtygis.em.QuarterEnum;
import com.tofly.xrtygis.entity.TfPublicLeakageInfo;
import com.tofly.xrtygis.entity.dto.PublicLeakageOrderDto;
import com.tofly.xrtygis.entity.dto.TfPublicLeakageInfoDto;
import com.tofly.xrtygis.entity.vo.TfPublicLeakageInfoCensusVo;
import com.tofly.xrtygis.exception.BusinessException;
import com.tofly.xrtygis.mapper.TfPublicLeakageInfoMapper;
import com.tofly.xrtygis.service.TfPublicLeakageInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
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 24 00:00:00 CST 2022
 */
@Service("tfPublicLeakageInfoService")
public class TfPublicLeakageInfoServiceImpl extends ServiceImpl<TfPublicLeakageInfoMapper, TfPublicLeakageInfo> implements TfPublicLeakageInfoService {

    @Autowired
    private FileInfoService fileInfoService;

    @Autowired
    private GdglinfoClient gdglinfoClient;

    @Autowired
    private AuditClient auditClient;

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

    @Override
    public List<TfPublicLeakageInfoCensusVo> getPublicCensus(TfPublicLeakageInfoDto tfPublicLeakageInfoDto) {

        List<TfPublicLeakageInfoCensusVo> censusVoList = new ArrayList<>();

        String startYear = tfPublicLeakageInfoDto.getStartDate();
        String endYear = tfPublicLeakageInfoDto.getEndDate();
        if(StringUtils.isNotBlank(startYear)&&StringUtils.isNotBlank(endYear)){
            //遍历起止时间的每一年
            for(int i = Integer.parseInt(startYear);i < Integer.parseInt(endYear) + 1;i++){
                censusVoList.add(getPublicLeakageCensusVo(null,String.valueOf(i),tfPublicLeakageInfoDto));
            }
        }else if(StringUtils.isNotBlank(tfPublicLeakageInfoDto.getCurrentQuarterDate())
                && StringUtils.isNotBlank(tfPublicLeakageInfoDto.getCurrentYearDate())){
            //遍历每一季度
            String[] quarterList = tfPublicLeakageInfoDto.getCurrentQuarterDate().split(",");
            for(String quarter:quarterList){
                censusVoList.add(getPublicLeakageCensusVo(quarter,null,tfPublicLeakageInfoDto));
            }
        }

        return censusVoList;
    }

    public TfPublicLeakageInfoCensusVo getPublicLeakageCensusVo(String quarter, String currentYearDate, TfPublicLeakageInfoDto tfPublicLeakageInfoDto) {
        TfPublicLeakageInfoCensusVo censusVo = new TfPublicLeakageInfoCensusVo();

        TfPublicLeakageInfoDto publicLeakageInfoQuery = new TfPublicLeakageInfoDto();
        publicLeakageInfoQuery.setDmaId(tfPublicLeakageInfoDto.getDmaId());

        int publicPeopleCount;
        int leakagePassCount;
        Integer estimateWaterCount;
        Integer rewardWaterCount;
        int leakageInfoCount;
        if(StringUtils.isNotBlank(quarter)){
            publicLeakageInfoQuery.setCurrentYearDate(tfPublicLeakageInfoDto.getCurrentYearDate());
            publicLeakageInfoQuery.setCurrentQuarterDate(quarter);
            publicPeopleCount = baseMapper.getPublicPeopleByQuarter(publicLeakageInfoQuery);
            leakagePassCount = baseMapper.getLeakagePassByQuarter(publicLeakageInfoQuery);
            estimateWaterCount = baseMapper.getEstimateWaterByQuarter(publicLeakageInfoQuery);
            rewardWaterCount = baseMapper.getRewardWaterByQuarter(publicLeakageInfoQuery);
            leakageInfoCount = baseMapper.getLeakageInfoByQuarter(publicLeakageInfoQuery);

            censusVo.setDate(tfPublicLeakageInfoDto.getCurrentYearDate()
                    + "年第" + QuarterEnum.getCodeForValue(quarter) + "季度");
        }else if(StringUtils.isNotBlank(currentYearDate)){
            publicLeakageInfoQuery.setCurrentYearDate(currentYearDate);
            publicPeopleCount = baseMapper.getPublicPeopleByYear(publicLeakageInfoQuery);
            leakagePassCount = baseMapper.getLeakagePassByYear(publicLeakageInfoQuery);
            estimateWaterCount = baseMapper.getEstimateWaterByYear(publicLeakageInfoQuery);
            rewardWaterCount = baseMapper.getRewardWaterByYear(publicLeakageInfoQuery);
            leakageInfoCount = baseMapper.getLeakageInfoByYear(publicLeakageInfoQuery);

            censusVo.setDate(currentYearDate + "年");
        }else {
            return censusVo;
        }


        int informationAccuracy = 0;
        if(leakageInfoCount != 0 && leakagePassCount != 0){
            informationAccuracy = leakagePassCount / leakageInfoCount * 100;
        }

        censusVo.setPublicPeopleCount(String.valueOf(publicPeopleCount));
        if(estimateWaterCount == null){
            estimateWaterCount = 0;
        }
        censusVo.setEstimateLeakageWaterCount(String.valueOf(estimateWaterCount));
        if(rewardWaterCount == null){
            rewardWaterCount = 0;
        }
        censusVo.setRewardWaterCount(String.valueOf(rewardWaterCount));
        censusVo.setInformationAccuracy(informationAccuracy + "%");
        censusVo.setLeakagePassCount(String.valueOf(leakagePassCount));

        return censusVo;
    }

    @Override
    public Page<TfPublicLeakageInfo> getTfPublicLeakageInfoPage(Page page, TfPublicLeakageInfoDto tfPublicLeakageInfoDto) {
        return baseMapper.getTfPublicLeakageInfoPage(page, tfPublicLeakageInfoDto);
    }

    @Override
    public boolean savePublicLeakageAudit(GdglinfoExtendDto gdglinfoExtendDto) {
        com.tofly.pojo.Audit audit;
        if(gdglinfoExtendDto.getAudit() != null){
            audit = gdglinfoExtendDto.getAudit();
            if(audit.getAuditPlanId() == null){
                throw new BusinessException(Constant.PLAN_ID_NULL_ERROR_CODE,Constant.PLAN_ID_NULL_ERROR);
            }
        }else {
            throw new BusinessException(Constant.AUDIT_IS_NULL_ERROR_CODE,Constant.AUDIT_IS_NULL_ERROR);
        }

        Audit auditQuery = new Audit();
        auditQuery.setAuditPlanId(audit.getAuditPlanId());
        auditQuery.setAuditType("021");
        ResultRespone<List<Audit>> auditListRes = auditClient.getAuditInfo(auditQuery);
        if(auditListRes != null && auditListRes.getCode()==1 && auditListRes.getResult().size()>0){
            throw new BusinessException(Constant.AUDIT_IS_EXIST_ERROR_CODE,Constant.AUDIT_IS_EXIST_ERROR);
        }

        audit.setAuditType("021");

        gdglinfoExtendDto.setAudit(audit);

        //审核通过则生成工单
        if(audit.getAuditState().equals("1")){
            ResultRespone res = gdglinfoClient.saveGdglInfo(gdglinfoExtendDto);
            //保存工单id
            if(res != null && res.getCode()==1 && StringUtils.isNotBlank(String.valueOf(res.getResult()))){
                Long orderId = Long.parseLong(String.valueOf(res.getResult()));
                TfPublicLeakageInfo tfPublicLeakageInfo = new TfPublicLeakageInfo();
                tfPublicLeakageInfo.setId(audit.getAuditPlanId());
                tfPublicLeakageInfo.setOrderId(orderId);
                if(audit.getAuditUser() != null){
                    tfPublicLeakageInfo.setVerifyUser(audit.getAuditUser());
                }
                if(audit.getAuditTime() != null){
                    tfPublicLeakageInfo.setVerifyTime(String.valueOf(audit.getAuditTime()));
                }
                this.updateById(tfPublicLeakageInfo);
            }
        }

        //保存审核信息
        List<com.tofly.pojo.Audit> auditList = new ArrayList<>();
        auditList.add(audit);
        auditClient.save(JSON.toJSONString(auditList));

        //添加审核信息入审核历史表
        Checkhistory checkhistory = new Checkhistory();
        checkhistory.setType(audit.getAuditType());
        checkhistory.setCheckId(audit.getAuditPlanId());
        checkhistory.setAuditResult(audit.getAuditState());
        checkhistory.setAuditNotes(audit.getAuditNote());
        checkhistory.setAuditUser(audit.getAuditUser());
        checkhistory.setAuditTime(audit.getAuditTime());

        // 保存审核记录
        auditClient.saveAuditHisInfo(checkhistory);

        return true;
    }

    @Override
    public boolean saveRewardWaterOder(PublicLeakageOrderDto dto, List<MultipartFile> fileList) {
        String isRewardWater = dto.getIsRewardWater();
        Long publicLeakageId = dto.getPublicLeakageId();
        if(isRewardWater.equals("0")){
            return true;
        }
        if(!isRewardWater.equals("1")){
            throw new ToflyDeniedException("是否是奖励水量字段传递有误");
        }
        TfPublicLeakageInfo publicLeakageInfoQuery = this.getById(publicLeakageId);
        if(!publicLeakageInfoQuery.getVerifyStatus().equals("3")){
            throw new ToflyDeniedException("该漏点审核状态不是真实且有效");
        }else if(publicLeakageInfoQuery.getIsRewardWater().equals("1")){
            throw new ToflyDeniedException("该漏点信息已经进行了水量奖励");
        }
        GdglinfoExtendDto gdglinfoExtendDto = new GdglinfoExtendDto();
        BeanUtils.copyProperties(dto,gdglinfoExtendDto);
        gdglinfoExtendDto.setIsRewardWater("1");
        ResultRespone res = gdglinfoClient.saveAnnexFeign(fileList,gdglinfoExtendDto);
        //保存工单id
        if(res != null && res.getCode()==1 && StringUtils.isNotBlank(String.valueOf(res.getResult()))){
            Long orderId = Long.parseLong(String.valueOf(res.getResult()));
            publicLeakageInfoQuery.setRewardWaterId(orderId);
            publicLeakageInfoQuery.setIsRewardWater("1");
            this.updateById(publicLeakageInfoQuery);
        }
        return true;
    }

//    @Override
//    public boolean updateNewPublicLeakage(TfPublicLeakageInfo tfPublicLeakageInfo) {
//        if(tfPublicLeakageInfo == null){
//            throw new BusinessException(Constant.AUDIT_ENTITY_ERROR_CODE,Constant.AUDIT_ENTITY_ERROR);
//        }
//
//        if(tfPublicLeakageInfo.getId() == null){
//            throw new BusinessException(Constant.ID_ERROR_CODE,Constant.ID_ERROR);
//        }
//
//        auditClient.delete("021",tfPublicLeakageInfo.getId());
//        this.updateById(tfPublicLeakageInfo);
//
//        return true;
//    }

    @Override
    public void savaTfPublicLeakageInfo(List<MultipartFile> fileList, TfPublicLeakageInfo tfPublicLeakageInfo)  throws BusinessException {
        StringBuilder fileIdList = new StringBuilder();
        // 判断当前是否有文件,则存入返回文件id
        if (null != fileList && fileList.size() > 0) {
            fileIdList = fileInfoService.saveFileList(fileList, publicLeakageFilePath, FileTableEnum.TF_PUBLIC_LEAKAGE_INFO.getTableName());
        }
        // 根据文件id反射填充对象
        TfPublicLeakageInfo info = JSONObject.parseObject(JSON.toJSONString(tfPublicLeakageInfo), TfPublicLeakageInfo.class);
        info.setAnnex(fileIdList.toString());
        // 对象入库
        this.save(info);
    }

//    @Override
//    public void updateTfPublicLeakageInfo(List<MultipartFile> fileList, TfPublicLeakageInfo tfPublicLeakageInfo) throws BusinessException {
//        TfPublicLeakageInfo updatePublicLeakage = JSONObject.parseObject(JSON.toJSONString(tfPublicLeakageInfo),TfPublicLeakageInfo.class);
//        List<Long> fileIdLongList = new ArrayList<>();
//        if (null != fileList && fileList.size() > 0) {
//            StringBuilder fileIdList = iFileInfoService.saveFileList(fileList, publicLeakageFilePath, FileTableEnum.TF_PUBLIC_LEAKAGE_INFO.getTableName());
//            fileIdLongList = Arrays.stream(fileIdList.toString().split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
//                    .collect(Collectors.toList());
//        }
//        TfPublicLeakageInfo publicLeakageInfo = this.getById(tfPublicLeakageInfo.getId());
//        String lostFileIds = publicLeakageInfo.getAnnex();
//        String fileIds = tfPublicLeakageInfo.getAnnex();
//        List<Long> removeFileId = new ArrayList<>();
//
//        List<Long> fileIdLongs = new ArrayList<>();
//        if(!org.springframework.util.StringUtils.isEmpty(fileIds)){
//            fileIdLongs = Arrays.stream(fileIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
//                    .collect(Collectors.toList());
//        }
//        // 判断当前文件是否有更新
//        if(!org.springframework.util.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);
//            });
//            updatePublicLeakage.setAnnex(stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString());
//            this.updateById(updatePublicLeakage);
//            return;
//        }
//        this.updateById(updatePublicLeakage);
//
//
//    }

    @Override
    public void deleteTfPublicLeakageInfo(List<Long> idList) throws BusinessException {
        List<Long> removeFileIdList = new ArrayList<>();
        idList.forEach(info ->{
            TfPublicLeakageInfo tfPublicLeakageInfo = this.getById(info);
            String fileIds = tfPublicLeakageInfo.getAnnex();
            if(!org.springframework.util.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){
            // 删除远程文件
            fileInfoService.removeFileList(removeFileIdList);
        }
        this.removeByIds(idList);
    }

}
