package com.neusoft.smart.pos.trade.repository;


import com.neusoft.smart.pos.framework.utils.IdGenerateUtils;
import com.neusoft.smart.pos.framework.utils.LocalDateTimeUtils;
import com.neusoft.smart.pos.order.constants.TradeConstant;
import com.neusoft.smart.pos.trade.persistent.domain.GrantOrderMaster;
import com.neusoft.smart.pos.trade.persistent.domain.GrantOrderMasterExample;
import com.neusoft.smart.pos.trade.persistent.ext.mapper.GrantOrderMasterExtMapper;
import com.neusoft.smart.pos.trade.persistent.mapper.GrantOrderMasterMapper;
import com.neusoft.smart.pos.utils.PosDeviceRedisUtils;
import com.neusoft.smart.pos.utils.RequestHeaderUtil;
import lombok.val;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author zcf
 * @date 2018-11-28 10：43
 * @description 资金预授权订单管理使用Repository
 */
@Component
public class GrantOrderMasterRepository {

	@Resource
	private GrantOrderMasterMapper grantOrderMasterMapper;
	
	@Resource
	private GrantOrderMasterExtMapper grantOrderMasterExtMapper;

	/**
	 * 订单信息保存方法
	 * @return
	 */
	public Integer saveGrantOrder(GrantOrderMaster grantOrderMaster){
		//存储设备别名
		if(!StringUtils.isEmpty(grantOrderMaster.getSerialNo())){
			grantOrderMaster.setDeviceName(PosDeviceRedisUtils.getDeviceInfoBySerialNo(grantOrderMaster.getSerialNo()).getAlias());
		}
		if(!StringUtils.isEmpty(RequestHeaderUtil.getUsername())){
			grantOrderMaster.setCustomerNumber(String.valueOf(RequestHeaderUtil.getUserId()));
			grantOrderMaster.setCreatedBy(RequestHeaderUtil.getUsername());
		}
        //计算订单失效时间，默认为2小时
		if(null == grantOrderMaster.getTimeExpire()){
			val currentLocalTime = LocalDateTimeUtils.getNow();
			val timeExpire = LocalDateTimeUtils.plusMinutes(currentLocalTime, TradeConstant.ORDER_DEFAULT_TIME_EXPIRE);
			grantOrderMaster.setTimeExpire(LocalDateTimeUtils.convertLocalDateTimeToDate(timeExpire));
			grantOrderMaster.setCreatedAt(LocalDateTimeUtils.convertLocalDateTimeToDate(currentLocalTime));
		}
		return grantOrderMasterMapper.insertSelective(grantOrderMaster);
	}

    /**
     * 订单号生成方法
     * @return
     */
    public String generateGrantOrderNumber(){
        String grantOrderNumber;
        while(true){
            grantOrderNumber = IdGenerateUtils.generateOrderNumber();
            val example = new GrantOrderMasterExample();
            example.createCriteria()
                    .andGrantOrderNumberEqualTo(grantOrderNumber)
                    .andCreatedAtGreaterThanOrEqualTo(LocalDateTimeUtils.convertLocalDateTimeToDate(LocalDateTimeUtils.getCurrentDayStart()));
            val orderInfos = grantOrderMasterMapper.selectByExample(example);
            if(null == orderInfos || orderInfos.size() == 0){
                break;
            }
        }
        return grantOrderNumber;
    }
	
	/**
	 * 订单信息查询方法
	 * @param grantOrderNumber：订单编号
	 * @return
	 */
	public GrantOrderMaster queryOrderByOrderNumber(String grantOrderNumber){
		val example = new GrantOrderMasterExample();
		example.createCriteria().andGrantOrderNumberEqualTo(grantOrderNumber);
		val orders = grantOrderMasterMapper.selectByExample(example);
		return orders.size()>0?orders.get(0):null;
	}
	
	/**
	 * 订单信息查询方法
	 * @param grantOrderNumber：订单编号
	 * @return
	 */
	public GrantOrderMaster queryOrderByOrderNumber(Integer orgId, Integer shopId, String grantOrderNumber){
		val example = new GrantOrderMasterExample();
		example.createCriteria().andGrantOrderNumberEqualTo(grantOrderNumber)
				.andOrgIdEqualTo(orgId)
				.andShopIdEqualTo(shopId);
		val orders = grantOrderMasterMapper.selectByExample(example);
		return orders.size()>0?orders.get(0):null;
	}
	
	/**
	 * 订单信息更新方法
	 * @return
	 */
	public Boolean updateGrantOrderMasterInfo(GrantOrderMaster grantOrderMaster){
		grantOrderMaster.setUpdatedAt(new Date());
		val example = new GrantOrderMasterExample();
		example.createCriteria().andGrantOrderNumberEqualTo(grantOrderMaster.getGrantOrderNumber());
		val result = grantOrderMasterMapper.updateByExampleSelective(grantOrderMaster,example);
		return result>0?true:false;
	}
	
	/**
	 * 订单信息列表查询方法
	 * @return
	 */
	public Integer queryGrantOrderCount(GrantOrderMasterExample example){
		return grantOrderMasterMapper.countByExample(example);
	}
	
	/**
	 * 订单信息列表查询方法
	 * @return
	 */
	public List<GrantOrderMaster> queryGrantOrderList(GrantOrderMasterExample example){
		return grantOrderMasterMapper.selectByExample(example);
	}
	
	/**
	 * 更新订单失效状态
	 */
	public void updateGrantOrderStatus(){
		GrantOrderMasterExample example = new GrantOrderMasterExample();
		grantOrderMasterExtMapper.updateGrantOrderStatus(example);
	}
}
