package com.dgtly.member.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.dgtly.apiframework.util.TokenUtil;
import com.dgtly.common.annotation.ApiNoCheckSign;
import com.dgtly.common.annotation.ApiPassToken;
import com.dgtly.common.core.controller.ApiBaseController;
import com.dgtly.common.core.domain.AjaxResult;
import com.dgtly.common.core.domain.ParameterObject;
import com.dgtly.common.core.domain.ResultType;
import com.dgtly.common.utils.DateUtils;
import com.dgtly.common.utils.StringUtils;
import com.dgtly.member.domain.MemberInfo;
import com.dgtly.member.service.IMemberInfoService;
import com.google.code.kaptcha.Constants;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @descption: 网站前端用户信息相关接口API
 * @author LiuLingChao
 * @version 1.0
 * @company 神州数码通用软件（洛阳）有限公司
 * @copyright (c) 2019 LuoYang DGT Co'Ltd Inc. All rights reserved.
 * @date 2020-2-25 14:41
 * @since JDK1.8
 */
@RestController
@RequestMapping("/member/info")
@ApiNoCheckSign/* 不用验证 签名 方法上可用*/
public class MemberInfoController extends ApiBaseController {

    @Autowired
    private IMemberInfoService iMemberInfoService;

    /**
     * @descption: 网站用户注册
     * @param:
     * @return:
     * @auther: LiuLingChao
     * @date: 2020-2-25 14:43
     */
    @ApiOperation(value = "网站用户注册")
    @ApiImplicitParam(name = "params" , paramType = "body")
    @ApiPassToken/* 不用验证token  方法上可用*/
    @PostMapping("/userRegister")
    public Object userRegister(){
        ParameterObject obj =  getParameterObject();
        MemberInfo memberInfo = obj.parseBean(MemberInfo.class);
        //校验用户名唯一性
        MemberInfo memberInfo1 = iMemberInfoService.checkMemberUnique(memberInfo.getLoginAccount());
        if(memberInfo1 != null){
            return AjaxResult.error(ResultType.LOGINNAMEREPEAT);
        }
        //校验手机号码唯一性
        MemberInfo memberInfo2 = iMemberInfoService.checkMemberPhoneUnique(memberInfo.getPhone());
        if(memberInfo1 != null){
            return AjaxResult.error(ResultType.PHONEREPEAT);
        }
        memberInfo.setLoginTime(DateUtils.getNowDate());
        memberInfo.setCreateTime(DateUtils.getNowDate());
        int flag = iMemberInfoService.insertMemberInfo(memberInfo);
        return toAjax(flag);

    }

    /**
     * @descption: 网站会员登录
     * @param:登录账号/手机号、密码
     * @return:
     * @auther: LiuLingChao
     * @date: 2020-2-25 15:35
     */
    @ApiOperation(value = "会员登录")
    @ApiImplicitParam(name = "params" , paramType = "body")
    @ApiPassToken/* 不用验证token  方法上可用*/
    @PostMapping("/memberLogin")
    public Object memberLogin(){
        ParameterObject obj =  getParameterObject();
        MemberInfo memberInfo = obj.parseBean(MemberInfo.class);
       //获取验证码
        HttpSession httpSession = getSession();
        String key = httpSession.getAttribute(Constants.KAPTCHA_SESSION_KEY)+"";
        logger.info("登录是sessionId:"+httpSession.getId());
        logger.info("登录sessionCode:"+key);
        logger.info("登录ValidateCode:"+memberInfo.getValidateCode());
        if(null != key && key.equals(memberInfo.getValidateCode())){
            MemberInfo memberInfo1 = iMemberInfoService.memberLogin(memberInfo);
            if(memberInfo1 == null){
                return AjaxResult.error(ResultType.PASSWORDERROR);
            }
            Date start = new Date();
            long currentTime = System.currentTimeMillis() + 12*60* 60 * 1000;//12小时有效时间
            Date end = new Date(currentTime);
            String token = JWT.create().withAudience(memberInfo1.getId()+"")
                    .withIssuedAt(start)
                    .withExpiresAt(end)
                    .sign(Algorithm.HMAC256(memberInfo1.getLoginPassword()));

            return AjaxResult.success().putKV("token",token);
        }

       return AjaxResult.error(ResultType.VERIFICATIONERROR);

    }

    /**
     * @descption: 根据token获取会员信息
     * @param: token
     * @return:
     * @auther: LiuLingChao
     * @date: 2020-2-26 22:16
     */
    @ApiOperation(value = "根据token获取会员信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body"),
            @ApiImplicitParam(name = "token" , paramType = "header")
    })
    @PostMapping("/getMemberInfo")
    public Object getMemberInfo(){
        String userId  = TokenUtil.getTokenUserId();
        MemberInfo memberInfo = iMemberInfoService.selectMemberInfoById(Long.parseLong(userId));
        return AjaxResult.success().putKV("memberInfo",memberInfo);
    }


    /**
     * @descption: 修改用户信息
     * @param: token  用户信息
     * @return:
     * @auther: LiuLingChao
     * @date: 2020-2-28 15:01
     */
    @ApiOperation(value = "修改用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body"),
            @ApiImplicitParam(name = "token" , paramType = "header")
    })
    @PostMapping("/editMemberInfo")
    public Object editMemberInfo(){
        String userId  = TokenUtil.getTokenUserId();
        ParameterObject obj =  getParameterObject();
        MemberInfo memberInfo = obj.parseBean(MemberInfo.class);
        memberInfo.setId(Long.parseLong(userId));
        int flag = iMemberInfoService.updateMemberInfo(memberInfo);
        return toAjax(flag);
    }



    /**
     * @descption: 统计平台会员注册数量
     * @param:
     * @return:
     * @auther: LiuLingChao
     * @date: 2020-03-11 10:36
     */
    @ApiPassToken
    @PostMapping("/countMemberInfo")
    public Object countMemberInfo(){
        int memberNum = iMemberInfoService.countMemberInfo();
        return AjaxResult.success().putKV("memberNum",memberNum);

    }

}
