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

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.config.SfCacheService;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;


import com.sifang.modules.supply.warehouse.entity.SupplyMaterialBatch;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 物料批次信息DAO接口
 * @author lzp
 * @version 
 */
@Repository
public class SupplyMaterialBatchDao extends BaseDao<SupplyMaterialBatch> {

    @Autowired
    SfCacheService cacheService;

    public void createOne(String bizType, String bizId, String bizDetailId, String bizCode, String materialKeepId, String materialId,
                          String belongType, String belongId, String warehouseId, BigDecimal amount, Date createTime, BigDecimal costPrice,
                          BigDecimal bdSalePrice,String batchCode) {
        SupplyMaterialBatch batch = new SupplyMaterialBatch();
        batch.setCode(batchCode);
        // 关联业务信息
        batch.setBizType(bizType);
        batch.setBizId(bizId);
        batch.setBizDetailId(bizDetailId);
        batch.setBizCode(bizCode);
        batch.setMaterialKeepId(materialKeepId);
        batch.setMaterialId(materialId);
        // 批次基本属性
        batch.setBelongType(belongType);
        batch.setBelongId(belongId);
        batch.setWarehouseId(warehouseId);
        batch.setAmount(amount);
        // 批次相关时间信息
        batch.setCreateTime(createTime);
        batch.setInputTime(createTime);
        batch.setInstoreTime(createTime);
        batch.setNewestStorageTime(createTime);
        batch.setRemaining(amount);
        batch.setSoldNum(BigDecimal.ZERO);
        batch.setVersion(1L);
        batch.setCostPrice(costPrice);
        batch.setBdSalePrice(bdSalePrice);
        save(batch);
    }

    /**
     * 生成批次号   批次号生成规则：入库时间的yymmdd+3位顺序号
     * @return
     */
    public synchronized String getBatchCode() {
        String current=DateUtils.formatDate(new Date(),"yyyy-MM-dd");
        long version= Db.queryLong("SELECT COUNT(id) FROM `crm_supply_material_batch` WHERE DATE_FORMAT(create_time,'%Y-%m-%d') =? ",current);
        version=version+1;
        String s = String.format("%03d", version);
        return DateUtils.formatDate(new Date(),"yyMMdd")+s;
    }

    public List<Record> materialBathListData(LayuiPage page, Map<String, String> map) {
        SqlBuilder builder = new SqlBuilder();
        builder.line(" select b.*,m.code as material_code,m.material_name, t.name as material_type ,m.material_specs ")
                .line(" ,m.unit_name as material_unit,m.material_brand,m.qq_code ,k.warehouse_name ,k.delivery_method ,w.ascription_name as trader_name")
                .line(" from  crm_supply_material_batch b  ")
                .line(" left join crm_supply_material m on m.id = b.material_id ")
                .line(" left join crm_supply_material_type t on t.id = m.material_type_id ")
                .line(" left join crm_supply_material_keep k on k.id = b.material_keep_id ")
                .line(" left join crm_supply_warehouse w on w.id = b.warehouse_id ")
                .line(" left join crm_trader a on a.id = w.ascription_id ")
               .line(" where 1=1 ");
        appendCondition(builder, map);
        builder.line("order by b.create_time desc ");
        if (page != null) {
            builder.limit(page.getPage(), page.getLimit());
        }
        return Db.find(builder.build(),builder.params());
    }

    public Long countBathList(Map<String, String> map) {
        SqlBuilder builder = new SqlBuilder();
        builder.line(" select count(1) ")
                .line(" from  crm_supply_material_batch b  ")
                .line(" left join crm_supply_material m on m.id = b.material_id ")
                .line(" left join crm_supply_material_type t on t.id = m.material_type_id ")
                .line(" left join crm_supply_material_keep k on k.id = b.material_keep_id ")
                .line(" left join crm_supply_warehouse w on w.id = b.warehouse_id ")
                .line(" left join crm_trader a on a.id = w.ascription_id ")
                .line(" where 1=1 ");
        appendCondition(builder, map);
        return Db.queryLong(builder.build(),builder.params());
    }

    public void appendCondition(SqlBuilder builder,Map<String, String> map){
        //代理商
        if (StringUtil.isNotBlank(map.get("traderId"))){
//            builder.line(" and b.belong_id = ? ",map.get("traderId"));
            builder.line(" and w.ascription_id = ? ",map.get("traderId"));
        }
        //物料代码
        if (StringUtil.isNotBlank(map.get("materialCode"))){
            builder.line(" and m.code = ? ",map.get("materialCode"));
        }
        //物料类型
        if (StringUtil.isNotBlank(map.get("materialType"))){
            builder.line(" and t.name = ? ",map.get("materialType"));
        }
        //批次号
        if (StringUtil.isNotBlank(map.get("code"))){
            builder.line(" and b.code = ? ",map.get("code"));
        }
        //入库时间
        if (StringUtil.checkParamsValid(map.get("createTimeSta"))) {
            builder.line("and b.input_time >= concat(?, ' 00：00：00')", map.get("createTimeSta").trim());
        }
        if (StringUtil.checkParamsValid(map.get("createTimeEnd"))) {
            builder.line("and b.input_time <= concat(?, ' 23：59：59')", map.get("createTimeEnd").trim());
        }
        //可用库存
        if (StringUtil.isNotBlank(map.get("availableStock"))){
            String availableStock = map.get("availableStock");
            if( "1".equals(availableStock)){
                builder.line(" and b.remaining > 0 ");
            }else if( "2".equals(availableStock)){
                builder.line(" and b.remaining = 0 ");
            }
        }
        //省区
        if (StringUtil.checkParamsValid(map.get("province"))){
            builder.line(" and a.province = ? ",map.get("province"));
        }
        //仓库
        if (StringUtil.checkParamsValid(map.get("warehouseId"))) {
            builder.line(" and K.warehouse_id=? ", map.get("warehouseId"));
        }
        //最新出库时间
        if (StringUtil.checkParamsValid(map.get("newestKeepTimeSta"))) {
            builder.line("and b.newest_keep_time >= concat(?, ' 00：00：00')", map.get("newestKeepTimeSta").trim());
        }
        if (StringUtil.checkParamsValid(map.get("newestKeepTimeEnd"))) {
            builder.line("and b.newest_keep_time <= concat(?, ' 23：59：59')", map.get("newestKeepTimeEnd").trim());
        }
        //库龄
        if (StringUtil.checkParamsValid(map.get("inStockTime"))) {
            String[] inStockTimes = map.get("inStockTime").split(",");
            builder.line(" and ( ");
            for (int i = 0; i < inStockTimes.length; i++) {
                if (i == 0){
                    if("1".equals(inStockTimes[i])){//30天以内
                        builder.line("  CASE WHEN b.remaining = 0 THEN DATEDIFF(b.newest_keep_time, b.input_time) < 30 ELSE DATEDIFF(NOW(), b.input_time) < 30 END");
                    } else if ("2".equals(inStockTimes[i])) {//30(含)天-60天
                        builder.line("  CASE WHEN b.remaining = 0 THEN ( DATEDIFF(b.newest_keep_time, b.input_time) >= 30 AND DATEDIFF(b.newest_keep_time, b.input_time) < 60 ) ELSE ( DATEDIFF(NOW(), b.input_time) >= 30 AND DATEDIFF(NOW(), b.input_time) < 60 ) END");
                    } else if ("3".equals(inStockTimes[i])) {//60(含)天-90天
                        builder.line("  CASE WHEN b.remaining = 0 THEN ( DATEDIFF(b.newest_keep_time, b.input_time) >= 60 AND DATEDIFF(b.newest_keep_time, b.input_time) < 90 ) ELSE ( DATEDIFF(NOW(), b.input_time) >= 60 AND DATEDIFF(NOW(), b.input_time) < 90 ) END");
                    } else if ("4".equals(inStockTimes[i])) {//90天及以上
                        builder.line("  CASE WHEN b.remaining = 0 THEN DATEDIFF(b.newest_keep_time, b.input_time) >= 90 ELSE DATEDIFF(NOW(), b.input_time) >= 90 END");
                    }
                }else {
                    if("1".equals(inStockTimes[i])){//30天以内
                        builder.line(" or CASE WHEN b.remaining = 0 THEN DATEDIFF(b.newest_keep_time, b.input_time) < 30 ELSE DATEDIFF(NOW(), b.input_time) < 30 END");
                    } else if ("2".equals(inStockTimes[i])) {//30(含)天-60天
                        builder.line(" or CASE WHEN b.remaining = 0 THEN ( DATEDIFF(b.newest_keep_time, b.input_time) >= 30 AND DATEDIFF(b.newest_keep_time, b.input_time) < 60 ) ELSE ( DATEDIFF(NOW(), b.input_time) >= 30 AND DATEDIFF(NOW(), b.input_time) < 60 ) END");
                    } else if ("3".equals(inStockTimes[i])) {//60(含)天-90天
                        builder.line(" or CASE WHEN b.remaining = 0 THEN ( DATEDIFF(b.newest_keep_time, b.input_time) >= 60 AND DATEDIFF(b.newest_keep_time, b.input_time) < 90 ) ELSE ( DATEDIFF(NOW(), b.input_time) >= 60 AND DATEDIFF(NOW(), b.input_time) < 90 ) END");
                    } else if ("4".equals(inStockTimes[i])) {//90天及以上
                        builder.line(" or CASE WHEN b.remaining = 0 THEN DATEDIFF(b.newest_keep_time, b.input_time) >= 90 ELSE DATEDIFF(NOW(), b.input_time) >= 90 END");
                    }
                }
            }
            builder.line(" ) ");
        }
    }

    /**
     * 电站物料退回仓库批次库存
     * sold_num -， remaining +
     */
    public boolean backStock(String batchId, BigDecimal amount) {
        StringBuilder sql = new StringBuilder();
        sql.append(" update SupplyMaterialBatch ")
                .append(" set remaining = remaining +:p1 ,soldNum = soldNum -:p2")
                .append(" where id =:p3");
        int result = update(sql.toString(), new Parameter(amount, amount, batchId));
        return result > 0;
    }
}
