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

import com.neusoft.smart.pos.framework.utils.IdGenerateUtils;
import com.neusoft.smart.pos.payorder.persistent.domain.MchPayInfo;
import com.neusoft.smart.pos.payorder.persistent.domain.MchPayInfoExample;
import com.neusoft.smart.pos.payorder.persistent.mapper.MchPayInfoMapper;
import lombok.val;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author zcf
 * @date 2018-01-09 10：43
 * @description 支付管理使用Repository
 */
@Component
public class MchPayInfoRepository {

	@Resource
	private MchPayInfoMapper mchPayInfoMapper;

	/**
	 * 商户信息查询方法
	 * @param mcode：商户号
	 * @return
	 */
	public MchPayInfo queryMchPayInfoByMcode(String mcode, String mchStatus){
		val example = new MchPayInfoExample();
		example.createCriteria()
				.andMcodeEqualTo(mcode)
				.andMchStatusEqualTo(mchStatus);
		val mchPayInfos = mchPayInfoMapper.selectByExample(example);
		return mchPayInfos.size()>0?mchPayInfos.get(0):null;
	}

	/**
	 * 商户信息查询方法
	 * @param userNumber：用户编号
	 * @param mchName：商户号
	 * @param applyType：申请类型
	 * @return
	 */
	public MchPayInfo createMchPayInfo(Integer userNumber,String mchName,String applyType,String mchStatus){
		val mchPayInfo = new MchPayInfo();
		mchPayInfo.setUserNumber(userNumber);
		mchPayInfo.setMchName(mchName);
		mchPayInfo.setApplyType(applyType);
		mchPayInfo.setMcode(generateMCode());
		mchPayInfo.setMchStatus(mchStatus);
		mchPayInfo.setSecretKey(IdGenerateUtils.randomLetterNumber(16));
		mchPayInfoMapper.insertSelective(mchPayInfo);
		return mchPayInfo;
	}

	/**
	 * 商户号生成方法
	 * @return
	 */
	public String generateMCode(){
		String mcode;
		while(true){
			mcode = IdGenerateUtils.generateMCode();
			val example = new MchPayInfoExample();
			example.createCriteria()
					.andMcodeEqualTo(mcode);
			val mchPayInfos = mchPayInfoMapper.selectByExample(example);
			if(null == mchPayInfos || mchPayInfos.size() == 0){
				break;
			}
		}
		return mcode;
	}

}
