package com.bizzan.bitrade.controller;

import static com.bizzan.bitrade.constant.SysConstant.SESSION_MEMBER;
import static org.springframework.util.Assert.hasText;
import static org.springframework.util.Assert.isTrue;
import static org.springframework.util.Assert.notNull;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import com.bizzan.bitrade.constant.BooleanEnum;
import com.bizzan.bitrade.constant.CommonStatus;
import com.bizzan.bitrade.constant.DisplayMode;
import com.bizzan.bitrade.constant.SysConstant;
import com.bizzan.bitrade.controller.BaseController;
import com.bizzan.bitrade.entity.Coin;
import com.bizzan.bitrade.entity.LoginInfo;
import com.bizzan.bitrade.entity.Member;
import com.bizzan.bitrade.entity.MemberWallet;
import com.bizzan.bitrade.entity.Sign;
import com.bizzan.bitrade.entity.SysAdvertise;
import com.bizzan.bitrade.entity.transform.AuthMember;
import com.bizzan.bitrade.service.ContractRewardRecordService;
import com.bizzan.bitrade.service.LocaleMessageSourceService;
import com.bizzan.bitrade.service.MemberService;
import com.bizzan.bitrade.service.MemberWalletService;
import com.bizzan.bitrade.service.SignService;
import com.bizzan.bitrade.service.SysAdvertiseService;
import com.bizzan.bitrade.service.SysConfigService;
import com.bizzan.bitrade.util.GoogleAuthenticatorUtil;
import com.bizzan.bitrade.util.Md5;
import com.bizzan.bitrade.util.MessageResult;
import com.bizzan.bitrade.vo.LoginInfoVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author QQ 2232965526
 * @Description:
 * @date 2019/5/49:30
 */
@Api(value = "MemberController" , tags = "用户基本信息接口")
@RestController
@Slf4j
@RequestMapping("member")
public class MemberController extends BaseController {
    @Autowired
    private MemberService memberService;
    @Autowired
    private SignService signService;
    @Autowired
    private MemberWalletService walletService;
    @Autowired
    private ContractRewardRecordService contractRewardRecordService;

    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private LocaleMessageSourceService msService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SysAdvertiseService sysAdvertiseService;

    @Value("${dev.mode.vcode:}")
    private String devModeVcode;

    //签到
    @ApiOperation(value="签到", notes="签到")
    @PostMapping("sign-in")
    public MessageResult signIn(@SessionAttribute(SESSION_MEMBER) AuthMember user) {
        //校验 签到活动 币种 会员 会员钱包
        Assert.notNull(user, "The login timeout!");

        Sign sign = signService.fetchUnderway();
        Assert.notNull(sign, "The check-in activity is over!");

        Coin coin = sign.getCoin();
        Assert.isTrue(coin.getStatus() == CommonStatus.NORMAL, "coin disabled!");

        Member member = memberService.findOne(user.getId());
        Assert.notNull(member, "validate member id!");
        Assert.isTrue(member.getSignInAbility() == true, "Have already signed in!");

        //签到事件
        memberService.signInIncident(member, sign);

        return success();
    }
    
    /**
     * 获取用户信息
     * @param user
     * @return
     */
    @ApiOperation(value="获取用户信息", notes="获取用户信息")
    @PostMapping("my-info")
    public MessageResult myInfo(@SessionAttribute(SESSION_MEMBER) AuthMember user) {
        //校验 签到活动 币种 会员 会员钱包
        Assert.notNull(user, "登录信息已超时!");

        Member member = memberService.findOne(user.getId());
        Assert.notNull(member, "登录信息错误!");

        Sign sign = signService.fetchUnderway();
        LoginInfo loginInfo;
        if (sign == null) {
            loginInfo = LoginInfo.getLoginInfo(member, member.getToken(), false, sysConfigService.get().getPromotionPrefix());
        } else {
            loginInfo = LoginInfo.getLoginInfo(member, member.getToken(), true, sysConfigService.get().getPromotionPrefix());
        }
        //LoginInfoVo vo = new LoginInfoVo();
        //BeanUtils.copyProperties(loginInfo, vo);
        //vo.setLoginType(loginInfo.getUsername().indexOf("@")>0?2:1);
        return success(loginInfo);
    }
    
    @ApiOperation(value="获取推荐信息", notes="获取推荐信息")
    @GetMapping("promotion")
    public MessageResult sysPromotion(
            @RequestHeader(value = "lang") String headerLanguage,
            @RequestHeader(value = "mode") DisplayMode mode) {
		//SysAdvertise sysAdvertise = sysAdvertiseService.findAll().findPromotion(headerLanguage, mode);
		MessageResult result = MessageResult.success();
		result.setData(sysAdvertiseService.findAll());
		return result;
	}

    //@PostMapping("promotion-rank")
    public MessageResult getPromotionRank() {
    	
    	return null;
    }
    
    @PostMapping("validate-password")
    public MessageResult validatePassword(@SessionAttribute(SESSION_MEMBER) AuthMember user, String password) {
    	Member member = memberService.findOne(user.getId());
    	try {
			if (Md5.md5Digest(password + member.getSalt()).toLowerCase().equals(member.getJyPassword()))
				return MessageResult.success();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return MessageResult.error(500, "");
		}
    	return MessageResult.error(500, "");
    }
    
    @ApiOperation(value="验证代码验证码", notes="验证代码验证码")
    @PostMapping("validate-agent-code")
    public MessageResult validateAgentCode(@SessionAttribute(SESSION_MEMBER) AuthMember user, Integer vtype, String vcode) {
    	Member member = memberService.findOne(user.getId());
    	boolean isDevBypass = !devModeVcode.isEmpty() && devModeVcode.equals(vcode);
    	if(vtype == 1) {
    		if (!isDevBypass) {
	        	ValueOperations valueOperations = redisTemplate.opsForValue();
	            Object cache = valueOperations.get(SysConstant.PHONE_AGENT_CODE_PREFIX + member.getMobilePhone());
	            notNull(cache, msService.getMessage("NO_GET_VERIFICATION_CODE"));
	            hasText(vcode, msService.getMessage("MISSING_VERIFICATION_CODE"));
	            if (!vcode.equals(cache.toString())) {
	            	return MessageResult.error(msService.getMessage("VERIFICATION_CODE_INCORRECT"));
	            } else {
	                valueOperations.getOperations().delete(SysConstant.PHONE_AGENT_CODE_PREFIX + member.getMobilePhone());
	            }
    		}
        } else if (vtype == 2) {
        	if (!isDevBypass) {
	        	ValueOperations valueOperations = redisTemplate.opsForValue();
	            Object cache = valueOperations.get(SysConstant.EMAIL_AGENT_PREFIX + member.getEmail());
	            notNull(cache, msService.getMessage("NO_GET_VERIFICATION_CODE"));
	            isTrue(vcode.equals(cache.toString()), msService.getMessage("VERIFICATION_CODE_INCORRECT"));
        	}
        } else if (vtype == 3) {
        	if (isDevBypass) {
        		// dev模式跳过谷歌验证
        	} else if(vcode==null || vcode.trim().equals("")) {
        		return MessageResult.error(msService.getMessage("VERIFICATION_CODE_INCORRECT"));
            } else {
            	long t = System.currentTimeMillis();
                GoogleAuthenticatorUtil ga = new GoogleAuthenticatorUtil();
                if(member.getGoogleKey()!=null) {
                    boolean r = ga.check_code(member.getGoogleKey(), Long.parseLong(vcode), t);
                    if(!r)
                    	return MessageResult.error(msService.getMessage("VERIFICATION_CODE_INCORRECT"));
                } else {
                	return MessageResult.error(msService.getMessage("GOOGLE_NO_BIND"));
                }
            }
        } else {
        	return MessageResult.error("");
        }
		return MessageResult.success();
    }
    
    @ApiOperation(value="获取代理商信息", notes="获取代理商信息")
    //@PostMapping(value = "agent")
    public MessageResult agentInfo(
            @SessionAttribute(SESSION_MEMBER) AuthMember user) {
    	Member member = memberService.findOne(user.getId());
    	log.info("contractRewardRecordService={}, id={}", contractRewardRecordService,member.getId());
    	//Double total_reward = contractRewardRecordService.findRewardSum(member.getId());
    	//member.setUsdtBalance(total_reward);
    	MessageResult result = MessageResult.success();
    	result.setData(member);
    	return result;
    }

}
