package com.sifang.modules.supply.stock.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.kingdee.service.MateriService;
import com.sifang.modules.order.utils.excelExt.ExcelReader;
import com.sifang.modules.q7link.service.CrmSupplyMaterialProjectPriceService;
import com.sifang.modules.sunshine.SystemSetting.dao.ElectricSetDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmElectricSet;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.form.AddElectricMaterialSet;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
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.stock.handler.ExcelImportMaterialHandler;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.aliyuncs.utils.StringUtils.isNotEmpty;

@Service
public class SupplyMaterialService extends BaseService {

    @Autowired
    private SupplyMaterialDao materialDao;

    @Autowired
    private MateriService materiService;

    @Autowired
    private ElectricSetDao electricSetDao;

    @Autowired
    private TraderService traderService;

    @Autowired
    private CrmSupplyMaterialProjectPriceService projectPriceService;



    public SupplyMaterial getById(String id){
        return materialDao.get(id);
    }


    public LayuiPage<Record> findMaterialPage(LayuiPage<Record> page, Map<String, String> map) {
        List<Record> materialList = materialDao.findMaterialList(page, map);

        // 按照 create_time 倒序和 sort 进行比较
        Collections.sort(materialList, new Comparator<Record>() {
            @Override
            public int compare(Record record1, Record record2) {
                Date createTime1 = record1.getDate("create_time");
                Date createTime2 = record2.getDate("create_time");
                Integer sort1 = record1.getInt("sort");
                Integer sort2 = record2.getInt("sort");

                // 空指针检查
                if (createTime1 == null || createTime2 == null) {
                    return 0; // 可以根据实际情况返回默认值或者直接认为相等
                }

                // 先按照 create_time 倒序排序
                int compareCreateTime = createTime2.compareTo(createTime1);
                if (compareCreateTime != 0) {
                    return compareCreateTime; // 如果 create_time 不相同，直接返回比较结果
                } else {
                    // 如果 create_time 相同，则比较 sort 字段
                    // 空指针检查
                    if (sort1 == null || sort2 == null) {
                        return 0; // 可以根据实际情况返回默认值或者直接认为相等
                    }

                    return sort1.compareTo(sort2);
                }
            }
        });

        page.setData(materialList);
        page.setCount(materialDao.getMaterialCount(map));

        return page;
    }




    @Transactional(rollbackFor = Exception.class)
    public void saveOreditMaterial(SupplyMaterial material){
        try{
            int minApplyAmount = material.getMinApplyAmount();
            if(minApplyAmount <= 0){
                throw new BusinessException("物料最小数量单位为正整数");
            }
            if((minApplyAmount+"").matches("\\.")){
                throw new BusinessException("物料最小数量单位必须是纯数字");
            }

//            String id = checkOnlyMaterial(material.getMaterialTypeId(),material.getMaterialSpecs(),material.getMaterialModel());
//            if(StringUtil.isNotBlank(id)){
//                if(!id.equals(material.getId())){
//                    throw new BusinessException("物料类型、物料型号、物料规格不唯一");
//                }
//            }
            if(StringUtil.isNotBlank(material.getId())){
                SupplyMaterial supma = materialDao.get(material.getId());
                //修改
                //先判断之前的物料管理，有没有同物料类型和物料规格的物料了，如果没有了，那么可以删除
               /* String materialTypeName=getNameByMaterialType(material.getMaterialTypeId());*/

                String oldMateTypeName=supma.getMaterialTypeId().equals(material.getMaterialTypeId())?material.getMaterialTypeId():supma.getMaterialTypeId();
                CrmElectricSet electricSet=getMaterialSet(oldMateTypeName,supma.getMaterialSpecs(),supma.getMaterialModel());
                logger.info("electricSet:{}", new Gson().toJson(electricSet));
                if(electricSet!=null){
                    long count=checkSameTypeSpecMaterial(supma.getMaterialTypeId(),supma.getMaterialSpecs(),
                            supma.getMaterialModel(),supma.getId());
                    if(count<=0){
                        // 修改后的物料参数 已存在记录 则删除记录，不存在则修改
                        long e2 = checkMaterialSet(material.getMaterialTypeId(),material.getMaterialSpecs(),material.getMaterialModel());
                        if (e2 <=0) {
                            electricSet.setType(material.getMaterialTypeId());
                            electricSet.setModel(material.getMaterialSpecs());
                            electricSet.setMaterialModel(material.getMaterialModel());
                            electricSetDao.save(electricSet);
                        }
                        else {
                            electricSet.setStatus(SourceConstants.ONE);
                            electricSet.setUpdateBy(UserUtils.getUser().getId());
                            electricSet.setUpdateTime(new Date());
                            electricSetDao.save(electricSet);
                        }
                    }else{
                        CrmElectricSet set=getMaterialSet(material.getMaterialTypeId(),material.getMaterialSpecs(),material.getMaterialModel());
                        if(set==null){
                            electricSet=new CrmElectricSet();
                            setField(material.getMaterialSpecs(),material.getMaterialTypeId(),electricSet,material.getRemarks(),material.getMaterialModel());
                            electricSetDao.save(electricSet);
                        }
                    }
                }else{
                    CrmElectricSet set=getMaterialSet(material.getMaterialTypeId(),material.getMaterialSpecs(),material.getMaterialModel());
                    if(set==null){
                        electricSet=new CrmElectricSet();
                        setField(material.getMaterialSpecs(),material.getMaterialTypeId(),electricSet,material.getRemarks(),material.getMaterialModel());
                        electricSetDao.save(electricSet);
                    }
                }

                supma.setMaterialName(material.getMaterialName());
                supma.setMaterialTypeId(material.getMaterialTypeId());
                supma.setMaterialModel(material.getMaterialModel());
                //当类型为3（组件）时,修改组件玻型、电池参数数据
                if(material.getMaterialTypeId().equals("3")){
                    supma.setComponentShape(material.getComponentShape());
                    supma.setBatteryParam(material.getBatteryParam());
                }else{
                    supma.setComponentShape(SourceConstants.ZERO);
                    supma.setBatteryParam(SourceConstants.ZERO);
                }
                supma.setMaterialAttribute(material.getMaterialAttribute());
                supma.setMaterialSpecs(material.getMaterialSpecs());
                supma.setMaterialBrand(material.getMaterialBrand());
                supma.setMaterialBrandId(material.getMaterialBrandId());
                supma.setRemarks(material.getRemarks());
                supma.setUnitName(material.getUnitName());
                supma.setNewUpdateTime(new Date());
                supma.setUnitCode(material.getUnitCode());
                supma.setCustomerPrice(material.getCustomerPrice());
                supma.setMaterialProperties(material.getMaterialProperties());
                supma.setMinApplyAmount(minApplyAmount);
                //判断物料外部编码是否唯一
                if (materialDao.checkQqCode(material.getQqCode(),material.getId())){
                    throw new BusinessException("该物料外部编码已存在，不可重复添加");
                }
                supma.setQqCode(material.getQqCode());
                materialDao.save(supma);
                /*if(StringUtil.isNotBlank(supma.getKingDeeId())){
                    materiService.updateMateriToKingDee(supma);
                }*/
            }else{
                if(materialDao.checkMaterial(material.getId(),material.getCode())){
                    throw new BusinessException("该物料代码已存在，不可重复添加");
                }
                if (materialDao.checkQqCode(material.getQqCode(),null)){
                    throw new BusinessException("该物料外部编码已存在，不可重复添加");
                }

                User user = UserUtils.getUser();
                material.setCreateBy(user.getId());
                material.setNewUpdateTime(new Date());
               // String kingDeId=materiService.saveMateriToKingDee(material);
               // material.setKingDeeId(kingDeId);
                materialDao.save(material);
                /*String materialTypeName=getNameByMaterialType(material.getMaterialTypeId());*/
                //物料管理记录
                CrmElectricSet set=getMaterialSet(material.getMaterialTypeId(),material.getMaterialSpecs(),material.getMaterialModel());
                if(set==null){
                    CrmElectricSet electricSet=new CrmElectricSet();
                    setField(material.getMaterialSpecs(),material.getMaterialTypeId(),electricSet,material.getRemarks(),material.getMaterialModel());
                    electricSetDao.save(electricSet);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>>saveOreditMaterial e:{}",e);
            throw new BusinessException(e.getMessage()+"!");
        }
    }

    public CrmElectricSet setField(String spec,String type,CrmElectricSet electricSet,String remarks,String materialModel){
        electricSet.setType(type);
        electricSet.setModel(spec);
        electricSet.setStatus(SourceConstants.ZERO);
        electricSet.setCreateBy(UserUtils.getUser().getId());
        electricSet.setCreateTime(new Date());
        electricSet.setRemarks(remarks);
        electricSet.setMaterialModel(materialModel);
        return electricSet;
    }

    //获取物料名称
    public String getNameByMaterialType(String materialTypeId){
         String materialType= materialDao.getNameByMaterialType(materialTypeId);
         return materialType;
    }

    public String getTypeByTypeName(String materialType){
      /*  if("组件".equals(materialType)){
            materialType="3";
        }else if("逆变器".equals(materialType)){
            materialType="1";
        }else if("并网箱".equals(materialType)){
            materialType="2";
        }else if("支架".equals(materialType)){
            materialType="4";
        }*/
        return materialType;
    }

    //首先判断一下 物料管理记录里面有没有相同记录
    public CrmElectricSet getMaterialSet(String materialType, String spec, String materialModel){
        if("组件".equals(materialType)){
            materialType="3";
        }else if("逆变器".equals(materialType)){
           materialType="1";
        }else if("并网箱".equals(materialType)){
            materialType="2";
        }else if("支架".equals(materialType)){
            materialType="4";
        }
        CrmElectricSet set=electricSetDao.getMaterialSet(materialType,spec,materialModel);
        return set;
    }

    //首先判断一下 物料管理记录里面有没有相同记录
    public long checkMaterialSet(String materialType, String spec, String materialModel){
        if("组件".equals(materialType)){
            materialType="3";
        }else if("逆变器".equals(materialType)){
           materialType="1";
        }else if("并网箱".equals(materialType)){
            materialType="2";
        }else if("支架".equals(materialType)){
            materialType="4";
        }
        return electricSetDao.checkMaterialSet(materialType,spec,materialModel);
    }

    public long  checkSameTypeSpecMaterial(String materialTypeId,String spec,String materialModel,String id){
        Long count= materialDao.checkSameTypeSpecMaterial(materialTypeId,spec,materialModel,id);
        return count;
    }

    public String  checkOnlyMaterial(String materialTypeId,String spec,String materialModel){
        String id = materialDao.checkOnlyMaterial(materialTypeId,spec,materialModel);
        return id;
    }



    public Result disableMaterial(String id){
        SupplyMaterial material = materialDao.get(id);
        material.setStatus("3");
        material.setNewUpdateTime(new Date());
        materialDao.save(material);
       /* try {
            if(StringUtil.isNotBlank(material.getKingDeeId())){
                materiService.forbidMateriToKingDee(material);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>>disableMaterial e:{}",e);
            throw new BusinessException("推入金蝶系统错误,"+e.getMessage()+"!");
        }*/
        return Result.ok();
    }

    /**
     * 启用
    */
    public Result enableMaterial(String id){
        SupplyMaterial material = materialDao.get(id);
        if(!"3".equals(material.getStatus())){
            return Result.fail("2005","物料状态发生改变，启用失败");
        }
        material.setStatus("1");
        material.setNewUpdateTime(new Date());
        materialDao.save(material);
       /* try {
            if(StringUtil.isNotBlank(material.getKingDeeId())){
                materiService.enableMateriToKingDee(material);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>>enableMaterial e:{}",e);
            throw new BusinessException("推入金蝶系统错误,"+e.getMessage()+"!");
        }*/
        return Result.ok();
    }

    public Result deleteMaterial(String ids){
        if(materialDao.checkMaterialAmount(ids)){
            return Result.fail("2005","该物料有库存，不可删除");
        }
        SQLQuery sqlQuery = materialDao.getSession().createSQLQuery("update crm_supply_material a set a.status='2',a.new_update_time=NOW() where a.id in("+ StringUtil.joinInSql(ids.split(","))+ ")  ");
       int count = sqlQuery.executeUpdate();
       if(count<1){
           return Result.fail("2005","删除失败，状态发生改变");
       }
        return Result.ok();
    }


    /**
     * 校验导入物料数据
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> checkImportMaterial(Map<String, String> params, InputStream in) {
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "check");
        ExcelImportMaterialHandler handler=new ExcelImportMaterialHandler();
        handler.setStartSheet(1);
        handler.setStartRow(1);
        try {
            new ExcelReader().check(in, params.get("extName"), handler);
            Map<String, Object> map = (Map<String, Object>) handler.getHandlerResult();
            String templateError = (String) map.get("TemplateError");
            if(!handler.isCheckFlag()){
                handler.appendErrorDetail("<p>未填充数据</p>");
            }

            List<String> codeslist = MaterialUtils.findMaterialCode();
            //获取所有物料类型
            List<String> types = MaterialUtils.findMaterialTypeName();
            //获取所有品牌类型
            List<String> brands=MaterialUtils.getMaterialBrand();

            //获取所有外部编码
            List<String> qqCode = MaterialUtils.findQqCode();


            //获取所有物料库存单位
            List<String> units = MaterialUtils.findMaterialUnitName();

            //获取物料管理库中所有类型、型号、规格拼接的字符串
            List<String> tmmlist = MaterialUtils.findMaterialModel();
            //过滤null
            tmmlist.stream().filter(s -> s != null).collect(Collectors.toList());
            List<AddMaterial> list =handler.getRetList();
            int i =1;
            String jy = "";
            String materialType = "";
            for(AddMaterial s :list){
                if("组件".equals(s.getMaterialType())){
                    materialType="3";
                    if(s.getBatteryParam() == null||s.getBatteryParam() == "null"||s.getBatteryParam() == ""){
                        handler.appendErrorDetail("第" + (i + 1) + "当物料类型为组件时，电池参数不能为空");
                    }else if(s.getComponentShape() == null||s.getComponentShape() == "null"||s.getComponentShape() == ""){
                        handler.appendErrorDetail("第" + (i + 1) + "当物料类型为组件时，组件玻型不能为空");
                    }
                }else if("逆变器".equals(s.getMaterialType())){
                    materialType="1";
                }else if("并网箱".equals(s.getMaterialType())){
                    materialType="2";
                }else if("支架".equals(s.getMaterialType())){
                    materialType="4";
                }
                jy = materialType+""+s.getMaterialSpecs()+""+s.getMaterialModel();
                if(tmmlist.contains(jy)){
                    handler.appendErrorDetail("第" + (i + 1) + "类型、型号、规格不唯一");
                }
                if (codeslist.contains(s.getCode())) {
                    handler.appendErrorDetail("第" + (i + 1) + "行物料代码已存在");
                }
                if (!types.contains(s.getMaterialType())) {
                    handler.appendErrorDetail("第" + (i + 1) + "行物料类型不存在");
                }
                if (qqCode.contains(s.getQqCode())){
                    handler.appendErrorDetail("第" + (i + 1) + "行外部编码已存在");
                }
                if(!brands.contains(s.getMaterialBrand())){
                    handler.appendErrorDetail("第" + (i + 1) + "行物料品牌不存在!");
                }
                if(StringUtil.isBlank(s.getUnitName().toString())){
                    handler.appendErrorDetail("第" + (i + 1) + "行物料库存单位不存在!");
                }
                i++;
            }

            String hanl = handler.getErrorDetail();
            if (StrKit.notBlank(templateError)){
                retMap.put("errorDetail", templateError);
                retMap.put("errorMessage", "y");
            }else if (StringUtils.isNotBlank(hanl)) {
                retMap.put("errorDetail", hanl);
                retMap.put("errorMessage", "y");
            } else if ("overLimit".equalsIgnoreCase((String) map.get("overLimit"))) {
                retMap.put("overLimit", "y");
            } else {
                retMap.put("pass", "y");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return retMap;
    }

    // 判断是否是科学计数法
    private static boolean isScientificNotation(String input) {
        return input.matches("[+-]?\\d+(\\.\\d+)?[eE][+-]?\\d+");
    }



    /**
     * 导入物料数据
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importMaterial(Map<String, String> params, InputStream in) {
        Map<String, Object> retMap = Maps.newHashMap();
        int i = 1;
        retMap.put("operType", "import");
        ExcelImportMaterialHandler handler=new ExcelImportMaterialHandler();
        handler.setStartSheet(1);
        handler.setStartRow(2);
        User user = UserUtils.getUser();

        try {
            new ExcelReader().readExcel(in, params.get("fileName"), handler);

            //获取所有物料类型
            List<Record> types = MaterialUtils.findMaterialType();
            //获取所有物料库存单位
            List<Record> units = MaterialUtils.findMaterialUnit();
            //获取所有物料品牌
            List<Record> brands=MaterialUtils.findMaterialBrand();

            Map<String,Record> maptype = Maps.newHashMap();
            for(Record rd :types){
                maptype.put(rd.getStr("name"),rd);
            }

            Map<String,String> brandMap=Maps.newHashMap();
            for(Record r:brands){
                brandMap.put(r.getStr("name"), r.getStr("id"));
            }


            Map<String,String> unitMap=Maps.newHashMap();
            for(Record r:units){
                unitMap.put(r.getStr("name"), r.getStr("unit_code"));
            }


            List<AddMaterial> list =handler.getRetList();
            List<SupplyMaterial> maters = Lists.newArrayList();
//            List<Map<String,Object>> listMap = Lists.newArrayList();
            List<CrmElectricSet> electricSets=new ArrayList<>();
            List<String> checkInfo = new ArrayList<>();
            for(AddMaterial s :list){
                SupplyMaterial app   = new SupplyMaterial();
                app.setStatus("1");
                //判断物料编码是否是科学计数法
                String code = s.getCode();
                if(isNotEmpty(code) && isScientificNotation(code)){
                    BigDecimal bd = new BigDecimal(code);
                    code = bd.toString();
                }
                app.setCode(code);
                //判断物料名称是否是科学记数法
                String materialName = s.getMaterialName();
                if(isNotEmpty(materialName) && isScientificNotation(materialName)){
                    BigDecimal bd = new BigDecimal(materialName);
                    materialName = bd.toString();
                }
                app.setMaterialName(materialName);

                Record rd=maptype.get(s.getMaterialType().trim());
                app.setMaterialTypeId(rd.getStr("id"));
                app.setMaterialAttribute(rd.getStr("attribute"));
                app.setMaterialSpecs(s.getMaterialSpecs());
                app.setMaterialBrand(s.getMaterialBrand());
                app.setMaterialModel(s.getMaterialModel());
                if(s.getComponentShape().equals("单玻")){
                    app.setComponentShape("1");
                }else if(s.getComponentShape().equals("双玻")){
                    app.setComponentShape("2");
                }else{
                    app.setComponentShape("0");
                }
                if(s.getBatteryParam().equals("N型")){
                    app.setBatteryParam("1");
                }else if(s.getBatteryParam().equals("P型")){
                    app.setBatteryParam("2");
                }else{
                    app.setBatteryParam("0");
                }
                String brandId=brandMap.get(s.getMaterialBrand().trim());
                app.setMaterialBrandId(brandId);
                app.setRemarks(s.getRemarks());
                app.setUnitName(s.getUnitName());
                app.setUnitCode(unitMap.get(s.getUnitName().trim()));
                app.setUnitName(s.getUnitName());
                app.setCreateBy(user.getId());
                app.setCreateTime(new Date());
                //判断外部编码是否是科学计数法
                String qqCode = s.getQqCode();
                if(isNotEmpty(qqCode) && isScientificNotation(qqCode)){
                    BigDecimal bd = new BigDecimal(qqCode);
                    qqCode = bd.toString();
                }
                app.setQqCode(qqCode);

                app.setNewUpdateTime(new Date());
                app.setMaterialProperties("1");
                app.setSort(i++);
                app.setCustomerPrice(s.getCustomerPrice());
                app.setMinApplyAmount(1);
               // String kingDeId=materiService.saveMateriToKingDee(app);
               // app.setKingDeeId(kingDeId);
                maters.add(app);
                /*Map<String,Object> model = materiService.doMateriData(app);
                listMap.add(model);*/
                //物料管理记录

                if(StringUtil.equalsAny(s.getMaterialType().trim(),"组件","逆变器","并网箱","支架")){
                    CrmElectricSet set=getMaterialSet(s.getMaterialType().trim(),app.getMaterialSpecs(),app.getMaterialModel());
                    String str = s.getMaterialType()+""+app.getMaterialSpecs()+""+app.getMaterialModel();
                   if (!checkInfo.contains(str)){
                       if(set==null){
                           checkInfo.add(s.getMaterialType()+""+app.getMaterialSpecs()+""+app.getMaterialModel());
                           CrmElectricSet electricSet=new CrmElectricSet();
                           setField(app.getMaterialSpecs(),app.getMaterialTypeId().trim(),electricSet,"",app.getMaterialModel());
                           electricSets.add(electricSet);
                       }
                   }
                }
            }
            materialDao.save(maters);
            if(electricSets.size()>0){
                electricSetDao.save(electricSets);
            }

            retMap.put("successCount", maters.size());
            retMap.put("pass", "y");
            retMap.put("materialList", handler.getRetList());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(" 导入物料异常,e:{}",e);
            throw new BusinessException(e.getMessage());
        } finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return retMap;
    }


    public List<Record> findMaterialByCode(String code,String remarks,String materialProperties,String supplierId){
        SqlBuilder builder = new SqlBuilder();
        builder.line("select m.id, m.code,m.unit_name,m.material_type_id, t.name as material_type, m.remarks,m.material_name,m.material_brand,m.material_specs,a.coefficient ")
                .line("from crm_supply_material m ")
                .line("left join crm_supply_material_type t on m.material_type_id=t.id")
                .line("left join crm_price_coefficient_apply a on a.material_type_id=m.material_type_id AND a.status='3'")
                .line("where m.status='1' ");
        if (StringUtil.checkParamsValid(code)) {
            builder.like("and m.code like ?", code);
        }
        if (StringUtil.checkParamsValid(remarks)) {
            builder.like("and m.remarks like ? ", remarks);
        }
        /*if (StringUtil.checkParamsValid(materialProperties)) {
            builder.line("and m.material_properties = ?",materialProperties);
        }*/
        if (StringUtil.isNotBlank(supplierId)) {
            String brandName = MaterialUtils.findSupplierBrandById(supplierId);
            if (StringUtil.isNotBlank(brandName)) {
                builder.line("and m.material_brand = ?",brandName);
            }
        }
        return Db.find(builder.build(),builder.params());
    }

}
