package com.seer.teach.pay.admin.withdrawal.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.pay.admin.withdrawal.controller.request.PayMerchantBankAccountPageReq;
import com.seer.teach.pay.admin.withdrawal.controller.request.PayMerchantBankAccountReq;
import com.seer.teach.pay.admin.withdrawal.controller.response.PayMerchantBankAccountResp;
import com.seer.teach.pay.admin.withdrawal.convert.PayMerchantBankAccountConvert;
import com.seer.teach.pay.admin.withdrawal.service.IAdminPayMerchantBankAccountService;
import com.seer.teach.pay.entity.PayMerchantBankAccountEntity;
import com.seer.teach.pay.service.IPayMerchantBankAccountService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class AdminPayMerchantBankAccountServiceImpl implements IAdminPayMerchantBankAccountService {

    private final IPayMerchantBankAccountService payMerchantBankAccountService;
    
    /**
     * 默认账户标识：是
     */
    private static final Integer DEFAULT_ACCOUNT_YES = 1;
    
    /**
     * 默认账户标识：否
     */
    private static final Integer DEFAULT_ACCOUNT_NO = 0;

    @Override
    public Boolean create(PayMerchantBankAccountReq req) {
        log.info("新增商家收款账户，参数: {}", req);
        PayMerchantBankAccountEntity entity = PayMerchantBankAccountConvert.INSTANCE.convertReqToEntity(req);
        entity.setUserId(StpUtil.getLoginIdAsInt());
        
        // 如果设置为默认账户，则将该用户下的其他账户设为非默认
        if (DEFAULT_ACCOUNT_YES.equals(req.getIsDefault())) {
            payMerchantBankAccountService.update(new LambdaUpdateWrapper<PayMerchantBankAccountEntity>()
                    .set(PayMerchantBankAccountEntity::getIsDefault, DEFAULT_ACCOUNT_NO)
                    .eq(PayMerchantBankAccountEntity::getUserId, entity.getUserId()));
        }
        
        boolean result = payMerchantBankAccountService.save(entity);
        log.info("新增商家收款账户结果: {}", result);
        return result;
    }

    @Override
    public Boolean update(PayMerchantBankAccountReq req) {
        log.info("修改商家收款账户，参数: {}", req);
        if (Objects.isNull(req.getId())) {
            log.warn("修改商家收款账户失败，ID不能为空");
            return false;
        }
        PayMerchantBankAccountEntity entity = payMerchantBankAccountService.getById(req.getId());
        if (Objects.isNull(entity)) {
            log.warn("修改商家收款账户失败，未找到该收款账户，ID: {}", req.getId());
            return false;
        }
        // 将请求参数映射到实体对象
        PayMerchantBankAccountConvert.INSTANCE.updateEntityFromReq(req, entity);
        
        // 如果设置为默认账户，则将该用户下的其他账户设为非默认
        if (DEFAULT_ACCOUNT_YES.equals(req.getIsDefault())) {
            payMerchantBankAccountService.update(new LambdaUpdateWrapper<PayMerchantBankAccountEntity>()
                    .set(PayMerchantBankAccountEntity::getIsDefault, DEFAULT_ACCOUNT_NO)
                    .eq(PayMerchantBankAccountEntity::getUserId, entity.getUserId())
                    .ne(PayMerchantBankAccountEntity::getId, entity.getId()));
        }
        
        boolean result = payMerchantBankAccountService.updateById(entity);
        log.info("修改商家收款账户结果: {}", result);
        return result;
    }

    @Override
    public Boolean delete(Integer id) {
        log.info("删除商家收款账户，ID: {}", id);
        boolean result = payMerchantBankAccountService.removeById(id);
        log.info("删除商家收款账户结果: {}", result);
        return result;
    }

    @Override
    public PayMerchantBankAccountResp getById(Integer id) {
        log.info("根据ID查询商家收款账户，ID: {}", id);
        PayMerchantBankAccountEntity entity = payMerchantBankAccountService.getById(id);
        if (Objects.isNull(entity)) {
            log.info("根据ID查询商家收款账户结果: 未找到该收款账户");
            return null;
        }
        PayMerchantBankAccountResp resp = PayMerchantBankAccountConvert.INSTANCE.convertEntityToResp(entity);
        log.info("查询商家收款账户结果: {}", resp);
        return resp;
    }

    @Override
    public PageListBean<PayMerchantBankAccountResp> pageList(PayMerchantBankAccountPageReq req) {
        // 查询当前登录用户的收款账户
        Integer userId = StpUtil.getLoginIdAsInt();
        log.info("分页查询商家收款账户，参数: {}", req);
        LambdaQueryWrapper<PayMerchantBankAccountEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PayMerchantBankAccountEntity::getUserId, userId)
                .eq(Objects.nonNull(req.getAccountType()), PayMerchantBankAccountEntity::getAccountType, req.getAccountType())
                .likeRight(Objects.nonNull(req.getAccountName()), PayMerchantBankAccountEntity::getAccountName, req.getAccountName())
                .eq(Objects.nonNull(req.getAccountStatus()), PayMerchantBankAccountEntity::getAccountStatus, req.getAccountStatus())
                .orderByDesc(PayMerchantBankAccountEntity::getCreateTime);

        IPage<PayMerchantBankAccountEntity> page = new Page<>(req.getPageNo(), req.getPageSize());
        IPage<PayMerchantBankAccountEntity> resultPage = payMerchantBankAccountService.page(page, queryWrapper);

        PageListBean<PayMerchantBankAccountResp> respPage = PageConverterUtils.convertPageListBean(resultPage, PayMerchantBankAccountConvert.INSTANCE::convertEntityListToRespList);

        log.info("分页查询商家收款账户结果，共{}条", respPage.getTotal());
        return respPage;
    }

    @Override
    public List<PayMerchantBankAccountResp> getListByUserId(Integer userId) {
        log.info("根据用户ID查询商家收款账户列表，用户ID: {}", userId);
        List<PayMerchantBankAccountEntity> list = payMerchantBankAccountService.list(
                new LambdaQueryWrapper<PayMerchantBankAccountEntity>()
                        .eq(PayMerchantBankAccountEntity::getUserId, userId)
                        .orderByDesc(PayMerchantBankAccountEntity::getCreateTime)
        );

        if (CollectionUtil.isEmpty(list)) {
            log.info("根据用户ID查询商家收款账户列表结果: 无数据");
            return CollectionUtil.newArrayList();
        }

        List<PayMerchantBankAccountResp> respList = PayMerchantBankAccountConvert.INSTANCE.convertEntityListToRespList(list);

        log.info("根据用户ID查询商家收款账户列表结果，共{}条", respList.size());
        return respList;
    }
}