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.CrmSupplyMaterialApplyDetail;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.util.SqlBuilder;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hongzq
 */
@Repository
public class MaterialApplyDetailDao extends BaseDao<CrmSupplyMaterialApplyDetail> {

    public List<CrmSupplyMaterialApplyDetail> findByApplyId(String appId) {
        return find("from CrmSupplyMaterialApplyDetail where applyId=:p1 order by sort", new Parameter(appId));
    }

    public List<Record> listByApplyId(String id) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select d.id, d.apply_id, d.material_id, d.apply_amount")
                .line(", t.name as materialTypeName,  m.remarks, m.unit_name, m.code")
                .line("from crm_supply_material_apply_detail d")
                .line("left join crm_supply_material m on d.material_id=m.id")
                .line("left join crm_supply_material_type t on m.material_type_id=t.id")

                .line("where d.apply_id=?", id)
                .line("order by d.sort");
        return Db.find(builder.build(), builder.params());
    }

    public List<Record> listByApplyIds(List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        SqlBuilder builder = new SqlBuilder();
        builder.line("select d.id, d.apply_id, d.material_id, d.apply_amount")
                .line(", t.name as materialTypeName,  m.remarks, m.unit_name, m.code")
                .line("from crm_supply_material_apply_detail d")
                .line("left join crm_supply_material m on d.material_id=m.id")
                .line("left join crm_supply_material_type t on m.material_type_id=t.id")

                .inst("where d.apply_id in ", ids)
                .line("order by d.sort");
        return Db.find(builder.build(), builder.params());
    }

    public void deleteByApplyId(String applyId) {
        update("delete from CrmSupplyMaterialApplyDetail where applyId=:p1", new Parameter(applyId));
    }

}
