package com.bootdo.datas.service.impl;

import com.bootdo.common.domain.DictDO;
import com.bootdo.common.service.DictService;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.datas.dao.DataDao;
import com.bootdo.datas.domain.DataDO;
import com.bootdo.datas.domain.UnitDO;
import com.bootdo.datas.dto.DateAndCountDTO;
import com.bootdo.datas.dto.DateAndCountListDTO;
import com.bootdo.datas.dto.MapDataDTO;
import com.bootdo.datas.dto.NameAndValueDTO;
import com.bootdo.datas.service.DataService;
import com.bootdo.datas.service.GyDataService;
import com.bootdo.system.domain.UserDO;
import com.google.common.collect.Lists;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.*;

@Service
public class DataServiceImpl implements DataService {

    private static Logger log = LoggerFactory.getLogger(DataServiceImpl.class);

    @Autowired
    private DataDao dataDao;

    @Value("${managerValue}")
    public String managerValue;

    @Autowired
    private DictService dictService;

    @Autowired
    private GyDataService gyDataService;

    @Override
    public List<MapDataDTO> mapDataList(String dataLevel) {
        return dataDao.mapDataList(dataLevel);
    }

    @Override
    public List<DateAndCountDTO> trendData() {
        UserDO currUser = ShiroUtils.getUser();
        String provinceName = null;
        if (!managerValue.contains(currUser.getDeptId().toString())) {
            provinceName = currUser.getProvince();
        }
        log.info("method: trendData, user: " + currUser.getUsername() + " provinceName: " + provinceName);
        return dataDao.trendData(provinceName);
    }

    @Override
    public List<NameAndValueDTO> industryData() {
        UserDO currUser = ShiroUtils.getUser();
        String provinceName = null;
        if (!managerValue.contains(currUser.getDeptId().toString())) {
            provinceName = currUser.getProvince();
        }

        List<NameAndValueDTO> dtoList = dataDao.IndustryData(provinceName);

        log.info("method: IndustryData, user: " + currUser.getUsername() + " provinceName: " +
                provinceName + " 数据: " + dtoList);

        // 处理 超过6条时, 将6条以上转为其他中 合并集合
        if (!CollectionUtils.isEmpty(dtoList) && dtoList.size() > 6) {
            return mergeDataList(dtoList);
        }

        // 不处理直接返回
        return dtoList;
    }

//    @Override
//    public List<NameAndValueDTO> industryTypeData() {
//        UserDO currUser = ShiroUtils.getUser();
//        String provinceName = null;
//        if (!managerValue.contains(currUser.getDeptId().toString())) {
//            provinceName = currUser.getProvince();
//        }
//
//        List<NameAndValueDTO> dtoList = dataDao.industryTypeData(provinceName);
//
//        log.debug("method: industryTypeData, user: " + currUser.getUsername() + " provinceName: " +
//                provinceName + " datas: " + dtoList);
//
//        // 处理 超过6条时, 将6条以上转为其他中 合并集合
//        if (!CollectionUtils.isEmpty(dtoList) && dtoList.size() > 6) {
//            return mergeDataList(dtoList);
//        }
//
//        // 不处理直接返回
//        return dtoList;
//    }

    @Override
    public List<NameAndValueDTO> industryTypeData() {
        UserDO currUser = ShiroUtils.getUser();
        String provinceName = null;
        if (!managerValue.contains(currUser.getDeptId().toString())) {
            provinceName = currUser.getProvince();
        }
        List<NameAndValueDTO> dtoList = new ArrayList<>();
        // 查询列表数据
        Map<String, Object> query = new HashMap<>(16);
        query.put("type", "industry_type");
        List<DictDO> dictList = dictService.list(query);
        query.clear();
        for (DictDO dictDO:dictList){
            String value = dictDO.getValue();
            query.put("industryTypeOne",value);
            query.put("unitProvince",provinceName);
            int total = gyDataService.countTotal(query);
            if (total > 0) {
                NameAndValueDTO nameAndValueDTO = new NameAndValueDTO();
                nameAndValueDTO.setName(value);
                nameAndValueDTO.setValue(total);
                dtoList.add(nameAndValueDTO);
            }
        }

        log.debug("method: industryTypeData, user: " + currUser.getUsername() + " provinceName: " +
                provinceName + " datas: " + dtoList);

        // 处理 超过6条时, 将6条以上转为其他中 合并集合
//        if (!CollectionUtils.isEmpty(dtoList) && dtoList.size() > 6) {
//            return mergeDataList(dtoList);
//        }

        // 不处理直接返回
        return dtoList;
    }

    @Override
    public DateAndCountListDTO dataLevelData() {
        UserDO currUser = ShiroUtils.getUser();
        String provinceName = null;
        if (!managerValue.contains(currUser.getDeptId().toString())) {
            provinceName = currUser.getProvince();
        }


        List<DateAndCountDTO> importantData = dataDao.dataLevelData(provinceName, "重要数据");
        List<DateAndCountDTO> coreData = dataDao.dataLevelData(provinceName, "核心数据");

        log.info("method: dataLevelData, user: " + currUser.getUsername() + " provinceName: " +
                provinceName + " 核心: " + coreData + " 重要: " + importantData);

        return new DateAndCountListDTO(importantData, coreData);
    }

    @Override
    public Double dataAuditData() {
        UserDO currUser = ShiroUtils.getUser();
        String provinceName = null;
        if (!managerValue.contains(currUser.getDeptId().toString())) {
            provinceName = currUser.getProvince();
        }
        Double passingRate = dataDao.dataAuditData(provinceName);
        log.info("method: dataAuditData, user: " + currUser.getUsername() + " provinceName: " +
                provinceName + " 通过率: " + passingRate);
        return passingRate;
    }

    @Override
    public List<NameAndValueDTO> dataCategoryData() {
        UserDO currUser = ShiroUtils.getUser();
        String provinceName = null;
        if (!managerValue.contains(currUser.getDeptId().toString())) {
            provinceName = currUser.getProvince();
        }
        List<NameAndValueDTO> result = dataDao.dataCategoryData(provinceName);
        log.info("method: dataCategoryData, user: " + currUser.getUsername() + " provinceName: " +
                provinceName + " 数据结果: " + result.toString());
        return result;
    }

    @Override
    public List<DataDO> portalDataList(Map<String, Object> parameter) {
        return dataDao.portalDataList(parameter);
    }

    @Override
    public Long portalDataListCount(Map<String, Object> parameter) {
        return dataDao.portalDataListCount(parameter);
    }

    /**
     * 超过六条 需要合并数据
     *
     * @param dtoList
     * @return
     */
    private List<NameAndValueDTO> mergeDataList(List<NameAndValueDTO> dtoList) {
        List<NameAndValueDTO> newDataList = Lists.newArrayList();
        NameAndValueDTO nameAndValueDTO = new NameAndValueDTO();
        nameAndValueDTO.setName("其他");
        nameAndValueDTO.setValue(0);
        for (int i = 0; i < dtoList.size(); i++) {
            if (i > 4) {
                nameAndValueDTO.setValue(nameAndValueDTO.getValue() + dtoList.get(i).getValue());
            } else {
                newDataList.add(dtoList.get(i));
            }
        }
        newDataList.add(nameAndValueDTO);
        return newDataList;
    }

    /**
     * 去除重复数据 由于Set的无序性，不会保持原来顺序
     *
     * @param list
     */
    public List<UnitDO> distinct(List<UnitDO> list) {

        List<UnitDO> newlist = new ArrayList<>();
        list.forEach(t -> {
            // anyMatch表示有一个匹配就返回true;
            boolean match = newlist.stream().anyMatch(u -> t.getReporterUnit().equals(u.getReporterUnit()));
            if (!match) {
                newlist.add(t);
            }
        });
        return newlist;
    }

    /**
     * @Description: 遍历excel信息
     * @Author: wangp
     * @Date: 2022/3/9 20:56
     * @param cell
     * @Return: String
     */
    private String getValues(Cell cell) {
        String value = "";
        try {
            if (cell != null) {
                log.info("CellType" + cell.getCellType());
                // cell.setCellType(CellType.STRING);
                value = cell.getStringCellValue();
            } else {
                value = "无";
            }
        } catch (Exception e) {
            log.info("String 处理异常");
            cell.setCellType(CellType.STRING);
            value = cell.getStringCellValue();
        }
        return value;
    }


    /**
     * @Description: 备案信息同步
     * @Author: wangp
     * @Date: 2022/4/22 15:55
     * @param dataDO
     * @Return: void
     */
    @Override
    public void datAsync(DataDO dataDO) {
        // 企业同步
//        UnitDO unitDO = new UnitDO();
//        unitDO.setReporterUnit(dataDO.getReporterUnit());// 数据处理者名称
//        unitDO.setIndustryType(dataDO.getIndustryType());// 所属行业
//        unitDO.setDataIndustry(dataDO.getDataIndustry());// 所属行业子类
//        unitDO.setUnitProvince(dataDO.getUnitProvince());// 省份
//        unitDO.setUnitCity(dataDO.getUnitCity());// 地市
//        unitDO.setUnitOther(dataDO.getUnitOther());// 地市
//        unitDO.setUploadUser("api");
//        unitDO.setUploadUserid("-1");
//        //查询企业
//        UnitDO unitDOs = unitDao.getUnit(unitDO);
//        if (unitDOs == null) {
//            try {
//                unitDao.save(unitDO);
//            } catch (Exception e) {
//                log.error("error reomve : {}", e.getMessage());
//            }
//        }
//        // 测试
//        dataDO.setDataName(dataDO.getDataName());
//        // 备案数据同步
//        Map<String, Object> params = new HashMap<>();
//        // 数据名称
//        params.put("dataName", dataDO.getDataName());
//        // 单位
//        params.put("reporterUnit", dataDO.getReporterUnit());
//        // 数据来源
//        params.put("dataSource", dataDO.getDataSource());
//        // 未删除状态的数据
//        params.put("deleteStatus", "0");
//        List<DataDO> listInfo = dataDao.queryList(params);
//
//        if (listInfo != null && listInfo.size() > 0) {
//            // 删除数据
//            log.info("删除数据id：" + listInfo.get(0).getId());
//            dataDao.remove(listInfo.get(0).getId());
//        }
//        dataDO.setSendVerify("1");// 送审状态 0:未送审 1：已送审
//        // 存储
//        dataDao.save(dataDO);

    }

}
