package com.fs.app.controller;

import cn.hutool.core.date.DateTime;
import com.fs.app.param.FsUserLoginByMpParam;
import com.fs.app.utils.JwtUtils;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.course.mapper.FsCourseWatchLogMapper;
import com.fs.his.domain.FsUser;
import com.fs.his.service.IFsUserService;
import com.fs.qw.mapper.QwExternalContactMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api("会员-h5-微信相关接口")
@RestController
@RequestMapping("/app/wx/h5/mp")
@Slf4j
public class WxH5MpController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private IFsUserService userService;

    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    RedisCache redisCache;

    @Autowired
    FsCourseWatchLogMapper fsCourseWatchLogMapper;
    @Autowired
    QwExternalContactMapper qwExternalContactMapper;


    @ApiOperation("微信授权登录成为会员")
    @PostMapping("/loginByMp")
    public R loginByMp(@Valid @RequestBody FsUserLoginByMpParam param) {
        try {
            //获取微信用户信息
            WxOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(param.getCode());
            WxOAuth2UserInfo wxMpUser = wxMpService.getOAuth2Service().getUserInfo(wxMpOAuth2AccessToken, null);
//            FsUser user = userService.selectFsUserByUnionid(wxMpUser.getUnionId());
            FsUser user;
            if(StringUtils.isNotEmpty(wxMpUser.getUnionId())) {
                user = userService.selectFsUserByUnionId(wxMpUser.getUnionId());
            } else {
                user = userService.selectFsUserByMpOpenId(wxMpUser.getOpenid());
            }
            if (user != null) {
                //修改
                FsUser userMap = new FsUser();
                userMap.setUserId(user.getUserId());
                userMap.setMpOpenId(wxMpUser.getOpenid());
                userMap.setUnionId(wxMpUser.getUnionId());
        userMap.setUpdateTime(new DateTime());
        userMap.setNickName(wxMpUser.getNickname());
        userMap.setAvatar(wxMpUser.getHeadImgUrl());
                userService.updateFsUser(userMap);
            } else {
                //新增
                user = new FsUser();
                user.setNickName(wxMpUser.getNickname());
                user.setAvatar(wxMpUser.getHeadImgUrl());
                user.setStatus(1);
                user.setMpOpenId(wxMpUser.getOpenid());
                user.setUnionId(wxMpUser.getUnionId());
                // 新用户 - 添加 appId
                if (StringUtils.isNotEmpty(param.getAppId())) {
                    user.setAppId(param.getAppId());
                }
                user.setCreateTime(new Date());
                userService.insertFsUser(user);
            }
            log.info("用户信息user: {}, 用户id: {}", user, user.getUserId());
            String token = jwtUtils.generateToken(user.getUserId());
            redisCache.setCacheObject("token:" + user.getUserId(), token, 604800, TimeUnit.SECONDS);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("user", user);
            return R.ok(map);
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 40163) {
                return R.error(40163, e.getError().getErrorMsg());
            } else {
                return R.error("授权失败," + e.getMessage());
            }
        }

    }

    @ApiOperation("单独返回用户头像和昵称的接口，不保存用户数据")
    @PostMapping("/userInfo")
    public R mpGetUserInfo(@Valid @RequestBody FsUserLoginByMpParam param) {
        try {
            //获取微信用户信息
            WxOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(param.getCode());
            WxOAuth2UserInfo wxMpUser = wxMpService.getOAuth2Service().getUserInfo(wxMpOAuth2AccessToken, null);
            String nickname = wxMpUser.getNickname();
            String headImgUrl = wxMpUser.getHeadImgUrl();
            log.info("仅仅获取用户昵称和头像，nickname: {}，headImgUrl：{}", nickname, headImgUrl);
            Map<String, Object> map = new HashMap<>();
            map.put("nickname", nickname);
            map.put("headImgUrl", headImgUrl);
            return R.ok(map);
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 40163) {
                return R.error(40163, e.getError().getErrorMsg());
            } else {
                return R.error("获取用户信息失败," + e.getMessage());
            }
        }

    }

}
