
package com.tmerclub.cloud.user.service.impl;

import com.alibaba.fastjson2.JSON;
import com.tmerclub.cloud.api.auth.constant.SysTypeEnum;
import com.tmerclub.cloud.api.auth.dto.AuthAccountDTO;
import com.tmerclub.cloud.api.auth.dto.AuthAccountWithSocialDTO;
import com.tmerclub.cloud.api.auth.dto.ThirdApiAbutmentUserDto;
import com.tmerclub.cloud.api.auth.feign.AccountFeignClient;
import com.tmerclub.cloud.api.payment.constant.PaySysType;
import com.tmerclub.cloud.api.payment.feign.AllinpayFeignClient;
import com.tmerclub.cloud.api.platform.feign.ConfigFeignClient;
import com.tmerclub.cloud.common.bean.PaySettlementConfig;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.constant.StatusEnum;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.util.IpHelper;
import com.tmerclub.cloud.user.bo.mongo.MongoUserScoreLogBO;
import com.tmerclub.cloud.user.constant.LevelTypeEnum;
import com.tmerclub.cloud.user.mapper.UserMapper;
import com.tmerclub.cloud.user.model.User;
import com.tmerclub.cloud.user.model.UserExtension;
import com.tmerclub.cloud.user.service.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.Objects;

/**
 * @author xxw
 * @version 1.0
 * @description: 第三方接口对接
 * @since 2023/12/18 15:03
 */
@Service
public class ThirdApiAbutmentServiceImpl implements ThirdApiAbutmenService {
    @Autowired
    private  UserService userService;
    @Autowired
    private UserMapper userMapper;
    @DubboReference
    private AccountFeignClient accountFeignClient;
    @Autowired
    private UserExtensionService userExtensionService;
    @Autowired
    private UserLevelService userLevelService;
    @DubboReference
    private ConfigFeignClient configFeignClient;
    @DubboReference
    private AllinpayFeignClient allinpayFeignClient;
    @Autowired
    private UserScoreLogService userScoreLogService;

    @Override
    public void regiserUser(ThirdApiAbutmentUserDto thirdApiAbutmentUserDto) {

        AuthAccountDTO authAccountDTO = getAuthAccountDTO(null, null, thirdApiAbutmentUserDto.getUserId());
        AuthAccountWithSocialDTO authAccountWithSocialDTO = new AuthAccountWithSocialDTO();
        authAccountWithSocialDTO.setAuthAccount(authAccountDTO);
        User user = new User();
        user.setUserId(thirdApiAbutmentUserDto.getUserId());
        user.setLevel(Constant.USER_LEVEL_INIT);
        user.setLevelType(LevelTypeEnum.ORDINARY_USER.value());
        user.setStatus(1);
        user.setPhone(authAccountDTO.getPhone());
        user.setNickName(thirdApiAbutmentUserDto.getNickName());
        // 默认开启商品个性化推荐
        user.setProdRecommendation(1);
        // 这里保存之后才有用户id
        userMapper.save(user);

        // 保存统一账户信息
        ServerResponseEntity<Long> serverResponse = accountFeignClient.saveAccountWithSocial(authAccountWithSocialDTO);
        // 抛异常回滚
        if (!serverResponse.isSuccess()) {
            throw new LuckException(serverResponse.getMsg());
        }

        UserExtension userExtension = new UserExtension();
        userExtension.setBalance(0L);
        userExtension.setActualBalance(0L);
        userExtension.setAllinpayBalance(0L);
        userExtension.setAllinpayActualBalance(0L);
        userExtension.setAllinpayRealNameSet(0);
        userExtension.setAllinpayPhoneBind(0);
        userExtension.setAllinpayPayPwdSet(0);
        userExtension.setAllinpayProtocolSign(0);
        userExtension.setAllinpayPayAcctBind(0);
        userExtension.setGrowth(0);
        userExtension.setLevel(1);
        userExtension.setLevelType(0);
        userExtension.setScore(0L);
        userExtension.setVersion(0);
        userExtension.setSignDay(0);
        // 上面保存这边才能拿到userId
        userExtension.setUserId(user.getUserId());

        userExtensionService.save(userExtension);
        //用户注册成功后初始化用户数据
        MongoUserScoreLogBO mongoUserScoreLogBO = userLevelService.initUserInfoAndLevelInfo(userExtension, Constant.USER_LEVEL_INIT, LevelTypeEnum.ORDINARY_USER.value(), authAccountDTO.getPhone());

        // 判断是否开启通联支付
        boolean isAllinpay = false;
        String data = configFeignClient.getConfig(Constant.PAY_SETTLEMENT_CONFIG).getData();
        if (!ObjectUtils.isEmpty(data)) {
            PaySettlementConfig config = JSON.parseObject(data, PaySettlementConfig.class);
            isAllinpay = config.getPaySettlementType() != null
                    && Objects.equals(config.getPaySettlementType(), PaySysType.ALLINPAY.value());
        }
        if (isAllinpay) {
            // 若开通则同步创建通联个人会员
            allinpayFeignClient.batchCreatePersonalMember(Collections.singletonList(user.getUserId().toString()));
        }
        if (Objects.nonNull(mongoUserScoreLogBO)) {
            userScoreLogService.saveToMongdb(mongoUserScoreLogBO);
        }
    }

    private static AuthAccountDTO getAuthAccountDTO(String mobile, String password, Long userId) {
        AuthAccountDTO authAccountDTO = new AuthAccountDTO();
        authAccountDTO.setCreateIp(IpHelper.getIpAddr());
        authAccountDTO.setPassword(password);
        authAccountDTO.setPhone(mobile);
        authAccountDTO.setIsAdmin(0);
        authAccountDTO.setSysType(SysTypeEnum.ORDINARY.value());
        authAccountDTO.setStatus(1);
        authAccountDTO.setUserId(userId);
        return authAccountDTO;
    }

    @Override
    public void updateUser(ThirdApiAbutmentUserDto thirdApiAbutmentUserDto) {
        User user = new User();
        user.setUserId(thirdApiAbutmentUserDto.getUserId());
        user.setNickName(thirdApiAbutmentUserDto.getNickName());
        userService.update(user);
    }

    @Override
    public void disableUser(Long userId) {
        User user = new User();
        user.setUserId(userId);
        user.setStatus(StatusEnum.DISABLE.value());
        userService.update(user);
    }
}
