package com.yunyan.business.document.y23.budget;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.yunyan.business.document.EasyExcelFinalListener;
import com.yunyan.business.document.utils.ReadExcelUtil;
import com.yunyan.business.document.y23.budget.pojo.budgetY23.*;
import com.yunyan.common.exception.ServiceException;
import com.yunyan.common.utils.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

/**
 * 预算表 表6 合成 的读取
 */
@Slf4j
public class ReadBudgetExcelT6Y22Utils {

    private static void testreadDataT8() {
        readDataT8("桂平", "2022");
    }

    /**
     * 读取
     */
    public static void testRead() {
        //BudgetT6DeptVo t6DeptVo = ReadBudgetExcelT6Y22Utils.readData("102");
        BudgetP3p5SubDeptVo p2p5SubDeptVo = ReadBudgetExcelT6Y22Utils.readDataP3t5( "101001", "田东", "2023");
    }

    /**
     * 预算表6 单独的合成表的 读取 读取 excel数据
     * 只需传一种方式， 当传文件时，直接读取文件
     * @param file 文件实体
     * @param fileName 文件路径名
     * @return
     * @throws IOException
     */
    public static List<BudgetT6DeptVo> getSheetInfos(MultipartFile file, String fileName) throws IOException {
        // step1. 读取excel内容
        EasyExcelFinalListener easyExcelFinalListener = new EasyExcelFinalListener();
        ExcelReaderBuilder read = new ExcelReaderBuilder();
        //        ExcelReaderBuilder read = EasyExcelFactory.read(file.getInputStream(), easyExcelListener);
        if(null != file) {
            read = EasyExcelFactory.read(file.getInputStream(), easyExcelFinalListener).registerConverter(new CellStringNumberConverter());
        } else if(StringUtils.isNotBlank(fileName)) {
            read = EasyExcelFactory.read(fileName, easyExcelFinalListener).registerConverter(new CellStringNumberConverter());
        } else {
            throw new ServiceException("文件读取异常");
        }

        ExcelReader excelReader = read.build();
        // step2. 获取各个sheet页信息
        List<ReadSheet> sheets = excelReader.excelExecutor().sheetList();
        // step3. 获取各个Shhet页表格内容存于map
        Map<Integer, List<LinkedHashMap<Integer, String>>> sheetInfos = new HashMap<>(sheets.size());

        List<BudgetT6DeptVo> t6DeptVoList = new ArrayList<>();

        for (ReadSheet sheet : sheets) {
            Integer sheetNo = sheet.getSheetNo();
            String sheetName =  sheet.getSheetName();
            excelReader.read(sheet);
            sheetInfos.put(sheetNo, easyExcelFinalListener.getListMap());

            setT6Report(easyExcelFinalListener.getListMap(), sheetName,  t6DeptVoList );
        }


        return t6DeptVoList;
    }

    public static void saveToFile(List<BudgetT6DeptVo> t6DeptVoList, String tofileName) {
        String jsonTableContent = JSONUtil.toJsonStr(t6DeptVoList);

        try {
            File file = ResourceUtils.getFile(tofileName);
            FileUtil.writeString(jsonTableContent, file, CharsetUtil.UTF_8);
        } catch (FileNotFoundException e) {
           log.debug("文件异常 [{}]", e);
        }

        log.debug(jsonTableContent);
    }

    /**
     * 读取 临时存的 田东数据
     * @return
     */
    @Deprecated
    private static List<BudgetT6DeptVo> readData() {
        List<BudgetT6DeptVo> listVo = new ArrayList<>();
        try {
            File file = ResourceUtils.getFile("classpath:tempData/y2022.tiandong.budget.t6.txt");
            String jsonTableContent = FileUtil.readUtf8String(file);

            listVo = JSONUtil.toList(jsonTableContent, BudgetT6DeptVo.class);
        } catch (FileNotFoundException e) {
            log.debug("文件异常 [{}]", e);
        }

        return listVo;
    }

    /**
     * 读取预算表6 获取单位的 数据, 决算的 p3部分
     * @param deptCode
     * @return
     */
    public static BudgetT6DeptVo readData(String deptCode, String area, String year) {

        if(StringUtils.isBlank(area)) {
            return null;
        }

        String fileName = "";
        if(StringUtils.isBlank(year)) {
            return null;
        }
        if("2022".equals(year)) {
            if(area.equals("田东")) {
                fileName = "y2022.tiandong.budget.t6.txt";
            } else if(area.equals("桂平")) {
                fileName = "y2022.guiping.budget.t6.txt";
            } else if(area.equals("平果")) {
                fileName = "y2022.pingguo.budget.t6.txt";
            } else {
                return null;
            }
        }
        if("2023".equals(year)) {
            if(area.equals("凭祥")) {
                fileName = "y2023/pingxiang/y2023.pingxiang.budget.t6.txt";
            } else if(area.equals("百色市")) {
                fileName = "y2023/baise/y2023.baise.budget.t6.txt";
            } else if(area.equals("平南")) {
                fileName = "y2023/pingnan/y2023.pingnan.budget.t6.txt";
            } else if(area.equals("博白")) {
                fileName = "y2023/bobai/y2023.bobai.budget.t6.txt";
            } else {
                return null;
            }
        }

        List<BudgetT6DeptVo> listVo = new ArrayList<>();
        InputStream templateInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("tempData/" + fileName);
        if(null == templateInputStream) {
            log.error("读取 resouse的文件 异常: [{}]", fileName);
            throw new RuntimeException("读取 resouse的文件 异常: " + fileName);
        }
        String jsonTableContent = IoUtil.readUtf8(templateInputStream);
        if(StringUtils.isNotBlank(jsonTableContent)) {
            listVo = JSONUtil.toList(jsonTableContent, BudgetT6DeptVo.class);

            if(!listVo.isEmpty()) {
                BudgetT6DeptVo t6DeptVo = listVo.stream().filter(i->i.getDeptCode().equals(deptCode)).findFirst().orElse(null);
                return t6DeptVo;
            }
        }

        /*
        try {
            File file = ResourceUtils.getFile("classpath:tempData/" + fileName);
            String jsonTableContent = FileUtil.readUtf8String(file);

            listVo = JSONUtil.toList(jsonTableContent, BudgetT6DeptVo.class);

            if(!listVo.isEmpty()) {
                BudgetT6DeptVo t6DeptVo = listVo.stream().filter(i->i.getDeptCode().equals(deptCode)).findFirst().orElse(null);
                return t6DeptVo;
            }

        } catch (FileNotFoundException e) {
            log.debug("文件异常 [{}]", e);
        }*/

        return null;
    }

    /**
     * 读取 汇总的 表8预算数据, 决算 t4部分
     * @param area
     * @return
     */
    public static List<BudgetP3p8DeptVo> readDataT8(String area, String year) {
        //TODO 加year

        if(StringUtils.isBlank(area)) {
            // throw new RuntimeException("区域不能为空 : " + area);
            log.info("区域不能为空 : " + area);
            return null;
        }

        if(StringUtils.isBlank(year)) {
            return null;
        }

        String fileName = "";
        if("2022".equals(year)) {
            if (area.equals("桂平")) {
                fileName = "y2022.guiping.budget.t8.txt";
            } else if (area.equals("平果")) {
                fileName = "y2022.pingguo.budget.t8.txt";
            } else {
                return null;
            }
        }
        if("2023".equals(year)) {
            if(area.equals("凭祥")) {
                fileName = "y2023/pingxiang/y2023.pingxiang.budget.t8.txt";
            } else if(area.equals("百色市")) {
                fileName = "y2023/baise/y2023.baise.budget.t8.txt";
            } else if(area.equals("平南")) {
                fileName = "y2023/pingnan/y2023.pingnan.budget.t8.txt";
            } else if(area.equals("博白")) {
                fileName = "y2023/bobai/y2023.bobai.budget.t8.txt";
            } else {
                return null;
            }
        }



        List<BudgetP3p8DeptVo> deptList = new ArrayList<>();
        InputStream templateInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("tempData/" + fileName);
        if(null == templateInputStream) {
            log.error("读取 resouse的文件 异常: [{}]", fileName);
            throw new RuntimeException("读取 resouse的文件 异常: " + fileName);
        }
        String jsonTableContent = IoUtil.readUtf8(templateInputStream);
        if(StringUtils.isNotBlank(jsonTableContent)) {
            deptList = JSONUtil.toList(jsonTableContent, BudgetP3p8DeptVo.class);
        }

        return deptList;
    }

    /**
     * 获取本年的预算数据 p3t2用到, 决算的第二部分
     * @param deptCode
     * @param deptCode
     * @param area 区域
     * @return
     */
    public static BudgetP3p5SubDeptVo readDataP3t5(String deptCode, String area, String year) {
        /*if(deptCode.length() == 3) {
            //3位数时， 默认加 000
            deptCode = deptCode + "000";
        }*/
        if(StringUtils.isBlank(deptCode)) {
            return null;
        }

        if(StringUtils.isBlank(area)) {
            return null;
        }
        if(StringUtils.isBlank(year)) {
            year = DateUtil.thisYear() + "";
        }

        String fileName = "";
        if("2022".equals(year)) {
            if(area.equals("田东")) {
                fileName = "y2022.tiandong.budget.t5.txt";
            } else if(area.equals("桂平")) {
                fileName = "y2022.guiping.budget.t5.txt";
            } else if(area.equals("平果")) {
                fileName = "y2022.pingguo.budget.t5.txt";
            } else {
                return null;
            }
        }
        if("2023".equals(year)) {
            if(area.equals("凭祥")) {
                fileName = "y2023/pingxiang/y2023.pingxiang.budget.t5.txt";
            } else if(area.equals("百色市")) {
                fileName = "y2023/baise/y2023.baise.budget.t5.txt";
            } else if(area.equals("平南")) {
                fileName = "y2023/pingnan/y2023.pingnan.budget.t5.txt";
            } else if(area.equals("博白")) {
                fileName = "y2023/bobai/y2023.bobai.budget.t5.txt";
            } else {
                return null;
            }
        }


        log.debug("file name: [{}] ", fileName);

        InputStream templateInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("tempData/" + fileName);
        if(null == templateInputStream) {
            log.error("读取 resouse的文件 异常: [{}]", fileName);
            throw new RuntimeException("读取 resouse的文件 异常: " + fileName);
        }
        String jsonTableContent = IoUtil.readUtf8(templateInputStream);
        if(StringUtils.isNotBlank(jsonTableContent)) {
            List<BudgetP3p5SubDeptVo> listVo = JSONUtil.toList(jsonTableContent, BudgetP3p5SubDeptVo.class);

            if(!listVo.isEmpty()) {
                BudgetP3p5SubDeptVo t6DeptVo = listVo.stream().filter(i->i.getDeptCode().equals(deptCode)).findFirst().orElse(null);
                return t6DeptVo;
            }
        }

        return null;
    }

    /**
     * 读取 表6
     * @param maps
     * @param
     */
    private static void setT6Report(List<LinkedHashMap<Integer, String>> maps, String sheetName, List<BudgetT6DeptVo> t6DeptVoList ) {

        //p2p6
        BudgetT6DeptVo t6DeptVo  = new BudgetT6DeptVo();
        List<BudgetT6ItemVo> itemList = new ArrayList<>();
        t6DeptVoList.add(t6DeptVo);
        t6DeptVo.setList(itemList);

        //("1.8.1部门预算公开表_101-田东县人民代表大会常务委员会"
        String deptCode = sheetName.substring(sheetName.lastIndexOf("_")+1, sheetName.indexOf("-"));
        String deptName = sheetName.substring(sheetName.lastIndexOf("-")+1);
        t6DeptVo.setDeptName(deptName);
        t6DeptVo.setDeptCode(deptCode);

        //项的 list的查询
        boolean listItemFlag = false;

        for (LinkedHashMap<Integer, String> map : maps) {
            //类 的编码
            String f0a =  map.getOrDefault(0, "");
            //款 的编码
            String f1b =  map.getOrDefault(1, "");
            //项名
            String itemName =  map.getOrDefault(2, "");

            if(listItemFlag) {
                if(StringUtils.isBlank(f1b) && StringUtils.isBlank(itemName) ) {
                    listItemFlag = false;
                }
            }

            if(listItemFlag && StringUtils.isNotBlank(f0a) && StringUtils.isBlank(f1b) &&  StringUtils.isNotBlank(itemName) ) {
                String total = ReadExcelUtil.getMapNumFormatInThousandsYuan(map, 3, "0");
                BudgetT6ItemVo t6ItemVo = new BudgetT6ItemVo();
                t6ItemVo.setCode(f0a);
                t6ItemVo.setName(itemName);
                t6ItemVo.setTotal(total);
                itemList.add(t6ItemVo);
                //t6ItemVo.setCode(f0a);
                /*if(!personTotal.equals("0")) {
                    String nameStr = BudgetY23Util.getStrJoin(p2p6Vo.getPersonStr(), itemName, BudgetY23Util.SEPARATE_STR);
                    p2p6Vo.setPersonStr(nameStr);
                }

                String publicTotal = ReadExcelUtil.getMapNumFormatInThousandsYuan(map, 5, "0");
                if(!publicTotal.equals("0")) {
                    String nameStr = BudgetY23Util.getStrJoin(p2p6Vo.getPublicStr(), itemName, BudgetY23Util.SEPARATE_STR);
                    p2p6Vo.setPublicStr(nameStr);
                }*/
            }


            if(map.containsValue("合计") && map.getOrDefault(2, "").equals("合计")) {
                //合计
                String total = ReadExcelUtil.getMapNumFormatInThousandsYuan(map, 3, "0");
                t6DeptVo.setTotal(total);
                /*String person = ReadExcelUtil.getMapNumFormatInThousandsYuan(map, 4, "0");
                String publicTotal = ReadExcelUtil.getMapNumFormatInThousandsYuan(map, 5, "0");*/

                /*p2p6Vo.setTotal(total);
                p2p6Vo.setPerson(person);
                p2p6Vo.setPublicTotal(publicTotal);*/
                listItemFlag = true;
            }

        }


    }



}
