package com.sifang.modules.sunshine.SystemSetting.handler;

import com.google.common.collect.Maps;
import com.sifang.modules.order.utils.excelExt.handler.ExcelAbstractHandler;
import com.sifang.modules.sunshine.SystemSetting.form.AddSettlementScheme;
import com.sifang.modules.sys.common.utils.DateUtils;
import org.apache.commons.lang.StringUtils;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExcelImportSettleTheBasePriceHandler extends ExcelAbstractHandler {
    private ArrayList<AddSettlementScheme>  addSettlementSchemes = new ArrayList<>();

    private static String PATTERN =  "^\\d+(\\.\\d{1,2})?$";

    boolean checkFlag;
    private int maxRows=5000;   //导入的最大条数

    @Override
    public Boolean handler(Map<String, Object> rowData, int rowIndex) {
        AddSettlementScheme addSettlementScheme = transToModel(rowData);
        addSettlementSchemes.add(addSettlementScheme);
        return true;
    }

    private AddSettlementScheme transToModel(Map<String, Object> rowData) {
        AddSettlementScheme addSettlementScheme = new AddSettlementScheme();
        addSettlementScheme.setName(formatCode(rowData.get("1")));
        try {
            addSettlementScheme.setCreateTime(DateUtils.convertExcelDateDayToJavaDate(Double.parseDouble(String.valueOf(rowData.get("2")))));
            addSettlementScheme.setCancelTime(DateUtils.convertExcelDateDayToJavaDate(Double.parseDouble(String.valueOf(rowData.get("3")))));
        }catch (ParseException e) {
        }
        addSettlementScheme.setType(formatCode(rowData.get("4")));
        addSettlementScheme.setAmount(formatCodeDouble(rowData.get("5")));
        addSettlementScheme.setProjectIds(formatCode(rowData.get("6")));
        return addSettlementScheme;
    }

    @Override
    public Boolean checkExcel(Map<String, Object> rowData, int rowIndex) {
        Map<String, Object> result = (Map<String, Object>) this.getHandlerResult();
        if (result == null) {
            result = Maps.newHashMap();
            this.setHandlerResult(result);
        }
        // check excel title match
        if (rowIndex == (getStartRow() - 1)) {//如果是title列，则直接检查是否同一个Excel模板,包括顺序和列名匹配
            boolean match = matchTemplate(rowData);
            boolean flag = true;
            if(!match){
                result.put("TemplateError", "<p>模板不匹配</p>");
                flag = false;
            }
            return flag;
        }
        if (rowIndex > (getStartRow() -1)) {
            checkFlag = true;
            if (rowData.get("1")== null || StringUtils.isBlank(String.valueOf(rowData.get("1")))){
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：方案名称为空" + "</p>");
            }
            if (rowData.get("2")== null || StringUtils.isBlank(String.valueOf(rowData.get("2")))){
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：生效开始时间为空" + "</p>");
            }else {
                try {
                    Date date = null;
                    try {
                        double parseDouble = Double.parseDouble(String.valueOf(rowData.get("2")));
                        date = DateUtils.convertExcelDateDayToJavaDate(parseDouble);
                    }catch (Exception e){
                        date =  DateUtils.converExcelDate(String.valueOf(rowData.get("2")));
                    }
                     date = DateUtils.convertExcelDateDayToJavaDate(Double.parseDouble(String.valueOf(rowData.get("2"))));
                  /*  if (DateUtils.daysBetween(DateUtils.getDate(),DateUtils.formatDate(date,"yyyy-MM-dd"))<0){
                        appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：生效开始时间不能小于今天" + "</p>");
                    }*/
                } catch (Exception e) {
                    appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：生效开始时间格式不正确" + "</p>");
                }
            }
            if (rowData.get("3")== null || StringUtils.isBlank(String.valueOf(rowData.get("3")))){
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：生效结束时间为空" + "</p>");
            }else {
                try {
                    Date date = null;
                    try {
                        double parseDouble = Double.parseDouble(String.valueOf(rowData.get("3")));
                        date = DateUtils.convertExcelDateDayToJavaDate(parseDouble);
                    }catch (Exception e){
                        date =  DateUtils.converExcelDate(String.valueOf(rowData.get("3")));
                    }
                    /*if (DateUtils.daysBetween(DateUtils.getDate(),DateUtils.formatDate(date,"yyyy-MM-dd"))<0){
                        appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：生效结束时间不能小于今天" + "</p>");
                    }*/
                } catch (Exception e) {
                    appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：生效结束时间格式不正确" + "</p>");
                }
            }
            if (rowData.get("4")== null || StringUtils.isBlank(String.valueOf(rowData.get("4")))){
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：结算方式为空" + "</p>");
            }
            if (rowData.get("5")== null || StringUtils.isBlank(String.valueOf(rowData.get("5")))){
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：结算价（元）为空" + "</p>");
            }else {
                if(!isValidAmountFormat(String.valueOf(rowData.get("5")))){
                    appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：结算价（元）格式不正确" + "</p>");
                }else {
                    Double d = Double.parseDouble(formatCodeDouble(rowData.get("5")));
                    if (d<0){
                        appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：结算价（元）不能小于0" + "</p>");
                    }
                }
            }
            if (rowData.get("6")== null || StringUtils.isBlank(String.valueOf(rowData.get("6")))){
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：适用产品编号为空" + "</p>");
            }
            addSettlementSchemes.add(transToModel(rowData));
            if (rowIndex > maxRows) {
                result.put("overLimit", "overLimit");
                return false;
            }
        }
        return true;
    }

    private boolean matchTemplate(Map<String, Object> rowData) {
        List<String> titles = new ArrayList<>();
        titles.add("方案名称");
        titles.add("生效开始时间");
        titles.add("生效结束时间");
        titles.add("结算方式");
        titles.add("结算价（元）");
        titles.add("适用产品编号");
        return checkTemplate(titles, rowData);
    }

    private boolean checkTemplate(List<String> titles, Map<String, Object> rowData) {
        boolean ret = true;
        for (int i = 0; i < titles.size(); i++) {
            String title = String.valueOf(rowData.get(String.valueOf(i + 1)));
            if (!titles.get(i).equals(title.trim())) {
                //模板不匹配
                ret = false;
                break;
            }
        }
        return ret;
    }

    private String formatCode(Object code) {
        if (code == null) {
            return "";
        }
        Object codeVal = code;
        if (codeVal instanceof Double) {
            codeVal = new DecimalFormat("#").format((Double) codeVal);
        } else {
            codeVal = code;
        }
        return String.valueOf(codeVal.toString());
    }

    private String formatCodeDouble(Object code) {
        if (code == null) {
            return "";
        }
        Object codeVal = code;
        if (codeVal instanceof Double) {
            codeVal = new DecimalFormat("#.00").format((Double) codeVal);
        } else {
            codeVal = code;
        }
        return String.valueOf(codeVal.toString());
    }
    public boolean isValidAmountFormat(String amount) {
        Pattern r = Pattern.compile(PATTERN);
        Matcher m = r.matcher(amount);
        return m.matches();
    }
    public ArrayList<AddSettlementScheme> getAddSettlementSchemes() {
        return addSettlementSchemes;
    }

    public void setAddSettlementSchemes(ArrayList<AddSettlementScheme> addSettlementSchemes) {
        this.addSettlementSchemes = addSettlementSchemes;
    }
    public boolean isCheckFlag() {
        return checkFlag;
    }

    public void setCheckFlag(boolean checkFlag) {
        this.checkFlag = checkFlag;
    }

    @Override
    public int getMaxRows() {
        return maxRows;
    }

    @Override
    public void setMaxRows(int maxRows) {
        this.maxRows = maxRows;
    }

}
