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.CrmSupplyMaterialDeliverOrderDetail;
import com.sifang.modules.supply.order.request.AddSupplierOrderDetailReq;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hongzq
 */
@Repository
public class MaterialDeliverDetailDao extends BaseDao<CrmSupplyMaterialDeliverOrderDetail> {

    public List<AddSupplierOrderDetailReq> listDetails(String orderId) {
        List<CrmSupplyMaterialDeliverOrderDetail> details = listDetailByOrderId(orderId);
        List<AddSupplierOrderDetailReq> reqs = new ArrayList<>();
        for (CrmSupplyMaterialDeliverOrderDetail detail : details) {
            AddSupplierOrderDetailReq detailReq = new AddSupplierOrderDetailReq();
            detailReq.setMaterialId(detail.getMaterialId());
            detailReq.setAmount(detail.getApplyAmount());
            reqs.add(detailReq);
        }
        return reqs;
    }

    public List<CrmSupplyMaterialDeliverOrderDetail> listDetailByOrderId(String orderId){
        return find("from CrmSupplyMaterialDeliverOrderDetail where mainId=:p1 and status='0' order by sort", new Parameter(orderId));
    }

    public int deleteDetailByOrderId(String orderId){
        return update("delete from CrmSupplyMaterialDeliverOrderDetail where main_id=:p1", new Parameter(orderId));
    }

    public List<Record> findDetailsByOrderId(String orderId) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select d.*")
                .line(",ifnull(t.name,d.material_type) as materialTypeName, m.remarks, m.unit_name, m.code, m.material_name, m.material_brand ,m.min_apply_amount ")
                .line(" ,m.unit_code,o.receive_invoice,ROUND((d.apply_amount*d.purchase_price),2) as countPrice   ")
                .line("from crm_supply_material_deliver_order_detail d")
                .line("left join crm_supply_material_deliver_order o on d.main_id=o.id")
                .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("left join crm_supply_material_warehouse_stocks w on o.in_warehouse_id=w.warehouse_id and d.material_id=w.material_id")
                .line("where d.main_id=? and d.status='0' ", orderId)
                .line("order by d.sort");
        return Db.find(builder.build(), builder.params());
    }

    public List<Record> findDetailsByOrderIds(List<String> orderIds) {
        if (CollectionUtils.isEmpty(orderIds)) {
            return new ArrayList<>();
        }
        SqlBuilder builder = new SqlBuilder();
        builder.line("select d.*")
                .line(",t.name as materialTypeName,m.remarks, m.unit_name, m.code, w.position")
                .line("from crm_supply_material_deliver_order_detail d")
                .line("left join crm_supply_material_deliver_order o on d.main_id=o.id")
                .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("left join crm_supply_material_warehouse_stocks w on o.in_warehouse_id=w.warehouse_id and d.material_id=w.material_id")
                .inst("where d.main_id in ", orderIds)
                .line("order by d.sort");
        return Db.find(builder.build(), builder.params());
    }

    /**
     * 创建下单物料详情
     */
    public void createOne(String mainId, String materialId, String materialType, String materialSpec, BigDecimal applyAmount, Integer sort) {
        CrmSupplyMaterialDeliverOrderDetail deliverOrderDetail = new CrmSupplyMaterialDeliverOrderDetail();
        deliverOrderDetail.setMainId(mainId);
        deliverOrderDetail.setMaterialId(materialId);
        if ("1".equals(materialType)) {
            deliverOrderDetail.setMaterialType("逆变器");
        } else if ("2".equals(materialType)) {
            deliverOrderDetail.setMaterialType("并网箱");
        } else if("3".equals(materialType)){
            deliverOrderDetail.setMaterialType("组件");
        } else if("4".equals(materialType)){
            deliverOrderDetail.setMaterialType("支架");
        }
        deliverOrderDetail.setMaterialSpec(materialSpec);
        deliverOrderDetail.setApplyAmount(applyAmount);
        deliverOrderDetail.setOutAmount(BigDecimal.ZERO);
        deliverOrderDetail.setInAmount(BigDecimal.ZERO);
        deliverOrderDetail.setSort(sort);
        deliverOrderDetail.setStatus("0");
        save(deliverOrderDetail);
    }

    public BigDecimal findReturnNum(String orderId, String materialId) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT IFNULL(a.return_num,0)")
                .line("FROM crm_supply_material_return_order_detail a")
                .line("LEFT JOIN crm_supply_material_return_order b ON b.id = a.main_id")
                .line("WHERE b.status IN ('1','2','3') AND a.status = '0'")
                .line("AND a.material_id=?",materialId)
                .line("AND b.relation_id=?",orderId)
                .line("LIMIT 1");
        return Db.queryBigDecimal(builder.build(), builder.params());
    }
}
