package com.sifang.modules.supply.stock.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.sunshine.SystemSetting.service.PlanService;
import com.sifang.modules.supply.stock.constant.MaterialConstants;
import com.sifang.modules.supply.stock.dao.SupplyMaterialDao;
import com.sifang.modules.supply.stock.entity.SupplyMaterial;
import com.sifang.modules.supply.stock.form.AddMaterial;
import com.sifang.modules.supply.warehouse.vo.PurchaseImportMaterialVo;
import com.sifang.modules.sys.util.SpringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;

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

public class ExcelPurchaseImportMaterialHandler extends ExcelAbstractHandler {

    private List<Map<String,Object>> errorRowData=new ArrayList<>();
    public List<Map<String, Object>> getErrorRowData() {
        return errorRowData;
    }

    private List<PurchaseImportMaterialVo> 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) {
        SupplyMaterialDao materialDao = SpringUtils.getBean(SupplyMaterialDao.class);
        Record material = materialDao.getMaterialByCode(String.valueOf(rowData.get("1")));
        PurchaseImportMaterialVo vo=transToModel(material,rowData);
        retList.add(vo);
        return true;
    }

    private PurchaseImportMaterialVo transToModel(Record material,Map<String, Object> rowData){
        PurchaseImportMaterialVo vo = new PurchaseImportMaterialVo();
        vo.setMaterialId(material.getStr("id"));
        vo.setCode(String.valueOf(rowData.get("1")));
        vo.setMaterialName(material.getStr("material_name"));
        if (rowData.get("3") == null) {
            vo.setMaterialType(material.getStr("materialTypeName"));
        } else {
            vo.setMaterialType(String.valueOf(rowData.get("3")));
        }
        vo.setMaterialBrand(material.getStr("material_brand"));
        if(rowData.get("5") != null && StringUtils.isNotBlank(String.valueOf(rowData.get("5")))){
            try {
                BigDecimal amount= new BigDecimal(String.valueOf(rowData.get("5")).trim());
                vo.setApplyAmount(amount);
            }catch (Exception e){
            }
        }
        if(rowData.get("6") != null && StringUtils.isNotBlank(String.valueOf(rowData.get("6")))){
            try {
                BigDecimal price=new BigDecimal(String.valueOf(rowData.get("6")).trim());
                vo.setPurchasePrice(price);
            }catch (Exception e){

            }
        }
        if(rowData.get("4")==null){
            vo.setMaterialSpec(material.getStr("material_specs"));
        }else {
            vo.setMaterialSpec(String.valueOf(rowData.get("4")));
        }
        vo.setMaterialTypeId(material.getStr("material_type_id"));
        return vo;
    }

    //匹配模板
    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);
    }

    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().replace("*",""))) {
                //模板不匹配
                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);
        }
        // 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 (materialCodeList.contains(String.valueOf(rowData.get("1")))) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：物料代码重复" + "</p>");
            }
            materialCodeList.add(String.valueOf(rowData.get("1")));

            SupplyMaterialDao materialDao = SpringUtils.getBean(SupplyMaterialDao.class);
            Record material = materialDao.getMaterialByCode(String.valueOf(rowData.get("1")));
            if (!StrKit.notNull(material)) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：物料代码不存在" + "</p>");
                return true;
            }
            if (rowData.get("5") == null || StringUtils.isBlank(String.valueOf(rowData.get("5")))) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：采购数量为空" + "</p>");
            }else{
                try {
                    new BigDecimal(String.valueOf(rowData.get("5")).trim());
                }catch (Exception e){
                    appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：采购数量格式不正确" + "</p>");
                }
            }
           /* if(!MaterialConstants.PROPERTIES_OUT.equals(material.getMaterialProperties())){   //物料对应金蝶的属性不是外购，那么该物料不能采购
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：该物料属性非外购物料，不能采购 " + "</p>");
            }*/

            if (rowData.get("6") == null || StringUtils.isBlank(String.valueOf(rowData.get("6")))) {
                appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：采购单价为空" + "</p>");
            }else {
                try {
                    new BigDecimal(String.valueOf(rowData.get("6")).trim());
                }catch (Exception e){
                    appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：采购单价格式不正确" + "</p>");
                }
            }
            retList.add(transToModel(material,rowData));

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

        return true;
    }

    private void checkMaterialCodeExists(List<AddMaterial> materials){
        PlanService planService = SpringUtils.getBean(PlanService.class);
        if (CollectionUtils.isEmpty(materials)) {
            return;
        }
        List<String> codeList = new ArrayList<>();
        for (AddMaterial material : materials) {
            codeList.add(material.getCode());
        }
        List<String> existsCode = planService.findExistsCode(codeList, "");
        for (int i = 0; i < codeList.size(); i++) {
            if (existsCode.contains(codeList.get(i))) {
                appendErrorDetail("第" + (i + 1) + "行料号已存在");
            }
        }
    }

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

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

    public boolean isCheckFlag() {
        return checkFlag;
    }

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