package cn.pluss.platform.userInfo.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.jfShop.JfShopHandler;
import cn.pluss.platform.mapper.UserPromotionMapper;
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 cn.pluss.platform.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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 javax.annotation.Resource;
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);

        RoleUserInfo role = new RoleUserInfo();
        role.setRoleId(roleId);
        role.setUserId(userInfo.getId());
        //如果没有邀请码默认是平台用户
        UserApp userApp = getSaveUserAppInfo(userInfo);
        userApp.setParentId(new Long(244));
        userApp.setInviteNum(getRandomNum());
        //查找代理
        UserPromotion promotion= getUserPromotionByUserId(String.valueOf(244));
        String parenId=promotion.getUserId().toString();
        UserPromotion promotionNew = new UserPromotion();
        promotionNew.setUserId(userInfo.getId());
        promotionNew.setParentUserId(parenId);
        if(userInfo.getTypeCode().equals("FB")){
            if (promotion.getCurrentFee().compareTo(userInfo.getCurrentFee()) >0||
                    userInfo.getCurrentFee().compareTo(getUserPromotionByUserId("244").getCurrentFee()) < 0){
                MsgException.checkNull(null,"错误的费率信息");
            }
        }

        if(userInfo.getTypeCode().equals("SB")){
            if (promotion.getCurrentFee().compareTo(userInfo.getCurrentFee()) >0||
                    userInfo.getCurrentFee().compareTo(getUserPromotionByUserId("244").getCurrentFee()) < 0){
                MsgException.checkNull(null,"错误的费率信息");
            }
        }
        //如果是普通商户默认费率0.38
        if (userInfo.getTypeCode().equals("MC")){
            promotion.setCurrentFee("0.38");
        }
        promotionNew.setCurrentFee(promotion.getCurrentFee());
        promotionNew.setTypeCode(userInfo.getTypeCode());
        promotionNew.setIsExtend(userInfo.getTypeCode().equals("MC")?"0":"1");
        promotionNew.setCreateTime(new Date());
        userPromotionMapper.insert(promotionNew);
        // 获取当前用户的id保存用户的角色信息
        userInfo = queryUserInfo(userInfo);
        // 保存信息
        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);


    }

    @Autowired
    private UserIpRecordService ipRecordService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void goregister(UserInfo userInfo, UserApp userApp, UserPromotion userPromotion) {
        save(userInfo);

        userApp.setUserId(userInfo.getId());
        userAppService.save(userApp);

        userPromotion.setUserId(userInfo.getId());
        userPromotionMapper.insert(userPromotion);

        ipRecordService.saveRegIp(userInfo.getId() + "", userInfo.getId() + "");
    }

    private String getRandomNum() {
        String inviteNum;
        UserApp condition = new UserApp();

        do {
            inviteNum = StringUtil.genRandomNum(5);
            condition.setInviteNum(inviteNum);
            UserApp userApp = userAppService.queryUserApp(condition);
            if (userApp == null) {
                return inviteNum;
            }
        } while (true);
    }
    @Resource
    private UserPromotionMapper userPromotionMapper;

    private UserPromotion getUserPromotionByUserId(String userId){
        UserPromotion userPromotion = new UserPromotion();
        userPromotion.setUserId(Long.valueOf(userId));
        UserPromotion promotion= userPromotionMapper.selectOne(new QueryWrapper<>(userPromotion));

        if(ObjectUtil.isNotEmpty(promotion)){
            if("MG".equals(promotion.getTypeCode())||"FB".equals(promotion.getTypeCode())||
              "SB".equals(promotion.getTypeCode())||"1".equals(promotion.getIsExtend())||
               "2".equals(promotion.getIsExtend())||"AG".equals(promotion.getTypeCode())){
                return promotion;
            }
        }
        getUserPromotionByUserId(promotion.getParentUserId());
        return promotion;
    }
}
