package com.sifang.modules.sunshine.handler;
import com.google.common.collect.Maps;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.order.utils.excelExt.handler.ExcelAbstractHandler;
import com.sifang.modules.supply.setting.dao.CrmSupplyMaterialTypeDao;
import com.sifang.modules.supply.stock.dao.SupplyMaterialDao;
import com.sifang.modules.supply.stock.entity.SupplyMaterial;
import com.sifang.modules.supply.warehouse.vo.ImportMaterialInfo;
import com.sifang.modules.sys.util.SpringUtils;
import org.apache.commons.lang.StringUtils;

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

public class InventutyExcelImportHandler extends ExcelAbstractHandler {


    private List<Map<String, Object>> errorRowData = new ArrayList<>();
    public List<Map<String, Object>> getErrorRowData() {
        return errorRowData;
    }
    private List<ImportMaterialInfo> retList = new ArrayList<>();
    private List<String> materialCodeList = new ArrayList<>();
    boolean checkFlag;
    private int maxRows=500;   //导入的最大条数

    @SuppressWarnings("unchecked")
    @Override
    public Boolean handler(Map<String, Object> rowData, int rowIndex) {
        SupplyMaterialDao materialDao = SpringUtils.getBean(SupplyMaterialDao.class);
        Record material = materialDao.getMaterialByQqCode(String.valueOf(rowData.get("1")));
        BigDecimal amount = new BigDecimal(String.valueOf(rowData.get("5")));
        ImportMaterialInfo info = transToModel(material, amount);
        retList.add(info);
        return true;
    }

    @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);
        }
        // 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>");
                return true;
            }
            if (materialCodeList.contains(String.valueOf(rowData.get("1")))) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：外部代码重复" + "</p>");
                return true;
            }
            SupplyMaterialDao materialDao = SpringUtils.getBean(SupplyMaterialDao.class);
            Record material = materialDao.getMaterialByQqCode(String.valueOf(rowData.get("1")));
            if (!StrKit.notNull(material)) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：外部代码不存在" + "</p>");
                return true;
            }
            materialCodeList.add(String.valueOf(rowData.get("1")));

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

            try {
                double num = Double.parseDouble(String.valueOf(rowData.get("5")));
            }catch (Exception e){
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：数量格式不正确" + "</p>");
                return true;
            }

            retList.add(transToModel(material, new BigDecimal(String.valueOf(rowData.get("5")).trim())));
            if (rowIndex > maxRows) {
                result.put("overLimit", "overLimit");
                return false;
            }
        }

        return true;
    }

    private ImportMaterialInfo transToModel(Record material, BigDecimal amount) {
      //  CrmSupplyMaterialTypeDao materialTypeDao = SpringUtils.getBean(CrmSupplyMaterialTypeDao.class);
        ImportMaterialInfo info = new ImportMaterialInfo();
        info.setCode(material.getStr("code"));
        info.setMaterialId(material.getStr("id"));
        info.setAmount(amount);
        info.setType(material.getStr("materialTypeName"));
        info.setUnit(material.getStr("unit_name"));
        info.setDescription(StringUtils.isBlank(material.getStr("remarks")) ? "" :material.getStr("remarks"));
        info.setMaterialAttribute(material.getStr("material_attribute"));
        info.setName(material.getStr("material_name"));
        info.setMaterialBrand(material.getStr("material_brand"));
        info.setMaterialSpecs(material.getStr("material_specs"));
        return info;
    }

    //匹配模板
    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("物料描述");
        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;
    }

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

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

    public boolean isCheckFlag() {
        return checkFlag;
    }

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

}
