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

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.stock.entity.SupplyMaterial;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.springframework.stereotype.Repository;

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

@Repository
public class SupplyMaterialDao extends BaseDao<SupplyMaterial> {

    public Record findById(String id) {
        return Db.findFirst("select * from crm_supply_material where id=? and status <> '2'", id);
    }

    public SupplyMaterial getById(String id) {
        return getByHql(" from SupplyMaterial where id=:p1 and status<> '2'", new Parameter(id));
    }

    public Record findByTypeAndName(String type ,String name){
        return Db.findFirst("select * from crm_supply_material where  status <> '2' and material_name = ? and material_specs = ?",type,name);
    }

    public List<Record> findMaterialList(LayuiPage<Record> page, Map<String,String> map){
        SqlBuilder sql = new SqlBuilder();

        sql.line(" SELECT m.*,t.name AS typeName");
        sql.line("FROM crm_supply_material m");
        sql.line("LEFT JOIN crm_supply_material_type t ON t.id=m.material_type_id");

        sql.line("WHERE m.status <>'2'");
        getMaterialQueryMap(sql,map);
        sql.line(" order by m.create_time desc , m.sort ASC ");
        if(page != null){
            sql.line(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
        }

        return Db.find(sql.build(),sql.params());
    }


    public long getMaterialCount(Map<String,String> map){
        SqlBuilder sql = new SqlBuilder();
        sql.line("select  count(*)  FROM crm_supply_material m ");
        sql.line("WHERE m.status <>'2' ");
        getMaterialQueryMap(sql,map);
        return Db.queryLong(sql.build(),sql.params());
    }

    public void getMaterialQueryMap(SqlBuilder builder, Map<String,String> map){

        if(StringUtil.checkParamsValid(map.get("code"))){
            builder.line(" and m.code like concat('%', ?, '%') ",map.get("code"));
        }
        if(StringUtil.checkParamsValid(map.get("materialTypeId"))){
            builder.line(" and m.material_type_id =? ",map.get("materialTypeId"));
        }
        if(StringUtil.checkParamsValid(map.get("materialName"))){
            builder.like(" and m.material_name like ? ",map.get("materialName"));
        }
        if(StringUtil.checkParamsValid(map.get("materialSpecs"))){
            builder.like(" and m.material_specs like ? ",map.get("materialSpecs"));
        }
        if(StringUtil.checkParamsValid(map.get("remarks"))){
            builder.line(" and m.remarks like concat('%', ?, '%') ",map.get("remarks"));
        }
        if(StringUtil.checkParamsValid(map.get("status"))){
            builder.line(" and m.status =? ",map.get("status"));
        }
         if(StringUtil.checkParamsValid(map.get("qqCode"))){
            builder.line(" and m.qq_code like concat('%', ?, '%')  ",map.get("qqCode"));
        }
      /*
        if(StringUtil.checkParamsValid(map.get("warehouseId"))){
            builder.line(" and m.warehouse_id =? ",map.get("warehouseId"));
        }
        if(StringUtil.checkParamsValid(map.get("storehouse"))){
            builder.line(" and m.storehouse like concat('%', ?, '%') ",map.get("storehouse"));
        }
        if(StringUtil.checkParamsValid(map.get("unitId"))){
            builder.line(" and m.unit_id =? ",map.get("unitId"));
        }

        if(StringUtil.checkParamsValid(map.get("supportApply"))){
            builder.line(" and m.support_apply =? ",map.get("supportApply"));
        }
        if (StringUtil.checkParamsValid(map.get("newUpdateTimeMin"))) {
            builder.line("and m.new_update_time >= concat(?, ' 00:00:00')", map.get("newUpdateTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("newUpdateTimeMax"))) {
            builder.line("and m.new_update_time <= concat(?, ' 23:59:59')", map.get("newUpdateTimeMax"));
        }*/

    }



    public boolean checkMaterial(String id,String code){
        SqlBuilder sql = new SqlBuilder();
        sql.line("SELECT COUNT(*) FROM crm_supply_material WHERE code=? AND status <>'2'",code);
        if(StringUtil.isNotBlank(id)){
            sql.line(" and id <> ?",id);
        }
        return Db.queryLong(sql.build(),sql.params())>0;
    }

    /**
     * 判断外部编码是否唯一
     * @param qqCode
     * @return
     */

    public boolean checkQqCode(String qqCode,String id){
        SqlBuilder sql = new SqlBuilder();
        sql.line("SELECT COUNT(*) FROM crm_supply_material WHERE qq_code=? AND status <>'2'",qqCode);
        if(StringUtil.isNotBlank(id)){
            sql.line(" and id <> ?",id);
        }
        return Db.queryLong(sql.build(),sql.params())>0;
    }






    /**
     * 查看是否有库存
    */
    public boolean checkMaterialAmount(String ids){

        return Db.queryLong("SELECT COUNT(*) FROM crm_supply_material_warehouse_stocks  WHERE material_id in("+StringUtil.joinInSql(ids.split(","))+") AND real_num>0")>0;
    }

    /**
     * 查看物料是否又在BOM中存在
     */
    public List<String> checkMaterialBom(String id){

        return Db.query(" SELECT materiel_bom_id FROM crm_supply_material_bom_detail  WHERE material_id =? AND STATUS='1' GROUP BY materiel_bom_id ",id);
    }

    public SupplyMaterial findByCode(String code) {
        return getByHql(" from SupplyMaterial where code=:p1 and status='1'", new Parameter(code));
    }

    public Record getMaterialByCode(String code){
        return Db.findFirst(" SELECT m.*,t.name AS materialTypeName FROM `crm_supply_material` m LEFT JOIN `crm_supply_material_type` t ON t.id=m.material_type_id WHERE m.code=? ",code);
    }

    public Record getMaterialByQqCode(String qqCode){
        return Db.findFirst(" SELECT m.*,t.name AS materialTypeName FROM `crm_supply_material` m LEFT JOIN `crm_supply_material_type` t ON t.id=m.material_type_id WHERE m.qq_code=? ",qqCode);
    }

    public String getNameByMaterialType(String materialTypeId){
        return Db.queryStr(" SELECT NAME FROM `crm_supply_material_type` WHERE id=? ",materialTypeId);
    }

    public long  checkSameTypeSpecMaterial(String materialTypeId,String spec,String materialModel,String id){
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT COUNT(m.id) ");
        sb.append("FROM `crm_supply_material` m ");
        sb.append("WHERE m.status='1' AND m.material_type_id=? AND m.material_specs=? and m.id<>? ");
        if (StringUtil.isNotBlank(materialModel)) {
            sb.append(" and m.material_model = '" + materialModel + "' ");
        }
        else {
            sb.append(" and m.material_model is null");
        }
        return Db.queryLong(sb.toString(),materialTypeId,spec,id);
    }

    public String  checkOnlyMaterial(String materialTypeId,String spec,String materialModel){
        return Db.queryStr(" SELECT m.id FROM `crm_supply_material` m WHERE m.status='1' AND m.material_type_id=? AND m.material_specs=? and m.material_model=?",materialTypeId,spec,materialModel);
    }

    public BigDecimal getMaxPriceBySpec(String materialTypeName,String materialSpec,String qqProjectCode){
       String sql=" SELECT IFNULL(MAX(p.price),0) AS customerPrice FROM `crm_supply_material` m " +
               "LEFT JOIN `crm_supply_material_type` t ON m.`material_type_id`=t.id " +
               "LEFT JOIN `crm_supply_material_project_price` p on p.qq_material_code = m.`qq_code`  " +
               "WHERE t.name=? AND m.material_specs=? AND m.status='1' AND p.status = '0' and  p.qq_project_code = ? ";
       return Db.queryBigDecimal(sql,materialTypeName,materialSpec,qqProjectCode);
    }

    public BigDecimal getMaxPriceBySpec2(String materialTypeId,String materialSpec,String qqProjectCode){
        String sql=" SELECT IFNULL(MAX(p.price),0) AS customerPrice FROM `crm_supply_material` m  ,crm_supply_material_project_price p " +
                "WHERE m.material_type_id=? AND m.material_specs=? AND m.status='1' AND m.qq_code = p.qq_material_code    AND p.status = '0' AND p.qq_project_code = ? ";
        return Db.queryBigDecimal(sql,materialTypeId,materialSpec,qqProjectCode);
    }


    //计算未扣减的预估授信额
    public BigDecimal getTotalAmountNotReduceAmount(String traderId,String orderId){
        String sql=" SELECT IFNULL(SUM(o.predict_amount),0) AS predictAmount FROM `crm_supply_material_deliver_order` o " +
                "WHERE o.trader_id=? AND o.type IN ('1','2') AND o.status IN ('1','2','3','4','5','9') ";
        if(com.sifang.modules.sys.common.utils.StringUtil.isNotBlank(orderId)){
            sql+=" and o.id <> '"+orderId+"' ";
        }
        return Db.queryBigDecimal(sql,traderId);
    }

    public BigDecimal fingMaterialPrice(String specs,String materialType){
        SqlBuilder sql = new SqlBuilder();
            sql.line("select bd_sale_price  from crm_supply_material_batch b")
                    .line("left join crm_supply_material m on m.id=b.material_id")
                    .line("where b.remaining>0 and b.belong_type='1'  and m.`status`='1'")
                    .line("and m.material_specs=? and m.material_type_id=?",specs,materialType);
        return Db.queryBigDecimal(sql.build(),sql.params());
    }

    /**
     * 根据规格查找品牌
     * @param spec
     * @param typeId
     * @return
     */
    public List<Record> findBrandBySpec(String spec,String typeId){
        SqlBuilder builder = new SqlBuilder();
        builder.line(" select material_brand,material_specs from crm_supply_material  ")
                .line("  where  status='1' and material_specs=? ",spec)
                .line(" and material_type_id = ? ",typeId)
                .line(" GROUP BY material_brand ");
        return Db.find(builder.build(),builder.params());
    }

    public List<Record> getMaterialCodeList(String materialCode){
        SqlBuilder builder = new SqlBuilder();
        builder.line(" select m.* , t.name AS materialType  ")
                .line(" from  crm_supply_material m ")
                .line(" LEFT JOIN crm_supply_material_type t ON t.id=m.material_type_id ")
                .like(" where  m.status='1'  and m.code like ? ",materialCode);
        return Db.find(builder.build(),builder.params());
    }

    public Record findMaterialByCode(String materialCode){
        SqlBuilder builder = new SqlBuilder();
        builder.line(" select m.* , t.name AS materialType  ")
                .line(" from  crm_supply_material m ")
                .line(" LEFT JOIN crm_supply_material_type t ON t.id=m.material_type_id ")
                .line(" where  m.status='1'  and m.code = ? ",materialCode);
        return Db.findFirst(builder.build(),builder.params());
    }

    // 根据物料规格、物料品牌 匹配组件物料 只用于广发存量电站的物料迁移
    public SupplyMaterial findSpecialZJBySpecBrand(String brand, String spec) {
        return getByHql(" from SupplyMaterial where materialBrand=:p1 and materialSpecs = :p2 and status='1' and code not like '%大E%' ",
                new Parameter(brand, spec));
    }
}
