package com.huijy.web.controller.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.huijy.common.annotation.LoginMember;
import com.huijy.common.annotation.UnLogin;
import com.huijy.common.core.domain.AjaxResult;
import com.huijy.common.exception.ServiceException;
import com.huijy.common.exception.base.BaseException;
import com.huijy.common.utils.JwtUtils;
import com.huijy.management.domain.Member;
import com.huijy.management.service.IMemberService;
import com.huijy.management.vo.WxLoginFrom;
import com.huijy.management.vo.WxUserInfo;
import com.huijy.weixin.config.WxMaConfiguration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api(value = "登录",tags = "登录接口")
@RestController
@RequestMapping("/api/login")
public class ApiLoginController extends ApiAbstractController  {


    @Autowired
    private JwtUtils jwtUtils;


    @Autowired
    private IMemberService memberService;


    @UnLogin
    @ApiOperation("测试获取token")
    @GetMapping("/getToken")
    public AjaxResult getToken(){
       Member member = memberService.selectMemberByMemberId(1L);
        //生成token
       String token = jwtUtils.generateToken(member.getMemberId());
        if (StringUtils.isBlank(token)) {
            return AjaxResult.error("登录失败,获取token出错");
        }
        Map<String, Object> resultObj = new HashMap<String, Object>();
        resultObj.put(jwtUtils.getHeader(), token);
        resultObj.put("expire", jwtUtils.getExpire());
       // resultObj.put("memberInfo", member);
        return AjaxResult.success(resultObj);
    }

    @ApiOperation("获取测试会员")
    @GetMapping("/getTestMember")
    public AjaxResult getTestMember(@ApiIgnore @LoginMember Member member){
        Map<String, Object> resultObj = new HashMap<String, Object>();
        resultObj.put("memberInfo", member);
        return AjaxResult.success(resultObj);

    }

    @UnLogin
    @ApiOperation("游客微信小程序登录")
    @PostMapping("/wxLogin/{code}")
    public AjaxResult weixin(@PathVariable String code,@RequestBody WxLoginFrom wxLoginFrom){

        if (null == wxLoginFrom) {
            return AjaxResult.error("登录失败,无用户信息");
        }
        //微信提交过来的用户信息
        WxUserInfo wxUserInfo = wxLoginFrom.getUserInfo();
        String token, sessionKey, openId, unionId;
        try {
            WxMaJscode2SessionResult result = WxMaConfiguration.getMaService().getUserService().getSessionInfo(code);
            unionId = result.getUnionid();
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
        } catch (WxErrorException e) {
           e.printStackTrace();
            throw new ServiceException("openid获取失败");
        }
        if (StringUtils.isBlank(openId) || StringUtils.isBlank(sessionKey)) {
            throw new ServiceException("openid获取失败");
        }
//        //验证用户信息完整性
        String sha1 = DigestUtils.sha1Hex(wxLoginFrom.getRawData() + sessionKey);
        if (!wxLoginFrom.getSignature().equalsIgnoreCase(sha1)) {
            logger.info("=====验证===="+wxLoginFrom.getSignature()+"=========="+sha1);

            return AjaxResult.error("登录失败,验证用户信息失败");
        }
       //根据openid查询游客是否已经存在
        Member member = memberService.getMemberByOpenId(openId);
        Date nowTime = new Date();
        if (member!=null){
            //昵称
            member.setNickName(wxUserInfo.getNickName());
            //微信openid
            member.setOpenid(openId);
            //微信UnionId
            member.setUnionid(unionId);
            //微信头像
            member.setAvatarUrl(wxUserInfo.getAvatarUrl());
            //登录ip
            member.setLastLoginIp(this.getClientIp());
            //最后登录 时间
            member.setLastLoginTime(nowTime);
            //登录次数
            member.setLoginNum(member.getLoginNum()+1);
        }else{
            member = new Member();
            //用户名
            member.setName("wx_" + RandomUtil.randomNumbers(10));

            //性别 0：未知、1：男、2：女
            member.setGender(wxUserInfo.getGender()+"");
            //昵称
            member.setNickName(wxUserInfo.getNickName());
            //微信openid
            member.setOpenid(openId);
            //微信UnionId
            member.setUnionid(unionId);
            //微信头像
            member.setAvatarUrl(wxUserInfo.getAvatarUrl());
            //国家
            member.setCountry(wxUserInfo.getCountry());
            //城市
            member.setCity(wxUserInfo.getCity());
            //省会
            member.setProvince(wxUserInfo.getProvince());
            //语言
            member.setLanguage(wxUserInfo.getLanguage());
            //登录ip
            member.setLastLoginIp(this.getClientIp());
            //最后登录 时间
            member.setLastLoginTime(nowTime);
            //注册时间
            member.setRegisterTime(nowTime);
            //登录次数
            member.setLoginNum(1L);

            memberService.insertMember(member);
        }
        //生成token
         token = jwtUtils.generateToken(member.getMemberId());
        if (StringUtils.isBlank(token)) {
            return AjaxResult.error("登录失败,获取token出错");
        }
        Map<String, Object> resultObj = new HashMap<String, Object>();
        resultObj.put(jwtUtils.getHeader(), token);
        resultObj.put("expire", jwtUtils.getExpire());
        resultObj.put("memberInfo", member);
        return AjaxResult.success(resultObj);

    }

}
