package com.hfkj.service.spread.impl;

import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.dao.BsUserSpreadPowerMapper;
import com.hfkj.entity.BsUser;
import com.hfkj.entity.BsUserSpreadAccount;
import com.hfkj.entity.BsUserSpreadPower;
import com.hfkj.entity.BsUserSpreadPowerExample;
import com.hfkj.service.spread.BsUserSpreadAccountService;
import com.hfkj.service.spread.BsUserSpreadPowerService;
import com.hfkj.service.user.BsUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @className: BsUserSpreadPowerServiceImpl
 * @author: HuRui
 * @date: 2025/3/31
 **/
@Service("userSpreadPowerService")
public class BsUserSpreadPowerServiceImpl implements BsUserSpreadPowerService {
    @Resource
    private BsUserSpreadPowerMapper userSpreadPowerMapper;
    @Resource
    private BsUserSpreadAccountService userSpreadAccountService;
    @Resource
    private BsUserService userService;

    @Override
    public void editData(BsUserSpreadPower data) {
        data.setUpdateTime(new Date());
        if (data.getId() == null) {
            data.setCreateTime(new Date());
            data.setStatus(1);
            userSpreadPowerMapper.insert(data);
        } else {
            userSpreadPowerMapper.updateByPrimaryKey(data);
        }
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW, rollbackFor= {RuntimeException.class})
    public void open(Long userId) {
        // 查询权限
        BsUserSpreadPower data = getDetailByUser(userId);
        if (data != null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "已开通，请勿重复开通权限");
        }
        BsUserSpreadPower power = new BsUserSpreadPower();
        power.setUserId(userId);
        editData(power);

        // 查询用户详情
        BsUser user = userService.getUser(userId);
        if (user == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到用户信息");
        }

        // 创建推广账户
        userSpreadAccountService.create(userId, user.getPhone());
    }

    @Override
    public BsUserSpreadPower getDetailByUser(Long userId) {
        BsUserSpreadPowerExample example = new BsUserSpreadPowerExample();
        example.createCriteria().andUserIdEqualTo(userId).andStatusNotEqualTo(0);
        List<BsUserSpreadPower> list = userSpreadPowerMapper.selectByExample(example);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

}
