package com.fs.app.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.hutool.core.date.DateTime;
import com.fs.app.annotation.Login;
import com.fs.app.param.LoginMaWxParam;
import com.fs.app.utils.JwtUtils;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.ServletUtils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyDeptService;
import com.fs.company.service.ICompanyUserService;
import com.fs.store.domain.FsUser;
import com.fs.store.service.IFsUserService;
import com.fs.wx.miniapp.config.WxMaConfiguration;
import com.fs.wx.miniapp.config.WxMaProperties;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
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 java.util.Date;

@Api("微信小程序相关接口（暂废弃，后面再删除）")
@RestController
@RequestMapping(value = "/app/wx/miniapp")
@Slf4j
public class WxCompanyUserController extends AppBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxMaProperties maProperties;

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    RedisCache redisCache;

    @Autowired
    private ICompanyUserService companyUserService;

    @Autowired
    private ICompanyDeptService companyDeptService;

    @Autowired
    private IFsUserService userService;

    @ApiOperation("小程序-授权登录")
    @PostMapping("/loginByMa")
    public R login(@RequestBody LoginMaWxParam param) {
        if (StringUtils.isBlank(param.getCode())) {
            return R.error("code不存在");
        }
        //获取第二个小程序配置，序号从0开始
        final WxMaService wxService = WxMaConfiguration.getMaService(maProperties.getConfigs().get(1).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());
            WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(session.getSessionKey(), param.getEncryptedData(), param.getIv());

            //以下暂时注释，不需要往销售表添加数据
//            CompanyUser companyUser = companyUserService.getCompanyUserByOpenId(session.getOpenid());
//            String ip = IpUtil.getRequestIp();
//
////            // 如果公司id为空（表示可能是该公司的第一位销售管理员），则需要根据电话号码判断是否存在销售，如果不存在则提示
////            if (param.getCompanyId() == null) {
////                if (checkPhone == null) {
////                    throw new CustomException("由于不是管理员，不能直接登录", 401);
////                }
////            }
//            if (companyUser == null) {
//                CompanyUser checkPhone = companyUserService.getCompanyUserByPhone(phoneNoInfo.getPhoneNumber());
//                if (checkPhone != null) {
//                    if (checkPhone.getMaOpenId() == null) {
//                        companyUser = checkPhone;
//                        companyUser.setMaOpenId(session.getOpenid());
//                        companyUser.setUserId(companyUser.getUserId());
//                        companyUser.setUpdateTime(new DateTime());
//                        companyUser.setLoginIp(ip);
//                        companyUserService.updateUserProfile(companyUser);
//                    } else {
//                        throw new CustomException("此手机号用户已存在");
//                    }
//                } else {
//                    //新增
//                    companyUser = new CompanyUser();
//                    companyUser.setUserName(phoneNoInfo.getPhoneNumber());
//                    companyUser.setNickName(userInfo.getNickName() == null ? "微信用户" : userInfo.getNickName());
//                    companyUser.setPhonenumber(phoneNoInfo.getPhoneNumber());
//                    companyUser.setSex(userInfo.getGender());
//                    //密码初始化为123456
//                    String pw = "123456";
//                    companyUser.setPassword(SecurityUtils.encryptPassword(param.getPassword() == null ? pw : param.getPassword()));
//                    companyUser.setCreateTime(new Date());
//                    companyUser.setCompanyId(param.getCompanyId());
//                    companyUser.setParentId(param.getParentCompanyUseId());
//                    companyUser.setMaOpenId(session.getOpenid());
//
//                    //部门信息
//                    CompanyDept dept = companyDeptService.getDefaultCompanyDeptByCompanyId(param.getCompanyId());
//                    if (Objects.nonNull(dept)) {
//                        companyUser.setDeptId(dept.getDeptId());
//                    }
//                    companyUserService.insertUser(companyUser);
//                }
//            } else {
//                CompanyUser companyUserMp = new CompanyUser();
//                companyUserMp.setPhonenumber(phoneNoInfo.getPhoneNumber());
//                companyUserMp.setUserId(companyUser.getUserId());
//                companyUserMp.setUpdateTime(new DateTime());
//                companyUserMp.setLoginIp(ip);
//                companyUserService.updateUserProfile(companyUser);
//            }

            // 添加会员表数据
            FsUser user = userService.selectFsUserByMpOpenId(session.getOpenid());
            if (user != null) {
                //修改
                FsUser userMap = new FsUser();
                userMap.setUserId(user.getUserId());
                userMap.setMpOpenId(session.getOpenid());
                userMap.setUnionId(session.getUnionid());
                userMap.setUpdateTime(new DateTime());
                userMap.setNickname(userInfo.getNickName() != null ? userInfo.getNickName() : "微信用户");
                userMap.setAvatar(userInfo.getAvatarUrl() != null ? userInfo.getAvatarUrl() : null);
                userMap.setPhone(phoneNoInfo.getPhoneNumber());
                userService.updateFsUser(userMap);
            } else {
                //新增
                user = new FsUser();
                user.setNickname(userInfo.getNickName() != null ? userInfo.getNickName() : "微信用户");
                user.setAvatar(userInfo.getAvatarUrl() != null ? userInfo.getAvatarUrl() : null);
                user.setStatus(1);
                user.setMpOpenId(session.getOpenid());
                user.setUnionId(session.getUnionid());
                user.setCreateTime(new Date());
                user.setPhone(phoneNoInfo.getPhoneNumber());
                userService.insertFsUser(user);
            }
            log.info("保存成功的用户信息user: {}, 用户id: {}", user, user.getUserId());
            String token = jwtUtils.generateToken(user.getUserId());
            // 返回一个写死的数据到前端
            return R.ok("登录成功").put("token", token).put("phoneNumber", phoneNoInfo.getPhoneNumber()).put("nickName", "微信用户").put("user", user);
        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            return R.error("授权失败," + e.getMessage());
        }
    }

    @Login(isMiniLogin = true)
    @ApiOperation("获取销售通过小程序登录后的用户信息")
    @GetMapping("/getMaUser")
    public R getUserInfo() {
        try {
            CompanyUser companyUser = companyUserService.selectCompanyUserById(Long.parseLong(getUserId()));
            if (companyUser == null) {
                return R.error(401, "用户信息不存在");
            }
            return R.ok().put("user", companyUser);
        } catch (Exception e) {
            return R.error("操作异常");
        }
    }

    /**
     * 特殊要求：销售小程序临时登录，登录后页面中还有一个之前常用的登录，所以为了区分，token名称不能跟之前的一样
     *
     * @return 用户id
     */
    public String getUserId() {
        String headValue = ServletUtils.getRequest().getHeader("UserToken");
        Claims claims = jwtUtils.getClaimByToken(headValue);
        String userId = claims.getSubject().toString();
        return userId;
    }


}
