package cn.cslg.report.service.business;

import cn.cslg.report.common.core.base.Constants;
import cn.cslg.report.common.model.vo.PersonnelVO;
import cn.cslg.report.common.model.vo.ReportVO;
import cn.cslg.report.common.model.vo.SystemDictVO;
import cn.cslg.report.common.utils.*;
import cn.cslg.report.common.utils.SecurityUtils.LoginUtils;
import cn.cslg.report.entity.Report;
import cn.cslg.report.entity.ReportField;
import cn.cslg.report.entity.ReportFiles;
import cn.cslg.report.entity.asso.AssoReportFile;
import cn.cslg.report.mapper.ReportMapper;
import cn.cslg.report.service.OutInterfaceService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class ReportService extends ServiceImpl<ReportMapper, Report> {
    private final OutInterfaceService outInterfaceService;
    private final ReportMapper reportMapper;
    private final ReportFieldService reportFieldService;
    private final CacheUtils cacheUtils;
    private final LoginUtils loginUtils;
    private final AssoReportFileService assoReportFileService;
    private final ReportFileService reportFileService;

    /**
     * @param report 报告类
     * @author 沈永艺
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer addReport(Report report ,List<MultipartFile> file) {
        try {
            report.getScenarioList();
            report.setScenarioId(StringUtils.join(report.getScenarioList(), ","));
            String res1 = outInterfaceService.getClientNameFromPAS(report.getClientId());
            JSONObject jsonObject = JSONObject.parseObject(res1);
            String clientName = jsonObject.getString("data");
            String res2 = outInterfaceService.getPersonNameAndDepart(report.getPersonId(), report.getDepartmentId());
            if (report.getAssociateReportId() != null) {
                LambdaQueryWrapper<Report> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Report::getId, report.getAssociateReportId());
                Report assioReport = this.list(wrapper).get(0);
                report.setAssociateReportName(assioReport.getName());
            }
            JSONObject jsonObject2 = JSONObject.parseObject(res2);
            Map<String, Object> map = (Map<String, Object>) jsonObject2.get("data");
            report.setClientName(clientName);
            report.setDepartmentName(map.get("departName").toString());
            report.setPersonName(map.get("personName").toString());
            PersonnelVO personnelVO =cacheUtils.getLoginUser(loginUtils.getId());
            report.setCreatePersonId(personnelVO.getId());
            report.setCreatePersonName(personnelVO.getName());
            boolean addFlag = this.save(report);

            if (file!=null&&file.size() != 0) {
                //将文档上传并返回文件入库的Id
                List<Integer> fileIds = reportFileService.uploadFiles(file);
                assoReportFileService.addAsso(report.getId(), fileIds);

            }
            if (addFlag) {
              reportFieldService.addDefaultField(report.getId(),report.getType());
                return report.getId();
            } else {
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("新增报告异常，异常信息:" + LogExceptionUtil.getMessage(e));
            log.info("新增报告功能异常，开始回滚! 时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.info("回滚完毕! 时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            return -1;
        } finally {
            // TODO: 2022/11/4 这个Finally可以引入表日志记录 或者做点别的什么 也可以删掉
            System.out.println("报告新增结束");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    //查询报告
    public String queryReport(ReportVO reportVO) throws IOException {
        LambdaQueryWrapper<Report> queryWrapper = new LambdaQueryWrapper<>();
        if (reportVO.getName() != null) {
            queryWrapper.like(Report::getName, reportVO.getName());
        }
        if (reportVO.getReportId() != null) {
            queryWrapper.eq(Report::getId, reportVO.getReportId());
        }
        queryWrapper.orderByDesc(Report::getId);
        if (reportVO.getSize() != null && reportVO.getSize() != null) {
            List<Report> reports = this.page(new Page<>(reportVO.getCurrent(), reportVO.getSize()), queryWrapper).getRecords();
            reports = this.reportData(reports);
            long count = this.count(queryWrapper);
            return Response.success(reports, DataUtils.setPageColumn(reportVO.getSize(), reportVO.getCurrent(), Math.toIntExact(count)));
        } else {
            List<Report> reports = this.list(queryWrapper);
            reports = this.reportData(reports);
            return Response.success(reports);
        }
    }

    public List<Report> reportData(List<Report> reports) throws IOException {
        List<Integer> reportIds =reports.stream().map(Report::getId).collect(Collectors.toList());
        List<AssoReportFile> assoReportFiles=assoReportFileService.queryFileByReportId(reportIds);
        List<ReportFiles> reportFilesList =new ArrayList<>();
        if(assoReportFiles.size()!=0){
        List<Integer> fileIds =assoReportFiles.stream().map(AssoReportFile::getFileId).collect(Collectors.toList());
         reportFilesList =reportFileService.getFiles(fileIds);}

        String res = outInterfaceService.getDictsFromPAS();
        JSONObject jsonObject = JSONObject.parseObject(res);
        List<SystemDictVO> list = JSONArray.parseArray(jsonObject.getString("data"),SystemDictVO.class);
        List<ReportFiles> temList=reportFilesList;
        reports.forEach(
                item -> {
                    if (StringUtils.isNotEmpty(item.getScenarioId())) {
                        item.setScenarioList(StringUtils.changeStringToString(item.getScenarioId(), ","));
                        item.setScenarioNames(list.stream().filter(systemDict -> systemDict.getType().equals(Constants.ENTERPRISE_APPLICATION_SCENARIO) && item.getScenarioList().contains(systemDict.getValue())).map(SystemDictVO::getLabel).collect(Collectors.toList()));
                        item.setScenarioId(null);
                    }
                  List<AssoReportFile> partReportFiles =assoReportFiles.stream().filter(tem->tem.getReportId().equals(item.getId())).collect(Collectors.toList());
                    if(partReportFiles.size()==0){ item.setReportFiles(null);}
                    else {
                        List<Integer> partFileIds = partReportFiles.stream().map(AssoReportFile::getFileId).collect(Collectors.toList());
                        List<ReportFiles> partFiles = temList.stream().filter(tem -> partFileIds.contains(tem.getId())).collect(Collectors.toList());
                        item.setReportFiles(partFiles);
                    }
                });

        return reports;
    }
    public String reportDele(int id) throws IOException{
       int  dele  = reportMapper.dele(id);
        if(dele>0){
            return Response.success();
        }
        return   Response.error("没有数据");

    }


}
