package cn.com.ctop.toutiao.modules.material.service.impl;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.common.module.utils.LoadFileUtil;
import cn.com.ctop.toutiao.modules.material.entity.FirstDeliveryValidMaterials;
import cn.com.ctop.toutiao.modules.material.entity.FirstDeliveryValidRatio;
import cn.com.ctop.toutiao.modules.material.mapper.FirstDeliveryValidMapper;
import cn.com.ctop.toutiao.modules.material.service.FirstDeliveryValidService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
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.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class FirstDeliveryValidServiceImpl implements FirstDeliveryValidService {

    @Autowired
    private FirstDeliveryValidMapper deliveryValidMapper;

    @Override
    public Result<Object> importExcelMaterials(MultipartFile file) throws Exception {
        List<FirstDeliveryValidMaterials> dataList = new ArrayList<>();
        StringBuffer path = new StringBuffer();
        try {
            String fileName = file.getOriginalFilename();
            List<JSONObject> list = this.analysisFile(file, fileName);
            LoadFileUtil.delFile(path.toString());
            for (JSONObject object : list) {
                FirstDeliveryValidMaterials material = new FirstDeliveryValidMaterials(object);
                if (!Check.isNull(material.getStatDate())) {
                    material.setDeliveryYear(material.getStatDate().substring(0, 4));
                }
                dataList.add(material);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("导入异常，" + e.getMessage());
        } finally {
            LoadFileUtil.delFile(path.toString());
        }
        if (!Check.isNull(dataList)) {
            //根据当前年份和月份，删除旧数据
            FirstDeliveryValidMaterials material = dataList.get(0);
            deliveryValidMapper.delMaterials(material.getDeliveryYear(), material.getDeliveryMonth());
            //插入 数据量大于5W，分批插入
            if (dataList.size() > 50000) {
                List<List<FirstDeliveryValidMaterials>> splitList = Lists.newArrayList(Lists.partition(dataList, 50000));
                for (List<FirstDeliveryValidMaterials> materials : splitList) {
                    deliveryValidMapper.replaceBatchMaterials(materials);
                }
            } else {
                deliveryValidMapper.replaceBatchMaterials(dataList);
            }
        }
        //执行宇鹏提供的sql
        deliveryValidMapper.replaceEtl();
        return Result.successMsg("导入成功", null);
    }

    @Override
    public Result<Object> importExcelRatio(MultipartFile file) throws Exception {
        List<FirstDeliveryValidRatio> dataList = new ArrayList<>();
        String year = DateUtils.date2Str().substring(0, 4);
        try {
            String fileName = file.getOriginalFilename();
            List<JSONObject> list = this.analysisFile(file, fileName);
            for (JSONObject object : list) {
                FirstDeliveryValidRatio material = new FirstDeliveryValidRatio(object);
                if ("走量".equals(material.getOperationLabel())) {
                    continue;
                }
                material.setDeliveryYear(year);
                dataList.add(material);
            }
        } catch (
                Exception e) {
            e.printStackTrace();
            throw new Exception("导入异常，" + e.getMessage());
        }
        if (!Check.isNull(dataList)) {
            //根据当前年份和月份，删除旧数据
            FirstDeliveryValidRatio material = dataList.get(0);
            deliveryValidMapper.delRatio(material.getDeliveryYear(), material.getDeliveryMonth());
            //插入 数据量大于5W，分批插入
            if (dataList.size() > 50000) {
                List<List<FirstDeliveryValidRatio>> splitList = Lists.newArrayList(Lists.partition(dataList, 50000));
                for (List<FirstDeliveryValidRatio> materials : splitList) {
                    deliveryValidMapper.replaceBatchRatio(materials);
                }
            } else {
                deliveryValidMapper.replaceBatchRatio(dataList);
            }
        }
        return Result.successMsg("导入成功", null);
    }

    @Override
    public List<JSONObject> getDataForProject(String year, String month) {
        return deliveryValidMapper.getDataForProject(year, month);
    }


    @Override
    public List<JSONObject> getDataForUserType(String year, String month, String userType) {
        return deliveryValidMapper.getDataForUserType(year, month, userType);
    }

    @Override
    public Result<Object> getDesignData(String date, Integer pageSize, Integer pageNo, Integer designRole) {
        String[] split = date.split("-");
        String year = split[0];
        String monthStr = split[1];
        String month = monthStr;
        if (Integer.valueOf(monthStr) < 10) {
            month = monthStr.replace("0", "");
        }
        Integer total = deliveryValidMapper.getDesignDataTotal(year, month, designRole);
        PageHelper.startPage(pageNo, pageSize, true);
        List<JSONObject> data = deliveryValidMapper.getDesignData(year, month, designRole);
        PageInfo<JSONObject> page = new PageInfo<>();
        page.setList(data);
        page.setTotal(total);
        return Result.OK(page);
    }


    @Override
    public List<JSONObject> getDesignDataExport(String date, Integer designRole) {
        String[] split = date.split("-");
        String year = split[0];
        String monthStr = split[1];
        String month = monthStr;
        if (Integer.valueOf(monthStr) < 10) {
            month = monthStr.replace("0", "");
        }
        List<JSONObject> data = deliveryValidMapper.getDesignData(year, month, designRole);
        return data;

    }


    @Override
    public Result<Object> projectData(String date, Integer pageSize, Integer pageNo) {
        String[] split = date.split("-");
        String year = split[0];
        String monthStr = split[1];
        String month = monthStr;
        if (Integer.valueOf(monthStr) < 10) {
            month = monthStr.replace("0", "");
        }
        Integer total = deliveryValidMapper.projectDataTotal(year, month);
        PageHelper.startPage(pageNo, pageSize, true);
        List<JSONObject> data = deliveryValidMapper.projectData(year, month);
        PageInfo<JSONObject> page = new PageInfo<>();
        page.setList(data);
        page.setTotal(total);
        return Result.OK(page);
    }

    @Override
    public Result<Object> getTotalData(String date, Integer pageSize, Integer pageNo) {
        String[] split = date.split("-");
        String year = split[0];
        String monthStr = split[1];
        String month = monthStr;
        if (Integer.valueOf(monthStr) < 10) {
            month = monthStr.replace("0", "");
        }
        Integer total = deliveryValidMapper.getTotalDataSum(year, month);
        PageHelper.startPage(pageNo, pageSize, true);
        List<JSONObject> data = deliveryValidMapper.getTotalData(year, month);
        PageInfo<JSONObject> page = new PageInfo<>();
        page.setList(data);
        page.setTotal(total);
        return Result.OK(page);
    }

    public static List<JSONObject> analysisFile(MultipartFile file, String fileName) throws Exception {
        JSONObject returnJson = new JSONObject();
        Workbook workbook = null;
        String substring = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
        if ("XLS".equals(substring)) {
            workbook = new HSSFWorkbook(file.getInputStream());
        } else if ("XLSX".equals(substring)) {
            workbook = new XSSFWorkbook(file.getInputStream());
        } else {
            throw new Exception("请上传正确格式的文件，支持扩展名.xls;.xlsx");
        }
        Sheet sheet = workbook.getSheetAt(0);
        if (Check.isNull(sheet)) {
            throw new Exception("未读取到Sheet页内容！");
        }
        int rows = sheet.getLastRowNum();//行数，一共有多少行+
        if (rows == 0) {
            throw new Exception("请填写数据");
        }
        ExportExcelUtils eeu = new ExportExcelUtils();
        //标题行
        Row titleRow = sheet.getRow(0);
        //最后一列（列数）
        int lastCellNum = titleRow.getLastCellNum();

        // list存储数据集
        List<JSONObject> list = new ArrayList<>();
        for (int i = 1; i <= rows + 1; i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                //每行数据对象，按照顺序从0到（lastCellNum-1）记录
                JSONObject cellEntity = new JSONObject();
                for (int j = 0; j < lastCellNum; j++) {
                    cellEntity.put(String.valueOf(j), eeu.getCellValue2(row.getCell(j)).replace("\"", ""));
                }
                list.add(cellEntity);
            }
        }
        return list;
    }

}
