package com.sifang.modules.supply.handler;

import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.order.utils.excelExt.handler.ExcelAbstractHandler;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyBarcode;
import com.sifang.modules.supply.warehouse.service.CrmSupplyBarcodeService;
import com.sifang.modules.sys.util.SpringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;

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

public class BarcodeExcelImportHandler extends ExcelAbstractHandler {

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

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

    boolean checkFlag;

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


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

    private CrmSupplyBarcode transToModel(Map<String, Object> rowData){
        CrmSupplyBarcode material = new CrmSupplyBarcode();
        material.setMaterialId(MaterialUtils.findQqCodeByCode(formatCode(rowData.get("1"))));
        material.setMaterialBarcode(formatCode(rowData.get("8")));
        material.setBatchCode(formatCode(rowData.get("9")));
        material.setBatchCodeNote(formatCode(rowData.get("10")));
        return material;
    }

    //匹配模板
    private boolean matchTemplate(Map<String, Object> rowData){
        List<String> titles = new ArrayList<>();
        titles.add("外部条码");
        titles.add("物料名称");
        titles.add("物料类型");
        titles.add("物料规格");
        titles.add("物料描述");
        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 {
                String materialId = MaterialUtils.findQqCodeByCode(formatCode(rowData.get("1")));
                if (StringUtils.isBlank(materialId)) {
                    appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：物料不存在，请先维护该物料" + "</p>");
                    return true;
                }
            }

            if (rowData.get("8") == null || StringUtils.isBlank(String.valueOf(rowData.get("8")))) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：物料条码为空" + "</p>");
                return true;
            }

            if (materialCodeList.contains(formatCode(rowData.get("8")))) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据： 物料条码重复" + "</p>");
                return true;
            }
            materialCodeList.add(formatCode(rowData.get("8")));


            retList.add(transToModel(rowData));
          /*  if (isLastRow(rowIndex)) {
                checkMaterialCodeExists(retList);
            }*/
            if (rowIndex > maxRows) {
                result.put("overLimit", "overLimit");
                return false;
            }
        }

        return true;
    }

    private void checkMaterialCodeExists(List<CrmSupplyBarcode> materials){
        CrmSupplyBarcodeService barcodeService = SpringUtils.getBean(CrmSupplyBarcodeService.class);
        if (CollectionUtils.isEmpty(materials)) {
            return;
        }
        List<String> codeList = new ArrayList<>();
        for (CrmSupplyBarcode con : materials) {
            codeList.add(con.getMaterialBarcode().trim());
        }
        List<String> existsCode = barcodeService.findExistsCode("");
        for (int i = 0; i < codeList.size(); i++) {
            if (existsCode.contains(codeList.get(i))) {
                appendErrorDetail("第" + (i + 1) + "行物料条码已存在</p>");
            }
        }
    }

    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<CrmSupplyBarcode> getRetList() {
        return retList;
    }

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

    public boolean isCheckFlag() {
        return checkFlag;
    }

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