package com.boman.report.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.boman.common.core.utils.CollectUtils;
import com.boman.common.core.utils.StringUtils;
import com.boman.domain.SysFile;
import com.boman.domain.dto.AjaxResult;
import com.boman.domain.dto.StatisticReportDto;
import com.boman.domain.entity.StatisticReport;
import com.boman.domain.entity.StatisticReportPersonnel;
import com.boman.domain.entity.vo.StatisticReportVo;
import com.boman.report.mapper.StatisticReportMapper;
import com.boman.report.mapper.StatisticReportPersonnelMapper;
import com.boman.report.service.StatisticReportService;
import com.boman.common.core.utils.SecurityUtils;
import com.boman.report.service.StatisticReportPersonnelService;
import org.apache.commons.lang3.SerializationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shiqian
 * @date 2021年08月24日 11:10
 **/
@Service
public class StatisticReportServiceImpl implements StatisticReportService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImportServiceImpl.class);


    public static final String INSERT =  "insert";

    public static final String UPDATE =  "update";


    @Autowired
    private StatisticReportPersonnelService personnelService;

    @Autowired
    private StatisticReportMapper statisticReportMapper;

    @Autowired
    private StatisticReportPersonnelMapper statisticReportPersonnelMapper;
    /**
     * 获取表报详情
     * @param id
     * @return
     */
    @Override
    public AjaxResult getReportInfo(Long id) {
        StatisticReportVo reportInfo = statisticReportMapper.getReportInfo(id);
        //获取参与人员信息
        List<StatisticReportPersonnel> statisticReportPersonnels = statisticReportPersonnelMapper.selectByStatisticId(id);
        if (statisticReportPersonnels != null && statisticReportPersonnels.size() > 0){
            Map<String, List<String>> personnelMap = statisticReportPersonnels.stream().collect(Collectors.groupingBy(StatisticReportPersonnel::getDeptName, Collectors.mapping(StatisticReportPersonnel::getUserName, Collectors.toList())));
            Map<String, List<String>> filledOutMap = statisticReportPersonnels.stream().filter(e -> "1".equals(e.getStatus())).collect(Collectors.groupingBy(StatisticReportPersonnel::getDeptName, Collectors.mapping(StatisticReportPersonnel::getUserName, Collectors.toList())));
            Map<String, List<StatisticReportPersonnel>> filledInMap = statisticReportPersonnels.stream().filter(e -> "2".equals(e.getStatus())).collect(Collectors.groupingBy(StatisticReportPersonnel::getDeptName));
            //参与人员
            List<Map<String,Object>> personnelList = new ArrayList<>();
            //已填报
            List<Map<String,Object>> filledInList = new ArrayList<>();
            //未填报
            List<Map<String,Object>> filledOutList = new ArrayList<>();
            if (personnelMap != null && personnelMap.size() > 0){
                personnelMap.forEach((key, value) -> {
                    Map<String,Object> map = new HashMap<>();
                    map.put("deptName",key);
                    map.put("userNameList",value);
                    personnelList.add(map);
                });
            }
            if (filledOutMap != null && filledOutMap.size() > 0){
                filledOutMap.forEach((key, value) -> {
                    Map<String,Object> map= new HashMap<>();
                    map.put("deptName",key);
                    map.put("userNameList",value);
                    filledOutList.add(map);
                });
            }
            if (filledInMap != null && filledInMap.size() > 0){
                Set<String> strings = filledInMap.keySet();
                for (String deptName : strings) {
                    List<StatisticReportPersonnel> statisticReportPersonnelList = filledInMap.get(deptName);
                    if (statisticReportPersonnelList != null && statisticReportPersonnelList.size() > 0){
                        for (StatisticReportPersonnel statisticReportPersonnel : statisticReportPersonnelList) {
                            Map<String,Object> map = new HashMap<>();
                            map.put("deptName",deptName);
                            map.put("userNameList",statisticReportPersonnel.getUserName());
                            String uploadFile = statisticReportPersonnel.getUploadFile();
                            //[{"name":"1627634606200.pdf","url":"http://192.168.101.11:9300/statics/2021/07/30/1627634606200.pdf","status":"success","uid":1627634606225}]
                            List<SysFile> sysFileList = JSON.parseObject(uploadFile, new TypeReference<List<SysFile>>() {}.getType());
                            List<String> fileName = new ArrayList<>();
                            List<String> fileUrl = new ArrayList<>();
                            if (sysFileList != null && sysFileList.size() > 0){
                                for (SysFile sysFile : sysFileList) {
                                    fileName.add(sysFile.getName());
                                    fileUrl.add(sysFile.getUrl());
                                }
                            }
                            map.put("fileNameList",fileName);
                            map.put("fileUrlList",fileUrl);
                            filledInList.add(map);
                        }
                    }
                }
            }
            reportInfo.setPersonnelList(personnelList);
            reportInfo.setFilledInList(filledInList);
            reportInfo.setFilledOutList(filledOutList);
        }
        return AjaxResult.success(reportInfo);
    }

    @Override
    public Map<String, Object> datas(String name) {
        Map<String, Object> result = new HashMap<>();
        Map<String, String> params = CollectUtils.newHashMap();
        if(StringUtils.isNotEmpty(name)) {
            params.put("name", name);
        }
        params.put("userName", SecurityUtils.getUsername());
        List<StatisticReportDto> reportDtos = statisticReportMapper.selectReportInfo(params);
        result.put("reports", reportDtos);
        return result;
    }

    @Override
    public List<StatisticReport> selectList(StatisticReport report) {
        report.setCreateBy(SecurityUtils.getUsername());
        return statisticReportMapper.selectList(report);
    }

    @Override
    public StatisticReport getDetailById(Long id) {
        return statisticReportMapper.getDetailById(id);
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public AjaxResult saveOrUpdate(StatisticReport report) {
        try {
            if(report.getId() != null) { // 修改
                this.genReport(report, UPDATE);
                // 先删除所有字表数据
                Long[] ids = new Long[1];
                ids[0] = report.getId();
                personnelService.deleteByStatisticIds(ids);
                // 保存报表数据
                statisticReportMapper.update(report);
            }else {//新增
                genReport(report, INSERT);
                statisticReportMapper.insert(report);
            }
            // 获取人员
            this.genReportPersonal(report);
            personnelService.insert(report.getPersonnels());
        }catch (Exception e) {
            LOGGER.info("新增错误，{}", e.getMessage());
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    private void genReport(StatisticReport report, String type) {
        Date now = new Date();
        String username = SecurityUtils.getUsername();
        if (type.equals(INSERT)) {
            report.setCreateBy(username);
            report.setCreateTime(now);
        }

        report.setUpdateBy(username);
        report.setUpdateTime(now);
    }

    private void genReportPersonal(StatisticReport report) {
        Long statisticId = report.getId();
        String reportName =  report.getReportName();
        String userName = SecurityUtils.getUsername();
        Date now = new Date();
        List<StatisticReportPersonnel> personnels = report.getPersonnels();
        for (StatisticReportPersonnel personnel : personnels) {
            personnel.setStatisticId(statisticId);
            personnel.setReportName(reportName);
            personnel.setCreateBy(userName);
            personnel.setCreateTime(now);
            personnel.setUpdateBy(userName);
            personnel.setUpdateTime(now);
        }
    }
}
