package com.fs.app.controller;

import cn.hutool.core.date.DateTime;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.OrderUtils;
import com.fs.store.param.LoginMpWxParam;
import com.fs.common.utils.IpUtil;
import com.fs.wx.miniapp.config.WxMaConfiguration;
import com.fs.wx.miniapp.config.WxMaProperties;
import com.fs.store.domain.FsUser;
import com.fs.store.param.LoginWxParam;
import com.fs.store.service.IFsUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Synchronized;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
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.*;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import me.chanjar.weixin.common.error.WxErrorException;

import java.util.Date;
import java.util.regex.Pattern;

import static com.fs.until.PhoneUtil.encryptPhone;

/**
 * 微信小程序用户接口
 *
 */
@Api("微信接口")
@RestController
@RequestMapping(value="/app/wx")
public class WxUserController extends AppBaseController{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private WxMaProperties maProperties;

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private IFsUserService userService;

    /**
     * 登陆接口
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public R login( @RequestBody LoginMpWxParam param) {
        Pattern PHONE_PATTERN = Pattern.compile("^1\\d{10}$");
        if (StringUtils.isBlank(param.getCode())) {
            return R.error("code不存在");
        }
        final WxMaService wxService = WxMaConfiguration.getMaService(maProperties.getConfigs().get(0).getAppid());
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(param.getCode());
            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
            // 解密
            WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(session.getSessionKey(), param.getEncryptedData(), param.getIv());
            FsUser user=userService.selectFsUserByMaOpenId(session.getOpenid());
            String ip = IpUtil.getRequestIp();
            if(user==null){
                FsUser checkPhone = null;
                //先看手机是否是11位，再加密查询
                if (PHONE_PATTERN.matcher(phoneNoInfo.getPhoneNumber().trim()).matches()){
                    String phone = encryptPhone(phoneNoInfo.getPhoneNumber());
                    logger.info("登录，用户为空，电话明文：" + phoneNoInfo.getPhoneNumber() + "电话密文：" + phone);
                    checkPhone = userService.selectFsUserByPhone(phone);
                }
                //查询手机号是否存在，如果存在，更新
                if(checkPhone!=null){
                    if(checkPhone.getMaOpenId()==null){
                        user=checkPhone;
                        FsUser userMap=new FsUser();
                        userMap.setMaOpenId(session.getOpenid());
                        userMap.setUserId(checkPhone.getUserId());
                        userMap.setUpdateTime(new DateTime());
                        userMap.setLastIp(ip);
                        userService.updateFsUser(userMap);
                    }
                    else{
                        throw new CustomException("此手机号已存在");
                    }
                }
                else{
                    //写入
                    user=new FsUser();
                    if(StringUtils.isNotEmpty(param.getUserCode())){
                        FsUser tuiUser=userService.selectFsUserByUserCode(param.getUserCode());
                        if(tuiUser!=null){
                            user.setIsPromoter(1);
                            user.setSpreadUserId(tuiUser.getUserId());
                        }
                    }
                    user.setUserCode(OrderUtils.genUserCode());
                    user.setPhone(phoneNoInfo.getPhoneNumber());
                    logger.info("登录:手机存在电话明文：" + phoneNoInfo.getPhoneNumber());
                    if (PHONE_PATTERN.matcher(phoneNoInfo.getPhoneNumber().trim()).matches()){
                        user.setPhone(encryptPhone(phoneNoInfo.getPhoneNumber()));
                        logger.info("登录:手机存在电话密文：" + user.getPhone());
                    }
                    user.setUsername(phoneNoInfo.getPhoneNumber());
                    user.setNickname("微信用户");
                    user.setStatus(1);
                    user.setMaOpenId(session.getOpenid());
                    user.setLastIp(ip);
                    user.setIsWeixinAuth(0);
                    user.setCreateTime(new Date());
                    userService.insertFsUser(user);
                }
           }
           else{
               FsUser userMap=new FsUser();
               userMap.setPhone(phoneNoInfo.getPhoneNumber());
               logger.info("用户存在，电话明文：" + phoneNoInfo.getPhoneNumber());
               if (PHONE_PATTERN.matcher(phoneNoInfo.getPhoneNumber().trim()).matches()){
                   user.setPhone(encryptPhone(phoneNoInfo.getPhoneNumber()));
                   logger.info("用户存在，电话密文：：" + user.getPhone());
               }
               userMap.setUserId(user.getUserId());
               userMap.setUpdateTime(new DateTime());
               userMap.setLastIp(ip);
               userService.updateFsUser(userMap);
           }
           String token = jwtUtils.generateToken(user.getUserId());
           return R.ok("登录成功").put("token",token).put("user", user);
        } catch (WxErrorException e) {
            return R.error("授权失败,"+e.getMessage());
        }
    }

    @ApiOperation("小程序登录")
    @PostMapping("/loginByMiniApp")
    public R loginByMiniApp( @RequestBody LoginMpWxParam param) {
        logger.info("小程序登录 {}",param);
        return userService.loginByMiniApp(param);
    }
    @ApiOperation("公众号登录")
    @PostMapping("/loginByMp")
    @Synchronized
    public R loginByMp( @RequestBody LoginWxParam param) {
        if (StringUtils.isBlank(param.getCode())) {
            return R.error("code不存在");
        }
        try{

            WxOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(param.getCode());
            WxOAuth2UserInfo wxMpUser = wxMpService.getOAuth2Service().getUserInfo(wxMpOAuth2AccessToken, null);
            //如果开启了UnionId
            FsUser user=userService.selectFsUserByMpOpenId(wxMpUser.getOpenid());
            String ip = IpUtil.getRequestIp();
            if(user==null){
                user=userService.selectFsUserByPhone(wxMpUser.getUnionId());
                if(user!=null){
                    FsUser userMap=new FsUser();
                    userMap.setUserId(user.getUserId());
                    userMap.setUpdateTime(new DateTime());
                    userMap.setLastIp(ip);
                    user.setMpOpenId(wxMpUser.getOpenid());
                    userService.updateFsUser(userMap);
                }
                else{
                    user=new FsUser();
                    user.setUsername("");
                    user.setNickname(wxMpUser.getNickname());
                    user.setStatus(1);
                    user.setMpOpenId(wxMpUser.getOpenid());
                    user.setLastIp(ip);
                    user.setCreateTime(new Date());
                    user.setAvatar(wxMpUser.getHeadImgUrl());
                    if(StringUtils.isNotEmpty(wxMpUser.getUnionId())){
                        user.setUnionId(wxMpUser.getUnionId());
                    }
                    userService.insertFsUser(user);
                }
            }
            else{
                FsUser userMap=new FsUser();
                userMap.setUserId(user.getUserId());
                userMap.setUpdateTime(new DateTime());
                userMap.setLastIp(ip);
                if(StringUtils.isNotEmpty(wxMpUser.getUnionId())){
                    userMap.setUnionId(wxMpUser.getUnionId());
                }
                userService.updateFsUser(userMap);
            }
            String token = jwtUtils.generateToken(user.getUserId());
            return R.ok("登录成功").put("token",token).put("user", user);
        }
        catch (WxErrorException e){
            if(e.getError().getErrorCode()==40163){
                return R.error(40163,e.getError().getErrorMsg());
            }
            else{
                return R.error("授权失败,"+e.getMessage());
            }
        }

    }

}
