package cn.pluss.platform.userInfo.impl;

import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.jfShop.JfShopHandler;
import cn.pluss.platform.roleUserInfo.RoleUserInfoService;
import cn.pluss.platform.systemConfig.SystemConfigService;
import cn.pluss.platform.user.UserIpRecordService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.MD5Util;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
import java.util.List;

/**
 * 新的实现类
 * @author djh
 */
@Service("userInfoNewService")
@Primary
@Slf4j
@RequiredArgsConstructor
public class UserInfoServiceNewImpl extends BaseUserInfoService {

    @Setter(onMethod_ = {@Autowired,@Lazy})
    private UserInfoService userInfoService;

    @Setter(onMethod_ = {@Autowired})
    private SystemConfigService systemConfigService;

    @Setter(onMethod_ = {@Autowired})
    private RoleUserInfoService roleUserInfoService;

    @Setter(onMethod_ = {@Autowired,@Lazy})
    private JfShopHandler jfShopHandler;

    /**
     * 新的注册可以在没有邀请码的情况下注册，没有上级邀请码，新注册的账号也不会生成邀请码
     * @param userInfo 用户信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(UserInfo userInfo) {
        if (userInfo.getInviteCode() != null) {
            // 如果有邀请码，走老注册逻辑
            userInfoService.register(userInfo);
            return;
        }

        userInfo.setPassword(MD5Util.MD5Encode(userInfo.getPassword(), "utf-8"));
        userInfo.setLoginName(userInfo.getPhone());
        // 验证手机号是否已被使用
        UserInfo queryUserInfo = new UserInfo();
        queryUserInfo.setLoginName(userInfo.getPhone());
        UserInfo checkUserInfo = queryUserInfo(queryUserInfo);
        if (checkUserInfo != null) {
            throw new MsgException("手机号已被注册！");
        }
        // 验证码
        PhoneValidateCode phoneValidateCode = new PhoneValidateCode();
        phoneValidateCode.setPhone(userInfo.getPhone());
        phoneValidateCode = phoneValidateCodeService.queryPhoneValidateCode(phoneValidateCode);

        if (phoneValidateCode == null) {
            throw new MsgException("无效的验证码！");
        }

        if (!phoneValidateCode.getCode().equalsIgnoreCase(userInfo.getCheckCode())) {
            throw new MsgException("无效的验证码！");
        }
        // 判断注册的角色信息
        String roleType = null;
        if ("staff".equalsIgnoreCase(userInfo.getSource())) {
            roleType = "staff";
        } else if ("promoter".equalsIgnoreCase(userInfo.getSource())) {
            roleType = "promoter_role_id";
        }
        Long roleId = null;
        // 获取全部的角色信息
        List<SystemConfig> systemConfigs = systemConfigService.querySystemConfigList(new SystemConfig());
        for (SystemConfig systemConfig : systemConfigs) {
            if (systemConfig.getPropertyKey().equalsIgnoreCase(roleType)) {
                roleId = Long.parseLong(systemConfig.getPropertyValue());
            }
        }
        if (roleId == null) {
            throw new MsgException("获取角色信息错误！");
        }
        userInfo.setCreateTime(new Date());
        saveUserInfo(userInfo);
        // 可能和数据库存储的数据不一致
        userInfo.setCreateTime(null);
        // 获取当前用户的id保存用户的角色信息
        userInfo = queryUserInfo(userInfo);
        RoleUserInfo role = new RoleUserInfo();
        role.setRoleId(roleId);
        role.setUserId(userInfo.getId());
        UserApp userApp = getSaveUserAppInfo(userInfo);
        userApp.setInviteNum(null);
        // 保存信息
        userAppService.save(userApp);
        roleUserInfoService.saveRoleUserInfo(role);
        // 删除验证码
        phoneValidateCodeService.deletePhoneValidateCode(phoneValidateCode);

        //TODO 同步用户到新版积分商城
        jfShopHandler.syncJfShopUser(userApp,userInfo);

        // 可能存在token,
        // ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // String operatorUserId = userInfo.getId() + "";
        // if (requestAttributes != null) {
        //     HttpServletRequest request = requestAttributes.getRequest();
        //     String token = request.getHeader("token");
        //     String myLoginName = request.getHeader("myLoginName");
        //     if (StringUtils.isNotEmpty(token) && StringUtils.isNotEmpty(myLoginName)) {
        //         // 若存在token，则通过userInfo取手机号
        //         UserInfo tokenUi = new UserInfo();
        //         tokenUi.setLoginName(myLoginName);
        //         tokenUi = getOne(new QueryWrapper<>(tokenUi));
        //         if (tokenUi == null) {
        //             throw new MsgException("非法的请求头");
        //         }
        //         UserApp tokenUa = new UserApp().setUserId(tokenUi.getId()).setToken(token);
        //         tokenUa = userAppService.getOne(new QueryWrapper<>(tokenUa));
        //
        //         if (tokenUa == null) {
        //             throw new MsgException("非法的请求头");
        //         }
        //
        //         operatorUserId = userInfo.getId() + "";
        //     }
        // }
        // ipRecordService.saveRegIp(userInfo.getId() + "", operatorUserId);


    }
}
