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.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.fs.app.utils.JwtUtils;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.param.LoginMaWxParam;
import com.fs.common.utils.IpUtil;
import com.fs.common.utils.ServletUtils;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyDeptService;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.ICompanyUserService;
import com.fs.core.config.WxMaConfiguration;
import com.fs.course.config.CourseMaConfig;
import com.fs.his.domain.FsUser;
import com.fs.his.service.IFsUserService;

import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@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;

    @Autowired
    ICompanyService companyService;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @ApiOperation("小程序-授权登录")
    @PostMapping("/loginByMa")
    public R login(@RequestBody LoginMaWxParam param) {
        log.info("=====================进入小程序授权登录, 入参: {}", param);
        if (StringUtils.isBlank(param.getCode())) {
            return R.error("code不存在");
        }
        SysConfig sysConfig3 = sysConfigMapper.selectConfigByConfigKey("courseMa.config");
        List<CourseMaConfig> courseMaConfigs = JSON.parseArray(sysConfig3.getConfigValue(), CourseMaConfig.class);
        if (courseMaConfigs.isEmpty()){
            return R.error("小程序配置为空");
        }
        CourseMaConfig courseMaConfig = courseMaConfigs.get(0);
        //获取第二个小程序配置，序号从0开始
        final WxMaService wxService = WxMaConfiguration.getMaService(courseMaConfig.getAppid());
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(param.getCode());
            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
            this.logger.info(session.getUnionid());
            // 解密
            WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(session.getSessionKey(), param.getEncryptedData(), param.getIv());
            FsUser user = userService.selectFsUserByPhone(phoneNoInfo.getPhoneNumber());

            // 特殊（需求设计：需要根据公司是否开启黑名单来设置会员初始化的状态）
            Company company = null;
            if(param.getCompanyId() != null){
                company = companyService.selectCompanyById(param.getCompanyId());
            }

            // 根据销售后台设置的  是否需要单独注册会员 来判断是否需要设置销售的值
            CompanyUser companyUser = null;
            if(param.getCompanyUserId() != null){
                companyUser = companyUserService.selectCompanyUserById(param.getCompanyUserId());
            }

            String ip = IpUtil.getRequestIp();
            if (user == null) {
                if(StringUtils.isNotEmpty(session.getUnionid())){
                    user = userService.selectFsUserByUnionId(session.getUnionid());
                } else {
                    user = userService.selectFsUserByCourseMaOpenId(session.getOpenid());
                }
                if (user != null) {
                    //修改
                    FsUser userMap = new FsUser();
                    userMap.setUserId(user.getUserId());
                    userMap.setCourseMaOpenId(session.getOpenid());
                    userMap.setUnionId(session.getUnionid());
                    userMap.setUpdateTime(new DateTime());
                    userMap.setNickName(param.getNickname() != null ? param.getNickname() : "微信用户");
                    userMap.setAvatar(param.getAvatar() != null ? param.getAvatar() : null);
                    userMap.setPhone(phoneNoInfo.getPhoneNumber());
                    // 逻辑调整：如果会员已经绑定了销售，直接提示，不让注册-2025年6月16日14点53分
                    if (user.getCompanyUserId() != null && !param.getCompanyUserId().equals(user.getCompanyUserId())){
                        return R.error(406, "该用户已成为其他销售会员");
                    }
                    if(companyUser != null && companyUser.getIsNeedRegisterMember() != null && companyUser.getIsNeedRegisterMember() != 1){
                        user.setCompanyId(param.getCompanyId());
                        user.setCompanyUserId(param.getCompanyUserId());
                    }
                    userService.updateFsUser(userMap);
                } else {
                    //新增
                    user = new FsUser();
                    user.setNickName(param.getNickname() != null ? param.getNickname() : "微信用户");
                    user.setAvatar(param.getAvatar() != null ? param.getAvatar() : null);
                    user.setStatus((company != null ? company.getFsUserIsDefaultBlack() : 0) == 1 ? 0 : 1);
                    user.setCourseMaOpenId(session.getOpenid());
                    user.setUnionId(session.getUnionid());
                    user.setCreateTime(new Date());
                    user.setPhone(phoneNoInfo.getPhoneNumber());
                    if(companyUser != null && companyUser.getIsNeedRegisterMember() != null && companyUser.getIsNeedRegisterMember() != 1){
                        user.setCompanyId(param.getCompanyId());
                        user.setCompanyUserId(param.getCompanyUserId());
                    }
                    userService.insertFsUser(user);
                }
            } else {
                FsUser userMap = new FsUser();
                userMap.setUserId(user.getUserId());
                userMap.setUpdateTime(new DateTime());
                userMap.setPhone(phoneNoInfo.getPhoneNumber());
                userMap.setLastIp(ip);
                if (StringUtils.isNotEmpty(session.getUnionid())) {
                    userMap.setUnionId(session.getUnionid());
                }
                userService.updateFsUser(userMap);
            }
            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;
    }


}
