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

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrder;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrderDetail;
import com.sifang.modules.supply.setting.entity.CrmSupplyWarehouse;
import com.sifang.modules.supply.stock.entity.MaterialWarehouseStocks;
import com.sifang.modules.supply.stock.entity.SupplyMaterial;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyMaterialKeep;
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.SqlBuilder;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;

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

@Repository
public class CrmSupplyMaterialKeepDao extends BaseDao<CrmSupplyMaterialKeep> {

    /**
     * 生成出入库记录
     */
    public String createOne(CrmSupplyMaterialDeliverOrder order, String belongingType, SupplyMaterial material,
                            String materialType, String type, CrmSupplyMaterialDeliverOrderDetail detail, BigDecimal warining, CrmSupplyWarehouse warehouse, Date now,
                            String createBy, String creator, String source,String batchCode) {
        CrmSupplyMaterialKeep keep = new CrmSupplyMaterialKeep();
        keep.setId(IdGen.uuid());
        // 数据类型
        keep.setBelongingType(belongingType);
        // 物料信息
        keep.setMaterialId(material.getId());
        keep.setMaterialCode(material.getCode());
        keep.setMaterialUnit(material.getUnitName());
        keep.setMaterialRemarks(material.getRemarks());
        keep.setMaterialType(materialType);
        keep.setType(type);
        keep.setAmount(detail.getInAmount());
        keep.setCurBgNum(warining);
        keep.setBdSalePrice(detail.getSalesPrice());//销售价
        keep.setCostPrice(detail.getPurchasePrice());//成本价
        // 仓库信息
        keep.setWarehouseId(warehouse.getId());
        keep.setWarehouseName(warehouse.getName());
        keep.setAscriptionName(warehouse.getAscriptionName());
        keep.setAscriptionId(warehouse.getAscriptionId());
        // 其它信息
        keep.setCreateTime(now);
        keep.setCreateBy(createBy);
        keep.setCreator(creator);
        keep.setSourceCode(order.getNumber());
        keep.setSourceId(order.getId());
        keep.setSource(source);
        keep.setRemarks(order.getRemarks());
        keep.setDeliveryMethod(order.getDeliverMethodName());
        keep.setProjectCode(order.getProjectCode());
        keep.setBatchCode(batchCode);
        save(keep);
        return keep.getId();
    }

    /**
     * 查找 累计已发电 累计已投放 物料数量 用于代理商库存管理页面数量统计
     */
    public Record findMaterialCount(String materialId,String warehouseId){
        SqlBuilder builder = new SqlBuilder();
        builder.line("  select IFNULL(sum(case when e.first_generation_time is not null then k.amount else 0 end ),0) as  yfdTotalCapacity , ")
                .line(" IFNULL(sum(case when a.payment_finish_time is not null then k.amount else 0 end ),0) as  ytfTotalCapacity , ")
                .line(" IFNULL(sum(case when e.material_fix_flag = '1' then k.amount else 0 end ),0) as  yazTotalCapacity")
                .line(" from  crm_supply_material_keep k  ")
                .line(" left join crm_customer_entry e on e.id = k.source_id ")
                .line(" left join crm_customer_incoming_application a on a.entry_id = e.id and a.if_delete = '0' ")
                .line(" where k.type = '2' and k.material_id = ? and k.warehouse_id = ? ",materialId,warehouseId);
        return Db.findFirst(builder.build(),builder.params());
    }

    public List<CrmSupplyMaterialKeep> getListByEntryId(String entryId) {
        Query query = getSession().createQuery("from CrmSupplyMaterialKeep where sourceId = :id and source= '5' ");
        query.setParameter("id", entryId);
        return query.list();
    }

    // 删除记录
    public boolean deleteKeep(CrmSupplyMaterialKeep keep){
        StringBuilder sql = new StringBuilder();
        sql.append(" INSERT INTO crm_supply_material_keep_del (id,belonging_type,material_id,material_remarks,material_type, ")
                .append("material_unit,material_code,type,amount,cur_bg_num,warehouse_id,warehouse_name,ascription_id,ascription_name,")
                .append("create_by,creator,create_time,source,source_id,source_code,remarks,delivery_method,project_code,cost_price,")
                .append("bd_sale_price,batch_code,batch_id,batch_remaining,account_flag,delet_time)")
                .append(" VALUES(:id,:belonging_type,:material_id,:material_remarks,:material_type,:material_unit,")
                .append(":material_code,:type,:amount,:cur_bg_num,:warehouse_id,:warehouse_name,:ascription_id,:ascription_name,")
                .append(":create_by,:creator,:create_time,:source,:source_id,:source_code,:remarks,:delivery_method,")
                .append(":project_code,:cost_price,:bd_sale_price,:batch_code,:batch_id,:batch_remaining,:account_flag, NOW())");
        Query query = getSession().createSQLQuery(sql.toString());
        query.setParameter("id", keep.getId());
        query.setParameter("belonging_type", keep.getBelongingType());
        query.setParameter("material_id", keep.getMaterialId());
        query.setParameter("material_remarks", keep.getMaterialRemarks());
        query.setParameter("material_type", keep.getMaterialType());
        query.setParameter("material_unit", keep.getMaterialUnit());
        query.setParameter("material_code", keep.getMaterialCode());
        query.setParameter("type", keep.getType());
        query.setParameter("amount", keep.getAmount());
        query.setParameter("cur_bg_num", keep.getCurBgNum());
        query.setParameter("warehouse_id", keep.getWarehouseId());
        query.setParameter("warehouse_name", keep.getWarehouseName());
        query.setParameter("ascription_id", keep.getAscriptionId());
        query.setParameter("ascription_name", keep.getAscriptionName());
        query.setParameter("create_by", keep.getCreateBy());
        query.setParameter("creator", keep.getCreator());
        query.setParameter("create_time", keep.getCreateTime());
        query.setParameter("source", keep.getSource());
        query.setParameter("source_id", keep.getSourceId());
        query.setParameter("source_code", keep.getSourceCode());
        query.setParameter("remarks", keep.getRemarks());
        query.setParameter("delivery_method", keep.getDeliveryMethod());
        query.setParameter("project_code", keep.getProjectCode());
        query.setParameter("cost_price", keep.getCostPrice());
        query.setParameter("bd_sale_price", keep.getBdSalePrice());
        query.setParameter("batch_code", keep.getBatchCode());
        query.setParameter("batch_id", keep.getBatchId());
        query.setParameter("batch_remaining", keep.getBatchRemaining());
        query.setParameter("account_flag", keep.getAccountFlag());
        int update = query.executeUpdate();
        if (update < 1) {
            return false;
        }

        SQLQuery deleteQuery = getSession().createSQLQuery("DELETE FROM crm_supply_material_keep WHERE id=:keepId");
        deleteQuery.setParameter("keepId", keep.getId());
        int executed = deleteQuery.executeUpdate();
        return executed > 0;
    }

}
