package com.zsElectric.boot.business.service.impl;

import com.zsElectric.boot.business.mapper.UserAccountLogMapper;
import com.zsElectric.boot.business.model.entity.UserAccountLog;
import com.zsElectric.boot.common.constant.SystemConstants;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsElectric.boot.business.mapper.UserAccountMapper;
import com.zsElectric.boot.business.service.UserAccountService;
import com.zsElectric.boot.business.model.entity.UserAccount;
import com.zsElectric.boot.business.model.form.UserAccountForm;
import com.zsElectric.boot.business.model.query.UserAccountQuery;
import com.zsElectric.boot.business.model.vo.UserAccountVO;
import com.zsElectric.boot.business.converter.UserAccountConverter;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 个人账户服务实现类
 *
 * @author zsElectric
 * @since 2025-12-12 10:20
 */
@Service
@RequiredArgsConstructor
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    private final UserAccountConverter userAccountConverter;
    
    private final UserAccountLogMapper userAccountLogMapper;

    /**
    * 获取个人账户分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<UserAccountVO>} 个人账户分页列表
    */
    @Override
    public IPage<UserAccountVO> getUserAccountPage(UserAccountQuery queryParams) {
        Page<UserAccountVO> pageVO = this.baseMapper.getUserAccountPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取个人账户表单数据
     *
     * @param id 个人账户ID
     * @return 个人账户表单数据
     */
    @Override
    public UserAccountForm getUserAccountFormData(Long id) {
        UserAccount entity = this.getById(id);
        return userAccountConverter.toForm(entity);
    }
    
    /**
     * 新增个人账户
     *
     * @param formData 个人账户表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveUserAccount(UserAccountForm formData) {
        UserAccount entity = userAccountConverter.toEntity(formData);
        return this.save(entity);
    }
    
    /**
     * 更新个人账户
     *
     * @param id   个人账户ID
     * @param formData 个人账户表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateUserAccount(Long id,UserAccountForm formData) {
        UserAccount entity = userAccountConverter.toEntity(formData);
        return this.updateById(entity);
    }
    
    /**
     * 删除个人账户
     *
     * @param ids 个人账户ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteUserAccounts(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的个人账户数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }
    /**
     * 更新账户余额并记录日志
     *
     * @param userId 用户ID
     * @param changeAmount 变更金额（正数为增加，负数为减少）
     * @param changeType 变更类型（1-增加，2-减少）
     * @param changeNote 变更备注
     * @param changeId 变更记录编号（订单号或充电订单号）
     * @return 更新后的用户账户信息
     */
    @Override
    public UserAccount updateAccountBalanceAndLog(Long userId, BigDecimal changeAmount,
                                                  Integer changeType, String changeNote, Long changeId) {
        // 查询用户账户
        UserAccount userAccount = this.getById(userId);
        
        // 创建账户变动日志
        UserAccountLog accountLog = new UserAccountLog();
        accountLog.setBeforeBalance(userAccount.getBalance());
        
        // 计算变更后余额
        BigDecimal finalBalance;
        if (SystemConstants.CHANGE_TYPE_ADD.equals(changeType)) {
            // 增加余额
            finalBalance = userAccount.getBalance().add(changeAmount);
        } else {
            // 减少余额
            finalBalance = userAccount.getBalance().subtract(changeAmount);
        }
        
        // 更新账户余额
        userAccount.setBalance(finalBalance);
        this.updateById(userAccount);
        
        // 保存变动日志
        accountLog.setUserId(userId);
        accountLog.setChangeType(changeType);
        accountLog.setChangeNote(changeNote);
        accountLog.setChangeId(changeId);
        accountLog.setAccountType(SystemConstants.ACCOUNT_TYPE_PERSONAL);
        accountLog.setChangeBalance(finalBalance);
        userAccountLogMapper.insert(accountLog);
        
        return userAccount;
    }

}
