package cn.com.ctop.kuaishou.modules.live.service.impl;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.kuaishou.modules.live.entity.LiveDataTouch;
import cn.com.ctop.kuaishou.modules.live.enums.TouchEnum;
import cn.com.ctop.kuaishou.modules.live.enums.liveDataUtil;
import cn.com.ctop.kuaishou.modules.live.mapper.LiveDataTouchMapper;
import cn.com.ctop.kuaishou.modules.live.service.ILiveDataTouchService;
import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
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.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 直播数据——触达人群报表
 *
 * @author jeecg-boot
 * 2022-04-02
 * @version V1.0
 */
@Service
public class LiveDataTouchServiceImpl extends ServiceImpl<LiveDataTouchMapper, LiveDataTouch> implements ILiveDataTouchService {

    @Override
    public Result<Object> importExcel(Long accountId, MultipartFile file) throws Exception {
        JSONObject returnJson = new JSONObject();
        Workbook workbook = null;
        String fileName = file.getOriginalFilename();
        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 if ("CSV".equals(substring)) {
            return analysisCsvFile(accountId, file);
        } else {
            throw new Exception("文件不是Excel文件");
        }
        Sheet sheet = workbook.getSheetAt(0);
        if (Check.isNull(sheet)) {
            throw new Exception("Sheet标题不是默认的Sheet1");
        }
        int rows = sheet.getLastRowNum();//行数，一共有多少行+
        if (rows == 0) {
            throw new Exception("请填写数据");
        }
        ExportExcelUtils eeu = new ExportExcelUtils();
        //标题行
        Row titleRow = sheet.getRow(0);
        //最后一列
        int lastCellNum = titleRow.getLastCellNum();
        //获取映射关系
        JSONObject titleObj = liveDataUtil.getTouchTitle(eeu, titleRow, lastCellNum);

        List<JSONObject> array = new ArrayList<>();
        for (int i = 1; i <= rows + 1; i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                JSONObject entityObj = new JSONObject();
                for (int j = 0; j < lastCellNum; j++) {
                    String value = eeu.getCellValue2(row.getCell(j));
                    String code = titleObj.getString(String.valueOf(j));
                    //URL 和 日期 为空时，添加不成功！
                    if (Check.isNull(value)) {
                        return Result.error("数据缺失，文档中第" + (i + 1) + "行，【" + TouchEnum.getNameByCode(code) + "】为空项，请补充完善后导入");
                    }
                    entityObj.put(code, value);
                }
                entityObj.put("accountId", accountId);
                entityObj.put("id", accountId + "_" + DateUtils.formatDate("yyyyMMdd") + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 9));
                array.add(entityObj);
            }
        }
        if (!Check.isNull(array)) {
            if (array.size() > 5000) {
                List<List<JSONObject>> splitVideos = Lists.partition(array, 5000);
                for (List<JSONObject> splitVideo : splitVideos) {
                    baseMapper.replaceBatch(splitVideo);
                }
            } else {
                baseMapper.replaceBatch(array);
            }
        }
        //记录枚举中不存在、不匹配的字段
        String sign = titleObj.getString("sign");
        if (!Check.isNull(sign)) {
            return Result.ok("数据导入成功， 其中（" + sign.substring(0, sign.length() - 1) + "）字段暂时不支持导入，如需要添加请联系研发人员");
        }
        return Result.ok("数据导入成功 ");
    }

    /**
     * 解析 CSV 格式文件
     */
    private Result<Object> analysisCsvFile(Long accountId, MultipartFile file) throws Exception {
        List<String[]> records = new ArrayList<String[]>();
        String record;
        BufferedReader files = new BufferedReader(new InputStreamReader(file.getInputStream(), CharsetUtil.CHARSET_GBK));
        // file.readLine(); //跳过表头所在的行

        // 遍历数据行并存储在名为records的ArrayList中，每一行records中存储的对象为一个String数组
        while ((record = files.readLine()) != null) {
            String fields[] = record.split(",");
            records.add(fields);
        }
        // 关闭文件
        files.close();
        List<List<String>> list = liveDataUtil.getCsvList(records);
        //获取映射关系
        JSONObject titleObj = liveDataUtil.getCsvTouchTitle(list.get(0));
        List<JSONObject> array = new ArrayList<>();
        for (int i = 1; i < list.size(); i++) {
            List<String> values = list.get(i);
            if(values.size()!=titleObj.size()-1){
                return Result.error("数据不全，请补充完善后导入");
            }
            JSONObject entityObj = new JSONObject();
            for (int j = 0; j < values.size(); j++) {
                String value = values.get(j);
                String code = titleObj.getString(String.valueOf(j));
                if (Check.isNull(value)) {
                    return Result.error("数据缺失，文档中第" + (i + 1) + "行，【" + TouchEnum.getNameByCode(code) + "】为空项，请补充完善后导入");
                }
                if ("statDate".equals(code)) {
                    value = DateUtils.formatDate(value.replace("/", "-"), DateUtils.WEB_FORMAT);
                }
                value = liveDataUtil.NUMBER_FORMULA(value);
                if (value.contains("%")) {
                    value = value.replace("%", "");
                    if (!("0.00".equals(value) || "0.0".equals(value) || "0".equals(value))) {
                        float f = Float.valueOf(value) / 100;
                        entityObj.put(code, f);
                    } else {
                        entityObj.put(code, value);
                    }
                } else {
                    entityObj.put(code, value);
                }
            }
            entityObj.put("accountId", accountId);
            entityObj.put("id", accountId + "_" + DateUtils.formatDate("yyyyMMdd") + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 9));
            array.add(entityObj);
        }

        if (!Check.isNull(array)) {
            if (array.size() > 5000) {
                List<List<JSONObject>> splitVideos = Lists.partition(array, 5000);
                for (List<JSONObject> splitVideo : splitVideos) {
                    baseMapper.replaceBatch(splitVideo);
                }
            } else {
                baseMapper.replaceBatch(array);
            }
        }
        //记录枚举中不存在活不匹配的字段
        String sign = titleObj.getString("sign");
        if (!Check.isNull(sign)) {
            return Result.ok("数据导入成功， 其中（" + sign.substring(0, sign.length() - 1) + "）字段暂时不支持导入，如需要添加请联系研发人员");
        }
        return Result.ok("数据导入成功 ");
    }


}
