package com.sifang.modules.account.handler;

import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.order.utils.excelExt.handler.ExcelAbstractHandler;
import com.sifang.modules.sys.util.CrmUtils;
import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CustomerEntryGeExcelImportHandler extends ExcelAbstractHandler {

    private List<CustomerEntry> retList = new ArrayList<>();

    private List<String> powerStationCodeList = new ArrayList<>();

    boolean checkFlag;

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


    /**
     * 如果返回false，则表示终止继续遍历Excel,截至到当前的行数
     */
    @SuppressWarnings("unchecked")
    @Override
    public Boolean handler(Map<String, Object> rowData, int rowIndex) {
        CustomerEntry addTrader = transToModel(rowData);
        retList.add(addTrader);
        return true;
    }

    private CustomerEntry transToModel(Map<String, Object> rowData) {
        CustomerEntry customerEntry = new CustomerEntry();
        customerEntry.setId(CrmUtils.getEntryIdByCode(formatCode(rowData.get("1"))));
        customerEntry.setEtd(new BigDecimal(rowData.get("2").toString()));
        customerEntry.setEto(new BigDecimal(rowData.get("3").toString()));
        customerEntry.setEtdc(new BigDecimal(rowData.get("4").toString()));
        customerEntry.setEtoc(new BigDecimal(rowData.get("5").toString()));
        return customerEntry;
    }

    //匹配模板
    private boolean matchTemplate(Map<String, Object> rowData) {
        List<String> titles = new ArrayList<>();
        titles.add("电站编码");
        titles.add("当期新增发电量");
        titles.add("累计发电量");
        titles.add("当期新增发电收入");
        titles.add("累计发电收入");
        return checkTemplate(titles, rowData);
    }

    public 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;
    }

    /**
     * 如果返回false，则表示终止继续遍历Excel,截至到当前的行数
     */
    //验证Excel模板
    @SuppressWarnings("unchecked")
    @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);
        }
        //如果是title列，则直接检查是否同一个Excel模板,包括顺序和列名匹配
        if (rowIndex == (getStartRow() - 1)) {
            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>");
                return true;
            } else if (!CrmUtils.checkEntryByCode(formatCode(rowData.get("1")))) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：电站不存在，请确认电站编码无误" + "</p>");
                return true;
            } else if (rowData.get("2") == null || StringUtils.isBlank(rowData.get("2").toString())) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：当期新增发电量为空" + "</p>");
                return true;
            } else if (!rowData.get("2").toString().matches("^\\d+(\\.\\d+)?$")) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：当期新增发电量格式不正确！" + "</p>");
                return true;
            } else if (rowData.get("3") == null || StringUtils.isBlank(rowData.get("3").toString())) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：累计发电量为空" + "</p>");
                return true;
            } else if (!rowData.get("3").toString().matches("^\\d+(\\.\\d+)?$")) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：累计发电量格式不正确！" + "</p>");
                return true;
            } else if (rowData.get("4") == null || StringUtils.isBlank(rowData.get("4").toString())) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：当期新增发电收入为空" + "</p>");
                return true;
            } else if (!rowData.get("4").toString().matches("^\\d+(\\.\\d+)?$")) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：当期新增发电收入格式不正确！" + "</p>");
                return true;
            } else if (rowData.get("5") == null || StringUtils.isBlank(rowData.get("5").toString())) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：累计发电收入为空" + "</p>");
                return true;
            } else if (!rowData.get("5").toString().matches("^\\d+(\\.\\d+)?$")) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：累计发电收入格式不正确！" + "</p>");
                return true;
            }

            if (powerStationCodeList.contains(formatCode(rowData.get("1")))) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据： 电站编码重复" + "</p>");
                return true;
            }
            powerStationCodeList.add(formatCode(rowData.get("1")));

            retList.add(transToModel(rowData));

            if (rowIndex > maxRows) {
                result.put("overLimit", "overLimit");
                return false;
            }
        }

        return true;
    }

    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);
    }

    private List<String> getNames(List<Record> records, String column) {
        List<String> names = new ArrayList<>();
        for (Record record : records) {
            names.add(record.getStr(column));
        }
        return names;
    }

    private boolean isLastRow(int rowIndex) {
        return rowIndex >= totalRow - 1;
    }

    public List<CustomerEntry> getRetList() {
        return retList;
    }

    public void setRetList(List<CustomerEntry> retList) {
        this.retList = retList;
    }

    public boolean isCheckFlag() {
        return checkFlag;
    }

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