package com.iamberry.wechat.service.giftCard;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.CommonDto;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.cart.SendPayDto;
import com.iamberry.wechat.core.entity.giftCard.AgentInfo;
import com.iamberry.wechat.core.entity.giftCard.AgentMachine;
import com.iamberry.wechat.core.entity.giftCard.AgentPayLogs;
import com.iamberry.wechat.core.entity.giftCard.GiftCardPayCode;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.pay.PayResult;
import com.iamberry.wechat.core.entity.product.ProductColor;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.giftCard.AgentService;
import com.iamberry.wechat.face.giftCard.GiftCardService;
import com.iamberry.wechat.face.mq.EfastOrderService;
import com.iamberry.wechat.face.pay.PayService;
import com.iamberry.wechat.service.mapper.AgentMachineMapper;
import com.iamberry.wechat.service.mapper.AgentMapper;
import com.iamberry.wechat.service.mapper.GiftCardPayCodeMapper;
import com.iamberry.wechat.service.mapper.ProductColorMapper;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;

/**
 * 付费代理商	service实现
 * @author muzx
 * create date : 2017年2月16日
 */
@Service
public class AgentServiceImpl implements AgentService {
	@Autowired
	private AgentMapper agentMapper;
	@Autowired
    private SystemService SystemDao;
	@Autowired
    private AgentMachineMapper agentMachineMapper;
    @Autowired
    private ProductColorMapper productColorMapper;
    @Autowired
    private GiftCardPayCodeMapper giftCardPayCodeMapper;
    @Autowired
    private EfastOrderService efastOrderService;
    @Autowired
    private PayService payService;
    @Autowired
    private GiftCardService cardService;
    @Autowired
    private RatFWLogger logger;
    
	@Override
	public List<AgentInfo> beRefereesList(AgentInfo agentInfo) {
		// TODO Auto-generated method stub
		return agentMapper.beRefereesList(agentInfo);
	}
	@Override
	public AgentPayLogs selectPayLogByOpenid(AgentPayLogs agentPayLogs) {
		// TODO Auto-generated method stub
		return agentMapper.selectPayLogByOpenid(agentPayLogs);
	}
	@Override
	public AgentPayLogs selectPayLogById(Integer id) {
		// TODO Auto-generated method stub
		return agentMapper.selectPayLogById(id);
	}
	@Override
	public boolean updatePayLogsById(AgentPayLogs payLogs) {
		// TODO Auto-generated method stub
		Integer i = agentMapper.updatePayLogsById(payLogs);
		if(i != null && i.intValue() > 0){
			return true;
		}else{
			return false;
		}
	}
	
	@Override
    public boolean updateAgentInfoByOpenId(AgentInfo agentInfo) {
        // TODO Auto-generated method stub
        return agentMapper.updateAgentInfoByOpenId(agentInfo);
    }
	@Override
	public AgentInfo selectAgentByOpenId(String openId) {
		// TODO Auto-generated method stub
		return agentMapper.selectAgentByOpenId(openId);
	}
	
	@Override
	public List<AgentInfo> selectAgentList() {
		// TODO Auto-generated method stub
		return agentMapper.selectAgentList();
	}
	@Override
	public List<AgentPayLogs> selectPayLogHasByOpenid(String openId) {
		// TODO Auto-generated method stub
		return agentMapper.selectPayLogHasByOpenid(openId);
	}
	@Override
    public String insertAgentInfoAndAgentPayLogAndAgentMachine(CommonDto commonDto, Member member, AgentMachine agentMachine) {
        // 1.添加付费代理信息<没有则添加,有则不变>
        insertAgentInfoByMember(commonDto.getStr1(), commonDto.getStr2(), member);
        // 2.添加支付记录 
        String payIdStr = insertPayLog(member);
        // 3.添加付费代理赠送机器信息
        agentMachine.setAgentMachineOpenId(member.getUserOpenid());
        String machineStr = addAgentMachine(agentMachine);
        StringBuilder sb = new StringBuilder("AOID_");
        sb.append(payIdStr);
        sb.append("_");
        sb.append(machineStr);
        return  sb.toString();
    }
	@Override
    public String updatePayLogStatusAndReferrerAndPayCodeStatus(String payId, String openId, GiftCardPayCode payCode) {
        // TODO Auto-generated method stub
        String str = "";    //推荐人赠送记录id 若无，则空字符串
        //1. 修改支付记录状态为已支付
        AgentPayLogs payLog = new AgentPayLogs();
        payLog.setPayId(Integer.parseInt(payId));
        payLog.setPayMoney(0);
        payLog.setPayStatus(2);
        agentMapper.updatePayLogsById(payLog);
        
        //2. 修改付费代理商的推荐人
        if(payCode != null && StringUtils.isNotEmpty(payCode.getCodeReferrerOpenid())){
            AgentInfo agentInfo = new AgentInfo();
            agentInfo.setAgentOpenId(openId);
            agentInfo.setAgentReferrerOpenid(payCode.getCodeReferrerOpenid());
            agentMapper.updateAgentInfoByOpenId(agentInfo);
            
            //3. 插入推荐人物流信息
            Integer j = 0;
            AgentMachine agentMachine = new AgentMachine();
            agentMachine.setAgentMachineOpenId(payCode.getCodeReferrerOpenid());
            agentMachine.setAgentMachineType(2);
            agentMachine.setAgentMachineStatus(0);
            j = agentMachineMapper.insertAgentMachine(agentMachine);
            if(j != null && j > 0 ){
                str = agentMachine.getAgentMachineId().toString();
            }
        }
        
        //4.修改支付密码的使用状态和使用人
        payCode.setCodeStatus(2);
        payCode.setCodeUseOpenid(openId);
        payCode.setCodeUpdateDate(new Date());
        giftCardPayCodeMapper.updatePayCodeStatusAndUseOpenId(payCode);
        return str;
    }
	
	@Override
    public String updatePayLogStatus(String payId, String openId, GiftCardPayCode payCode) {
        // TODO Auto-generated method stub
        String str = "";    //推荐人赠送记录id 若无，则空字符串
        //1. 修改支付记录状态为已支付
        AgentPayLogs payLog = new AgentPayLogs();
        payLog.setPayId(Integer.parseInt(payId));
        payLog.setPayMoney(0);
        payLog.setPayStatus(2);
        agentMapper.updatePayLogsById(payLog);
        
        //4.修改支付密码的使用状态和使用人
        payCode.setCodeStatus(2);
        payCode.setCodeUseOpenid(openId);
        giftCardPayCodeMapper.updatePayCodeStatusAndUseOpenId(payCode);
        return str;
    }
	
	/**
     * 添加付费代理信息(没有才添加)
     * 2017年2月28日
     * @author muzx
     * @param userName 用户名
     * @param tel 电话
     * @param member 用户其他信息
     * @return
     */
    private Integer insertAgentInfoByMember(String userName, String tel, Member member) {
        // TODO Auto-generated method stub
        if(member == null || StringUtils.isEmpty(member.getUserOpenid())){
            return null;
        }
        AgentInfo agentInfo = agentMapper.selectAgentByOpenId(member.getUserOpenid()); 
        if(agentInfo == null){
            agentInfo = new AgentInfo();
            agentInfo.setAgentOpenId(member.getUserOpenid());
            agentInfo.setAgentNickname(userName);
            agentInfo.setAgentTel(tel);
            agentInfo.setAgentHead(member.getUserHead());
            agentInfo.setAgentArea(member.getUserAddr());
            agentInfo.setAgentSex(member.getUserSex());
            agentInfo.setAgentCardSum(0);
            agentMapper.insertAgentInfo(agentInfo);
        }
        return agentInfo.getAgentId();
    }
    /**
     * 添加付费代理商支付记录
     * 2017年3月2日
     * @author muzx
     * @param member
     * @return
     */
    private String insertPayLog(Member member){
        AgentPayLogs payLog = new AgentPayLogs();
        payLog.setPayOpenId(member.getUserOpenid());
        payLog.setPayStatus(1); //默认待支付
        //从规则表中获取生成礼品卡的数量
        ShopSystemRule shopSystemRule =  SystemDao.selectOneShopRuleById(222);
        int cardNum = shopSystemRule.getRuleNum().intValue();
        payLog.setPayGiftCardNum(cardNum);
        //从规则表中获取:付费代理商支付金额
        ShopSystemRule shopSystemRule1 =  SystemDao.selectOneShopRuleById(224);
        int money = shopSystemRule1.getRuleNum().intValue();
        payLog.setPayMoney(money);
        agentMapper.insertAgentPayLog(payLog);
        Integer payId = payLog.getPayId();
        return payId.toString();
    }
    /**
     * 添加当前代理商物流信息
     * 2017年2月21日
     * @author muzx
     * @return 物流记录id
     */
    private String addAgentMachine(AgentMachine agentMachine) {
        // TODO Auto-generated method stub
        StringBuilder sb = new StringBuilder("");
        if(agentMachine == null || 
                StringUtils.isEmpty(agentMachine.getAgentMachineOpenId()) || 
                agentMachine.getAgentMachineProductId() == null ||
                agentMachine.getAgentMachineColorId() == null){
            return sb.toString();
        }
        //填充数据
        ProductColor productColor = productColorMapper.selectProductColorById(agentMachine.getAgentMachineColorId());
        agentMachine.setAgentMachineColorName(productColor.getColorName());
        agentMachine.setAgentMachineProductName(productColor.getColorProductName());
        agentMachine.setAgentMachine69code(productColor.getColor69Code());
        agentMachine.setAgentMachineStatus(0);
        agentMachine.setAgentMachineType(1);
        //插入当前代理商物流信息
        Integer i = agentMachineMapper.insertAgentMachine(agentMachine);
        if(i != null && i > 0){
            sb.append(agentMachine.getAgentMachineId());
        }
        return sb.toString();
    }
    
    @Override
    public ResultMsg toPayAgain(AgentMachine agentMachine, String agentNickname, String agentTel, String payPassword) throws Exception{
        ResultMsg rm = new ResultMsg();
        rm.setResultCode(ResultInfo.ERRORCODE);
        SendPayDto dto = new SendPayDto();
        dto.setSuccess(false);
        AgentInfo agentInfo = checkAndUpdateAgentInfo(agentMachine.getAgentMachineOpenId(), agentNickname, agentTel);        
        // 获取抵扣密码
        GiftCardPayCode payCode = new GiftCardPayCode(); // 抵扣密码
        if (StringUtils.isNotEmpty(payPassword) && agentInfo.getAgentIsHudredAgent() != 1) {
            payCode.setCodePassword(payPassword);
            payCode = giftCardPayCodeMapper.getPayCodeByIdOrPassword(payCode);
        }
        String orderId = addAgentPayLogAndLogisticsMachine(agentInfo, agentMachine, payCode);
        return beginPay(payCode, agentMachine, dto, orderId, agentInfo);
    }
    
    /**
     * 校验并修改代理商信息
     * 2017年4月1日
     * @author muzx
     * @param openId
     * @param agentNickname
     * @param agentTel
     * @return
     */
    private AgentInfo checkAndUpdateAgentInfo(String openId, String agentNickname, String agentTel){
        AgentInfo agentInfo = agentMapper.selectAgentByOpenId(openId);
        if(agentInfo == null){
            return null;
        }
        agentInfo.setAgentNickname(StringUtils.isNotEmpty(agentNickname) ? agentNickname : "");
        agentInfo.setAgentTel(StringUtils.isNotEmpty(agentTel) ? agentTel : "");
        agentMapper.updateAgentInfoByOpenId(agentInfo);
        return agentInfo;
    }
    /**
     * 获取万元代理/百台代理支付金额
     * 2017年4月1日
     * @author muzx
     * @param agentInfo
     * @return
     */
    private int getAgentPayManey(AgentInfo agentInfo){
        int i = 224;        //  付费代理商支付金额
        if(agentInfo.getAgentIsHudredAgent() == 1){
            i = 230;        //  百台代理续费支付金额
        }
        ShopSystemRule shopSystemRule1 = SystemDao.selectOneShopRuleById(i);
        return shopSystemRule1.getRuleNum().intValue();
    }
    
    /**
     * 添加万元小代理/百台代理 支付记录和赠送机器记录
     * @time 2017年3月31日 重构
     * @author muzx
     * @param agentInfo
     * @param agentMachine
     * @return  用作：支付订单号,   格式："AOID_" + 支付记录id + "_" + 代理商机器物流记录id
     * @throws Exception
     */
    private String addAgentPayLogAndLogisticsMachine(AgentInfo agentInfo, AgentMachine agentMachine, GiftCardPayCode payCode) throws Exception{
        StringBuilder sb = new StringBuilder("AOID_");
        boolean hasPayCode = payCode != null && StringUtils.isNotEmpty(payCode.getCodePassword())
                 && payCode.getCodeStatus() == 1;    //是否是能用的抵扣券支付
        
        AgentPayLogs payLog = new AgentPayLogs();
        payLog.setPayOpenId(agentInfo.getAgentOpenId());
        payLog.setPayStatus(hasPayCode ? 2 : 1);
        payLog.setPayCreateDate(new Date());
        payLog.setPayMoney(hasPayCode ? 0 :getAgentPayManey(agentInfo));
        if(agentMapper.insertAgentPayLog(payLog) < 1){
            throw new IllegalAccessException();
        }
        
        //填充产品信息
        ProductColor productColor = productColorMapper.selectProductColorById(agentMachine.getAgentMachineColorId());
        agentMachine.setAgentMachineColorName(productColor.getColorName());
        agentMachine.setAgentMachineProductName(productColor.getColorProductName());
        agentMachine.setAgentMachine69code(productColor.getColor69Code());
        agentMachine.setAgentMachineStatus(hasPayCode ? 2 : 0);
        agentMachine.setAgentMachineType(1);
        //插入当前代理商物流信息
        if(agentMachineMapper.insertAgentMachine(agentMachine) < 1){
            throw new IllegalAccessException();
        }
        sb.append(payLog.getPayId()).append("_").append(agentMachine.getAgentMachineId());
        return sb.toString();
    }
    
    /**
     * 发起支付
     * @time    2017年4月1日
     * @author  muzx
     * @param payCode   抵扣密码信息
     * @param agentMachine  代理商机器物流信息
     * @param dto   封装返回参数
     * @param orderId   支付订单号,格式："AOID_" + 支付记录id + "_" + 代理商机器物流记录id
     * @param payMoney
     * @return
     * @throws Exception
     */
    private ResultMsg beginPay(GiftCardPayCode payCode, AgentMachine agentMachine, SendPayDto dto, String orderId, AgentInfo agentInfo) throws Exception{
        ResultMsg rm = new ResultMsg();
        rm.setResultCode(ResultInfo.ERRORCODE);
        
        String[] arr = orderId.split("_");
        if (payCode != null && StringUtils.isNotEmpty(payCode.getCodePassword())) { // 有抵扣密码，则抵扣金额
            if (payCode.getCodeStatus() == 1) {
                payCode.setCodeStatus(2);
                payCode.setCodeUseOpenid(agentMachine.getAgentMachineOpenId());
                giftCardPayCodeMapper.updatePayCodeStatusAndUseOpenId(payCode);
                int agentType = 1;
                if(agentInfo.getAgentIsHudredAgent() == 1){
                    agentType = 2;
                }
                cardService.saveCardAndMachine(agentType, agentMachine.getAgentMachineOpenId(), Integer.parseInt(arr[2]), null);
                try {
                    // 推送百胜
                    efastOrderService.giftCard(
                            agentMachine.getAgentMachineAddressInfo(),
                            "ZS1111111_" + agentMachine.getAgentMachineId(),
                            agentMachine.getAgentMachineColorId(),
                            agentMachine.getAgentMachineAddressName(),
                            agentMachine.getAgentMachineAddressTel(),
                            agentMachine.getAgentMachineOpenId());
                } catch (Exception e) {
                    logger.info(this, "ZS1111111_" + agentMachine.getAgentMachineId() + "推送百胜失败!");
                    e.printStackTrace();
                }
                dto.setInfo("恭喜您抵扣成功!");
                dto.setSuccess(true);
            } else { // 错误的抵扣密码
                dto.setInfo("您输入的抵扣密码不正确或已经被使用!");
                dto.setSuccess(false);
                rm.setResultCode("4003");
                rm.setMessage("您输入的抵扣密码不正确或已经被使用!");
                rm.setData(dto);
                rm.setStatus(false);
                return rm;
            }
        }else{
            PayResult result = payService.requestPay(agentMachine.getAgentMachineOpenId(),
                    orderId, getAgentPayManey(agentInfo), "美国Watero净饮水一体机" + "...",
                    NameUtils.getConfig("WECHAT_AGENT_RENEWAL_BACK"));
            if (result.isPaySuccess()) {
                // 支付成功后，插入付费代理及其推荐人物流信息
                dto.setInfo(result.getPayData());
                dto.setSuccess(true);
            } else {
                dto.setInfo(result.getPayData());
                dto.setSuccess(false);
                rm.setResultCode("4002");
                rm.setMessage("支付失败!");
                rm.setData(dto);
                rm.setStatus(false);
                return rm;
            }
        }
        dto.setOrderId(orderId);
        rm.setResultCode(ResultInfo.SUCCESSCODE);
        rm.setMessage(NameUtils.getConfig("SUCCESSINFO"));
        rm.setData(dto);
        rm.setStatus(true);
        return rm;
    }
   
}
