package com.ruoyi.system.service.grid.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.zqt.ZQTImportExcelUtil;
import com.ruoyi.system.domain.grid.GridCompany;
import com.ruoyi.system.domain.grid.GridCompanyEconomy;
import com.ruoyi.system.domain.grid.GridCompanyEconomyExample;
import com.ruoyi.system.domain.grid.GridCompanyExample;
import com.ruoyi.system.domain.grid.ext.GridCompanyEconomyExt;
import com.ruoyi.system.domain.grid.vo.GridStatistic;
import com.ruoyi.system.domain.other.BsCommon;
import com.ruoyi.system.domain.other.BsCommonExample;
import com.ruoyi.system.listener.MyBaseService;
import com.ruoyi.system.mapper.grid.GridCompanyEconomyMapper;
import com.ruoyi.system.service.BaseServiceImpl;
import com.ruoyi.system.service.grid.GridCompanyEconomyService;
import com.ruoyi.system.service.grid.GridCompanyService;
import com.ruoyi.system.service.other.BsCommonService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Cesar
 * @date ${cTime}
 * @desc GridCompanyEconomyService实现
 */
@Service
@MyBaseService
public class GridCompanyEconomyServiceImpl extends BaseServiceImpl<GridCompanyEconomyMapper, GridCompanyEconomy, GridCompanyEconomyExample> implements GridCompanyEconomyService {

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

    @Autowired
    GridCompanyEconomyMapper gridCompanyEconomyMapper;

    @Autowired
    GridCompanyService gridCompanyService;

    @Autowired
    BsCommonService bsCommonService;

    private static String companyCode = "qylx";

    @Override
    public List<GridCompanyEconomy> selectGridCompanyEconomyByCreditCode(String creditCode, String belongTime) {
        GridCompanyEconomyExample ex = new GridCompanyEconomyExample();
        GridCompanyEconomyExample.Criteria ca = ex.createCriteria();
        if (StringUtils.isNotBlank(creditCode)) {
            ca.andCreditCodeEqualTo(creditCode);
        }
        if (StringUtils.isNotBlank(belongTime)) {
            ca.andBelongTimeEqualTo(belongTime);
        }
        return this.selectByExample(ex);
    }

    @Override
    public AjaxResult importExcel(MultipartFile file, String belongTime) {
        if (file == null) {
            return AjaxResult.error(400, "文件不存在");
        }
        StringBuilder msg = new StringBuilder();
        Workbook workbook = null;
        try {
            String fileName = file.getOriginalFilename();
            InputStream is = file.getInputStream();
            if ("xls".equals(ZQTImportExcelUtil.getPostFix(fileName))) {
                workbook = new HSSFWorkbook(is);
            } else if ("xlsx".equals(ZQTImportExcelUtil.getPostFix(fileName))) {
                workbook = new XSSFWorkbook(is);
            } else {
                return AjaxResult.error(400, "文件格式不正确");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            msg.append(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            msg.append(e.getMessage());
            return AjaxResult.error(400, "系统错误" + msg);
        }

        List<GridCompanyEconomy> list = new ArrayList<>();

//        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
//            Sheet sheet = workbook.getSheetAt(i); //读取工作表
//            if (sheet == null) //空判断
//                continue;
//            for (int j = 1; j <= sheet.getLastRowNum(); j++) {
//                Row row = sheet.getRow(j); //读取每行
//                if (row.getCell(0) != null) {
//                    GridCompanyEconomy ce = new GridCompanyEconomy();
//                    if (StringUtils.isBlank(ImportExcelUtil.getValue(row.getCell(0)))) {
//                        msg.append("第").append(j).append("行统一社会信用代码不能为空;");
//                    } else {
//                        ce.setCreditCode(ImportExcelUtil.getValue(row.getCell(0)).trim());
//                    }
//
//                    if (StringUtils.isBlank(ImportExcelUtil.getValue(row.getCell(1)))) {
//                        msg.append("第").append(j).append("行企业名称不能为空;");
//                    } else {
//                        ce.setCompanyName(ImportExcelUtil.getValue(row.getCell(1)).trim());
//                    }
//                    ce.setSale(ImportExcelUtil.getValue(row.getCell(2)));
//                    ce.setTax(ImportExcelUtil.getValue(row.getCell(3)));
//                    ce.setProduction(ImportExcelUtil.getValue(row.getCell(4)));
//                    list.add(ce);
//                }
//            }
//        }


        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i); //读取工作表
            if (sheet == null) //空判断
                continue;
            for (int j = 1; j <= sheet.getLastRowNum(); j++) {
                Row row = sheet.getRow(j); //读取每行
                if (row.getCell(0) != null) {
                    GridCompanyEconomy ce = new GridCompanyEconomy();
                    ce.setCreditCode(ZQTImportExcelUtil.getValue(row.getCell(0)));
                    ce.setCompanyName(ZQTImportExcelUtil.getValue(row.getCell(1)));
                    ce.setSale(ZQTImportExcelUtil.getValue(row.getCell(2)));
                    ce.setTax(ZQTImportExcelUtil.getValue(row.getCell(3)));
                    ce.setProduction(ZQTImportExcelUtil.getValue(row.getCell(4)));
                    list.add(ce);
                }
            }
        }

        if (StringUtils.isBlank(msg)) {
            int records = 0;
            int temp = 0;
            try {
                for (GridCompanyEconomy ce : list) {
                    List<GridCompanyEconomy> companyEconomyList = this.selectGridCompanyEconomyByCreditCode(ce.getCreditCode(), belongTime);
                    if (companyEconomyList.isEmpty()) {
                        ce.setId(IdUtil.fastSimpleUUID());
                        ce.setBelongTime(belongTime);
                        ce.setCreateTime(DateUtil.formatDateTime(new Date()));
                        temp = this.insertSelective(ce);
                    } else {
                        ce.setId(companyEconomyList.get(0).getId());
                        ce.setBelongTime(belongTime);
                        ce.setCreateTime(DateUtil.formatDateTime(new Date()));
                        temp = this.updateByPrimaryKeySelective(ce);
                    }
                    if (temp == 1) {
                        records++;
                    } else {
                        msg.append("第").append(records + 2).append("行数据导入出错:");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                msg.append(e.getMessage());
                return AjaxResult.error(400, msg.toString());
            }
            msg.append("导入").append(records).append("条数据");
            return AjaxResult.success("success", msg.toString());//返回成功信息
        }
        return AjaxResult.error(400, msg.toString());
    }

    @Override
    public HashMap<String, Object> getNowYearCount(String wgCode) {

        HashMap<String, Object> result = new HashMap<>();

        result.put("sale", 0);
        result.put("tax", 0);
        result.put("production", 0);

        List<GridCompanyEconomy> companyEconomylist = this.listComEconomy(wgCode, null);

        //没有数据 直接返回
        if (CollectionUtils.isEmpty(companyEconomylist)) {
            return result;
        }

        BigDecimal sale = new BigDecimal(0);
        BigDecimal tax = new BigDecimal(0);
        BigDecimal production = new BigDecimal(0);

        for (GridCompanyEconomy o : companyEconomylist) {
            sale = sale.add(new BigDecimal(o.getSale()));
            tax = tax.add(new BigDecimal(o.getTax()));
            production = production.add(new BigDecimal(o.getProduction()));
        }

        result.put("sale", sale);
        result.put("tax", tax);
        result.put("production", production);

        return result;
    }

    private List<GridCompanyEconomy> listComEconomy(String wgCode, Integer year) {
        GridCompanyExample wsCompanyExample = new GridCompanyExample();
        GridCompanyExample.Criteria criteria = wsCompanyExample.createCriteria();
        if (StringUtils.isNotBlank(wgCode)) {
            criteria.andWgCodeLike(wgCode + "%");
        }
        List<GridCompany> wsCompanies = gridCompanyService.selectByExample(wsCompanyExample);

        if (CollectionUtils.isEmpty(wsCompanies)) {
            return new ArrayList<>();
        }

        List<String> creditCodes = wsCompanies.stream().map(o -> o.getCreditCode()).collect(Collectors.toList());
        if(year == null){
            Calendar calendar = Calendar.getInstance();
            year = calendar.get(Calendar.YEAR);
        }
        GridCompanyEconomyExample ex = new GridCompanyEconomyExample();
        GridCompanyEconomyExample.Criteria ca = ex.createCriteria();
        ca.andCreditCodeIn(creditCodes);
        ca.andBelongTimeLike( year+ "%");
        List<GridCompanyEconomy> companyEconomylist = gridCompanyEconomyMapper.selectByExample(ex);

        return companyEconomylist;
    }

    @Override
    public HashMap<String, Object> getMonthCount(Integer year) {

        HashMap<String, Object> result = new HashMap<>();

        List<GridCompanyEconomy> companyEconomylist = this.listComEconomy(null, year);

        Map<String, List<GridCompanyEconomy>> economyMap = companyEconomylist.stream()
                .collect(Collectors.groupingBy(GridCompanyEconomy::getBelongTime));

        List<GridStatistic> saleWs = new ArrayList<>();
        List<GridStatistic> taxWs = new ArrayList<>();
        List<GridStatistic> productionWs = new ArrayList<>();

        result.put("sale", saleWs);
        result.put("tax", taxWs);
        result.put("production", productionWs);

        for (int i = 0; i < 12; i++) {
            String ym;
            if(i < 9){
                ym = year + "-0" + (i+1);
            }else{
                ym = year + "-" + (i+1);
            }
            BigDecimal sale = new BigDecimal(0);
            BigDecimal tax = new BigDecimal(0);
            BigDecimal production = new BigDecimal(0);

            if (economyMap.containsKey(ym)) {
                for (GridCompanyEconomy o : economyMap.get(ym)) {
                    sale = sale.add(new BigDecimal(o.getSale()));
                    tax = tax.add(new BigDecimal(o.getTax()));
                    production = production.add(new BigDecimal(o.getProduction()));
                }
            }
            GridStatistic wsSale = new GridStatistic();
            wsSale.setYm(ym);
            wsSale.setNum(sale.toString());
            saleWs.add(wsSale);

            GridStatistic wsTax = new GridStatistic();
            wsTax.setYm(ym);
            wsTax.setNum(tax.toString());
            taxWs.add(wsTax);

            GridStatistic wsPro = new GridStatistic();
            wsPro.setYm(ym);
            wsPro.setNum(production.toString());
            productionWs.add(wsPro);
        }

        return result;
    }


    @Override
    public List<GridCompanyEconomy> getTopTenCount(String wgCode, String type) {

        List<GridCompanyEconomy> result = new ArrayList<>();

        List<GridCompanyEconomy> companyEconomylist = this.listComEconomy(wgCode, null);

        //没有数据 则返回空列表
        if (CollectionUtils.isEmpty(companyEconomylist)) {
            return result;
        }

        Map<String, List<GridCompanyEconomy>> comEconomyMap = companyEconomylist.stream()
                .collect(Collectors.groupingBy(GridCompanyEconomy::getCreditCode));

        //获取企业表中企业名称对应信用代码
        GridCompanyExample wsCompanyExample = new GridCompanyExample();
        GridCompanyExample.Criteria criteria = wsCompanyExample.createCriteria();
        if (StringUtils.isNotBlank(wgCode)) {
            criteria.andWgCodeLike(wgCode + "%");
        }
        List<GridCompany> wsCompanies = gridCompanyService.selectByExample(wsCompanyExample);


        Map<String, GridCompany> creditMap = wsCompanies.stream().collect(Collectors.toMap(GridCompany::getCreditCode, v -> v));

        BsCommonExample commonExample = new BsCommonExample();
        BsCommonExample.Criteria commonCriteria = commonExample.createCriteria();
        commonCriteria.andCodeLike(companyCode + "%");
        List<BsCommon> commons = bsCommonService.selectByExample(commonExample);

        Map<String, String> commonMap = commons.stream().collect(Collectors.toMap(BsCommon::getCode, BsCommon::getName));

        for (String creditCode : comEconomyMap.keySet()) {

            BigDecimal sale = new BigDecimal(0);
            BigDecimal tax = new BigDecimal(0);
            BigDecimal production = new BigDecimal(0);

            for (GridCompanyEconomy o : comEconomyMap.get(creditCode)) {
                sale = sale.add(new BigDecimal(o.getSale()));
                tax = tax.add(new BigDecimal(o.getTax()));
                production = production.add(new BigDecimal(o.getProduction()));
            }

            GridCompanyEconomyExt economy = new GridCompanyEconomyExt();
            GridCompany company = creditMap.get(creditCode);
            economy.setCompanyName(null != company ? company.getCompanyName() : "");
            economy.setTypeName(null != company ? commonMap.get(company.getQylxCode()) : "");
            economy.setCreditCode(creditCode);
            economy.setSale(sale.toString());
            economy.setTax(tax.toString());
            economy.setProduction(production.toString());

            result.add(economy);
        }

        //根据 税收 销售 产值 进行排序
        if ("1".equals(type)) {
            result = result.stream()
                    .sorted(Comparator.comparing(o -> new BigDecimal(o.getSale()), Comparator.reverseOrder()))
                    .collect(Collectors.toList());
        } else if ("2".equals(type)) {
            result = result.stream()
                    .sorted(Comparator.comparing(o -> new BigDecimal(o.getTax()), Comparator.reverseOrder()))
                    .collect(Collectors.toList());
        } else if ("3".equals(type)) {
            result = result.stream()
                    .sorted(Comparator.comparing(o -> new BigDecimal(o.getProduction()), Comparator.reverseOrder()))
                    .collect(Collectors.toList());
        }

        if (!CollectionUtils.isEmpty(result) && result.size() > 10) {
            result = result.subList(0, 10);
        }
        return result;
    }
}
