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

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialReturnOrderDetail;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.util.SqlBuilder;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

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

@Repository
public class MaterialReturnOrderDetailDao extends BaseDao<CrmSupplyMaterialReturnOrderDetail> {



    public List<CrmSupplyMaterialReturnOrderDetail> getDetail(String returnId) {
        String sql = "from CrmSupplyMaterialReturnOrderDetail where mainId = :mainId and status ='0'";
        Query query = getSession().createQuery(sql);
        query.setParameter("mainId", returnId);

        List<CrmSupplyMaterialReturnOrderDetail> list = query.list();
        return list;
    }

    public List<Record> getAllDetail(String returnId) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select * from crm_supply_material_return_order_detail where main_id = ? and status ='0'",returnId);
        return Db.find(builder.build(),builder.params());
    }

    public BigDecimal getAllReturnNum(String relationNumber,String materialId) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT IFNULL(SUM(return_num),0) AS sumNum")
                .line("FROM crm_supply_material_return_order_detail od")
                .line("LEFT JOIN crm_supply_material_return_order o ON o.id = od.main_id AND o.status <> '4'")
                .line("WHERE o.relation_number = ? AND od.status = '0'", relationNumber)
                .line("AND od.material_id = ? ",materialId);
        return Db.queryBigDecimal(builder.build(),builder.params());
    }

    public void deleteAllDetail(String returnId) {
        Db.update("update crm_supply_material_return_order_detail set status = '1' where status = '0' and main_id = ?", returnId);
    }

}
