package com.reyun.util;

import com.reyun.dic.UploadErrorEnumType;
import com.reyun.model.UploadHistory;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sunhao on 17/5/19.
 * desc:EXCEL操作工具类
 */
public class ExcelUtil {

    private static final Logger logger = LoggerFactory.getLogger(AwsS3Util.class);
    private static final int MAX_UPLOAD_ROW = 1000;
    private static final int MAX_KEYWORD_LENGTH = 40;
    private static final int MAX_CREATIVE_LENGTH = 40;
    private static final String KEYWORD_TABLE_HEAD_URL = "访问地址/应用下载地址";
    private static final String KEYWORD_TABLE_HEAD_KEYWORD = "关键词";
    private static final String KEYWORD_TABLE_HEAD_CREATIVE = "创意";



    /**
     * 读取keywords的EXCEL文件,最多支持读取1000行,之后的数据丢弃。
     * 文件格式:下载地址  关键字  创意
     * created by sunhao 20170519
     */
    public static UploadHistory readKeywordsExcel(InputStream inputStream){

        UploadHistory uploadHistory = new UploadHistory();
        List<Integer> errorRowList = new ArrayList<>();
        Map<String,Map<Integer,String>> keywordCreativeMap = new HashMap<>();

        try {

            //Get the workbook instance for XLS and XLSX file
            Workbook workbook = WorkbookFactory.create(inputStream);

            //获取第一个SHEET
            Sheet sheet = workbook.getSheetAt(0);

            //数据格式化
            DataFormatter cellDadaFormat = new DataFormatter();

            //取行数,最多读1000行
            int rowNumber = sheet.getLastRowNum();
            rowNumber = rowNumber > MAX_UPLOAD_ROW ? MAX_UPLOAD_ROW : rowNumber;

            //校验表头格式false 不合法,true 合法
            boolean tableHeadValid = checkTableHead(sheet.getRow(0),cellDadaFormat);

            //空表校验
            if(rowNumber == 0){

                if(tableHeadValid){
                    uploadHistory.setErrorType(UploadErrorEnumType.TABLE_EMPTY.getKey());
                } else {
                    uploadHistory.setErrorType(UploadErrorEnumType.HEAD_ERROR.getKey());
                }

                return uploadHistory;
            }

            //表头有误
            if(!tableHeadValid){
                uploadHistory.setErrorType(UploadErrorEnumType.HEAD_ERROR.getKey());
                return uploadHistory;
            }


            //从第二行读起
            for (int i = 1; i <= rowNumber; i++) {

                Row row = sheet.getRow(i);

                if (null == row) {
                    errorRowList.add(i + 1);
                    continue;
                }

                //读取前三列,下载地址,关键字,创意
                String url = getCellStringValue(row, cellDadaFormat, 0);
                String keyword = getCellStringValue(row, cellDadaFormat, 1);
                String creative = getCellStringValue(row, cellDadaFormat, 2);

                //构建subCampaign,校验字符串合法性
                String keywordString = checkAndBuildKeywordString(url, keyword, creative);

                //构建
                if (!StringUtils.isEmpty(keywordString)) {

                    String mapKey = getKeywordKey(keyword, creative);

                    Map<Integer, String> rowDataMap = keywordCreativeMap.get(mapKey);
                    rowDataMap = (null == rowDataMap ? new HashMap<Integer, String>() : rowDataMap);

                    rowDataMap.put(i + 1, keywordString);
                    keywordCreativeMap.put(mapKey, rowDataMap);

                } else {

                    errorRowList.add(i + 1);
                }
            }

            uploadHistory.setUploadErrorList(errorRowList);
            uploadHistory.setRowNumber(sheet.getLastRowNum());
            uploadHistory.setKeywordCreativeMap(keywordCreativeMap);

        } catch (IOException | InvalidFormatException e) {
            logger.error(e.getMessage());
            uploadHistory = null;
        }

        return uploadHistory;
    }

    /**
     * 校验表头是否正确 false 不合法,true 合法
     */
    private static boolean checkTableHead(Row row, DataFormatter cellDadaFormat) {

        if(null != row){

            String urlHead = getCellStringValue(row, cellDadaFormat, 0);
            String keywordHead = getCellStringValue(row, cellDadaFormat, 1);
            String creativeHead = getCellStringValue(row, cellDadaFormat, 2);

            return urlHead.equals(KEYWORD_TABLE_HEAD_URL) && keywordHead.equals(KEYWORD_TABLE_HEAD_KEYWORD) && creativeHead.equals(KEYWORD_TABLE_HEAD_CREATIVE);
        }

        return false;
    }

    /**
     * 获取KEY
     */
    private static String getKeywordKey(String keyword, String creative){
        return keyword + "-" + creative;
    }

    /**
     * 获取单元格字符串
     */
    private static String getCellStringValue(Row row, DataFormatter cellDadaFormat, int index) {

        String result = "";

        Cell cell = row.getCell(index);

        if (null != cell && !cell.getCellTypeEnum().equals(CellType.BLANK)) {

            result = cellDadaFormat.formatCellValue(cell);
        }

        return result;
    }

    /**
     * 检验和构建SubCampaign
     *
     */
    private static String checkAndBuildKeywordString(String url, String keyword, String creative) {

        String keywordString = null;

        //满足URL格式,keyword格式,creative格式
        if (!StringUtils.isEmpty(url) && StringUtil.urlMatch(url.trim())
                && !StringUtils.isEmpty(keyword) && keyword.length() <= MAX_KEYWORD_LENGTH && StringUtil.nameMatch(keyword.trim())
                && (StringUtils.isEmpty(creative) || creative.length() <= MAX_CREATIVE_LENGTH)) {

            keywordString = url + ";" + keyword.trim() + (StringUtils.isEmpty(creative) ? "" : ";" + creative.trim());
        }

        return keywordString;
    }


}
