package com.chinacreator.video.restful.service;


import com.chinacreator.video.bean.HandleOrgMap;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.ChannelDao;
import com.chinacreator.video.mapper.QueryOrderDao;
import com.chinacreator.video.mapper.UnifiedInvokeDao;
import com.chinacreator.video.restful.dao.RedeemUserDao;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.RedisService;
import com.chinacreator.video.validate.*;
import org.apache.commons.lang.StringUtils;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RedeemUserService {
    @Autowired
    private RedeemUserDao redeemUserDao;


    @Autowired
    private IpValidate ipValidate;


    @Autowired
    private ChannelValidate channelValidate;

    @Autowired
    private MobValidate mobValidate;

    @Autowired
    private TimetampValidate timetampValidate;

    @Autowired
    private ChannelDao channelDao;


    public void check(OrderInfo orderInfo) throws Exception {
        //timetamp验证
        timetampValidate.validate(orderInfo.getTimestamp());
        //渠道验证
        channelValidate.validate(orderInfo.getChannel());
        //ip验证
        ipValidate.volidate(orderInfo);
        //签名验证
         this.validate(orderInfo);
        //手机号码验证
        mobValidate.validate(orderInfo);

    }

    public void insert(OrderInfo orderInfo) {
        redeemUserDao.insert(orderInfo);
    }


    public void validate(OrderInfo orderInfo) throws Exception {
        String lcalsign = getSign(orderInfo);
        lcalsign += channelDao.queryChannel(orderInfo.getChannel()).getPassword();
        lcalsign = MD5.MD5Encode(lcalsign);
        if(!lcalsign.equals(orderInfo.getSignature())) {
            throw new BussinessException("10006", "签名校验失败");
        }
    }

    public void findUser(OrderInfo orderInfo) throws BussinessException {
       int count=redeemUserDao.findUser(orderInfo);
       if (count>0){
           throw  new  BussinessException("8001","用户已订购");
       }
    }
    /**
     * 拼接签名信息 cpid+spid+userid+type+channel+timestamp
     * @param orderInfo
     * @return
     */
    private String getSign(OrderInfo orderInfo) {
        if (orderInfo == null) {
            return "";
        }
        StringBuilder strb = new StringBuilder();
        if(orderInfo.getOrderid() != null && !"".equals(orderInfo.getOrderid())){
            strb.append(orderInfo.getOrderid());
        }
        strb.append(orderInfo.getUserid());
        strb.append(orderInfo.getChannel());
        strb.append(orderInfo.getCpid());
        strb.append(orderInfo.getSpid());
        strb.append(orderInfo.getTimestamp());
        return strb.toString();
    }

}
