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.param.LoginMaWxParam;
import com.fs.app.utils.JwtUtils;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.IpUtil;
import com.fs.company.domain.CompanyDept;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyDeptService;
import com.fs.company.service.ICompanyUserService;
import com.fs.core.security.SecurityUtils;
import com.fs.store.service.IFsUserService;
import com.fs.wx.miniapp.config.WxMaConfiguration;
import com.fs.wx.miniapp.config.WxMaProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.Objects;

@Api("微信小程序相关接口")
@RestController
@RequestMapping(value = "/app/wx/miniapp")
public class WxCompanyUserController extends AppBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxMaProperties maProperties;

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    private ICompanyUserService companyUserService;

    @Autowired
    private ICompanyDeptService companyDeptService;

    @ApiOperation("授权登录")
    @PostMapping("/login")
    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);
            }
            String token = jwtUtils.generateToken(companyUser.getUserId());
            return R.ok("登录成功").put("token", token).put("companyUser", companyUser);
        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            return R.error("授权失败," + e.getMessage());
        }
    }


}
