package com.fs.app.controller.store;

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.fs.app.controller.AppBaseController;
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.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.hisStore.domain.FsUserScrm;
import com.fs.hisStore.service.IFsUserScrmService;
import com.fs.wx.miniapp.config.WxMaProperties;
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 javax.validation.Valid;
import java.util.Date;

@Api("微信小程序相关接口")
@RestController
@RequestMapping(value = "/store/app/wx/miniapp/m")
@Slf4j
public class WxCompanyUserScrmControllerCopy 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 IFsUserScrmService userService;

    @Autowired
    ICompanyService companyService;

    @ApiOperation("小程序-授权登录")
    @PostMapping("/loginByMa")
    public R login(@RequestBody @Valid LoginMaWxParam param) {
        log.info("=====================进入小程序授权登录, 入参: {}", param);
        if (StringUtils.isBlank(param.getCode())) {
            return R.error("code不存在");
        }
        //根据前端传的appId来切换小程序配置
        final WxMaService wxService = WxMaConfiguration.getMaService(param.getAppId());
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(param.getCode());
            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
            this.logger.info(session.getUnionid());

            if (StringUtils.isEmpty(session.getOpenid())){
                return R.error("登陆失败，openid未授权，请稍后再试!");
            }

            // 手机号信息
            WxMaPhoneNumberInfo phoneNoInfo = new WxMaPhoneNumberInfo();
            FsUserScrm user = null;
            if (param.getAuthType()==1){
                phoneNoInfo = wxService.getUserService().getPhoneNoInfo(session.getSessionKey(), param.getEncryptedData(), param.getIv());
                if (StringUtils.isEmpty(phoneNoInfo.getPhoneNumber())){
                    return R.error("授权失败，请联系客服！");
                }
                user = userService.selectFsUserByPhone(phoneNoInfo.getPhoneNumber());
            }

            // 特殊（需求设计：需要根据公司是否开启黑名单来设置会员初始化的状态）
            Company company = companyService.selectCompanyById(param.getCompanyId());
            if (company==null || company.getStatus()==0){
                return R.error("注册失败团队已停用，或不存在！");
            }



            // 根据销售后台设置的  是否需要单独注册会员 来判断是否需要设置销售的值
            CompanyUser companyUser = companyUserService.selectCompanyUserById(param.getCompanyUserId());;
            if(companyUser == null || companyUser.getStatus().equals("1")){
                return R.error("注册失败客服已停用，或不存在！");
            }

            String ip = IpUtil.getRequestIp();
            if (user == null) {
                if(StringUtils.isNotEmpty(session.getUnionid())){
                    user = userService.selectFsUserByUnionId(session.getUnionid());
                } else {
                    user = userService.selectFsUserByMaOpenId(session.getOpenid());
                }
                if (user != null) {
                    //修改
                    FsUserScrm userMap = new FsUserScrm();
                    userMap.setUserId(user.getUserId());
                    userMap.setMaOpenId(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(500, "该用户("+user.getUserId() + ")已成为其他销售会员");
                    }
//                    if((companyUser.getIsAllowedAllRegister() == null || companyUser.getIsAllowedAllRegister() == 1)
//                            && companyUser.getIsNeedRegisterMember() != null && companyUser.getIsNeedRegisterMember() != 1){
//                        userMap.setCompanyId(param.getCompanyId());
//                        userMap.setCompanyUserId(param.getCompanyUserId());
//                    }
                    userService.updateFsUser(userMap);
                } else {
                    //新增
                    user = new FsUserScrm();
//                    user.setNickname(param.getNickname() != null ? param.getNickname() : "微信用户");
//                    user.setAvatar(param.getAvatar() != null ? param.getAvatar() : null);
                    user.setStatus(1);
                    user.setMaOpenId(session.getOpenid());
                    user.setUnionId(session.getUnionid());
                    user.setCreateTime(new Date());
                    user.setPhone(phoneNoInfo.getPhoneNumber());
                    if((companyUser.getIsAllowedAllRegister() == null || companyUser.getIsAllowedAllRegister() == 1)
                            && companyUser.getIsNeedRegisterMember() != null && companyUser.getIsNeedRegisterMember() != 1){
                        user.setCompanyId(param.getCompanyId());
                        user.setCompanyUserId(param.getCompanyUserId());
                    }
//                    redisCache.setCacheObject("");
                    userService.insertFsUser(user);
                }
            } else {
                FsUserScrm userMap = new FsUserScrm();
                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());
        }
    }


}
