package com.hotwj.platform.pay.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.hotwj.platform.pay.domain.bo.PayWalletTransactionBo;
import com.hotwj.platform.pay.domain.vo.PayWalletTransactionVo;
import com.hotwj.platform.pay.service.IPayWalletTransactionService;
import com.hotwj.platform.resourceManagement.company.service.ISysUserLoginPortService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 会员钱包流水
 *
 * @author shihongwei
 * @date 2026-05-08
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/platform/walletTransaction")
@Tag(name = "会员钱包流水", description = "会员钱包流水管理")
public class PayWalletTransactionController extends BaseController {

    private final IPayWalletTransactionService payWalletTransactionService;

    /**
     * 查询会员钱包流水列表
     */
    @SaCheckPermission("platform:walletTransaction:list")
    @GetMapping("/list")
    @Operation(summary = "分页查询会员钱包流水列表")
    public TableDataInfo<PayWalletTransactionVo> list(PayWalletTransactionBo bo, PageQuery pageQuery) {
        return payWalletTransactionService.queryPageList(bo, pageQuery);
    }

    /**
     * 企业端查询当前企业钱包流水明细
     */
    @GetMapping("/company/current/list")
    @Operation(summary = "企业端分页查询当前企业钱包流水明细")
    public TableDataInfo<PayWalletTransactionVo> currentCompanyList(PayWalletTransactionBo bo, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        boolean isEnterprise = loginUser != null && ISysUserLoginPortService.ENTERPRISE_PORT.equals(loginUser.getLoginPort());
        boolean isAdmin = LoginHelper.isSuperAdmin() || LoginHelper.isTenantAdmin();
        if (!isEnterprise && !isAdmin) {
            throw new ServiceException("非企业端用户无权访问");
        }
        Long companyId = loginUser == null ? null : loginUser.getCompanyId();
        if (companyId == null) {
            throw new ServiceException("当前登录企业信息不存在");
        }
        return payWalletTransactionService.queryCompanyWalletPage(companyId, bo, pageQuery);
    }

    /**
     * 总部端查询指定企业钱包流水明细
     */
    @GetMapping("/company/list")
    @Operation(summary = "总部端分页查询指定企业钱包流水明细")
    public TableDataInfo<PayWalletTransactionVo> companyList(
            @NotNull(message = "企业ID不能为空")
            @Parameter(name = "companyId", description = "企业ID", required = true, example = "1")
            @RequestParam Long companyId,
            PayWalletTransactionBo bo, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        boolean isHeadquarters = loginUser != null && ISysUserLoginPortService.HEADQUARTERS_PORT.equals(loginUser.getLoginPort());
        boolean isAdmin = LoginHelper.isSuperAdmin() || LoginHelper.isTenantAdmin();
        if (!isHeadquarters && !isAdmin) {
            throw new ServiceException("非总部端用户无权访问");
        }
        return payWalletTransactionService.queryCompanyWalletPage(companyId, bo, pageQuery);
    }

    /**
     * 总部端按钱包ID分页查询钱包流水
     */
    @SaCheckPermission("platform:walletTransaction:list")
    @GetMapping("/headquarters/list")
    @Operation(summary = "总部端按钱包ID分页查询钱包流水")
    public TableDataInfo<PayWalletTransactionVo> headquartersList(
            @NotNull(message = "钱包ID不能为空")
            @Parameter(name = "walletId", description = "钱包ID", required = true, example = "1")
            @RequestParam Long walletId,
            PayWalletTransactionBo bo, PageQuery pageQuery) {
        ensureHeadquartersAccess();
        PayWalletTransactionBo queryBo = bo == null ? new PayWalletTransactionBo() : bo;
        queryBo.setWalletId(walletId);
        return payWalletTransactionService.queryPageList(queryBo, pageQuery);
    }

    /**
     * 导出会员钱包流水列表
     */
    @SaCheckPermission("platform:walletTransaction:export")
    @Log(title = "会员钱包流水", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @Operation(summary = "导出会员钱包流水列表")
    public void export(PayWalletTransactionBo bo, HttpServletResponse response) {
        List<PayWalletTransactionVo> list = payWalletTransactionService.queryList(bo);
        ExcelUtil.exportExcel(list, "会员钱包流水", PayWalletTransactionVo.class, response);
    }

    /**
     * 获取会员钱包流水详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("platform:walletTransaction:query")
    @GetMapping("/{id}")
    @Operation(summary = "获取会员钱包流水详细信息")
    public R<PayWalletTransactionVo> getInfo(@NotNull(message = "主键不能为空")
                                             @Parameter(name = "id", description = "主键", required = true, example = "1")
                                             @PathVariable Long id) {
        return R.ok(payWalletTransactionService.queryById(id));
    }

    /**
     * 新增会员钱包流水
     */
    @SaCheckPermission("platform:walletTransaction:add")
    @Log(title = "会员钱包流水", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    @Operation(summary = "新增会员钱包流水")
    public R<Void> add(@Validated(AddGroup.class) @RequestBody PayWalletTransactionBo bo) {
        return toAjax(payWalletTransactionService.insertByBo(bo));
    }

    /**
     * 修改会员钱包流水
     */
    @SaCheckPermission("platform:walletTransaction:edit")
    @Log(title = "会员钱包流水", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    @Operation(summary = "修改会员钱包流水")
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody PayWalletTransactionBo bo) {
        return toAjax(payWalletTransactionService.updateByBo(bo));
    }

    /**
     * 删除会员钱包流水
     *
     * @param ids 主键串
     */
    @SaCheckPermission("platform:walletTransaction:remove")
    @Log(title = "会员钱包流水", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Operation(summary = "删除会员钱包流水")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @Parameter(name = "ids", description = "主键串", required = true, example = "1,2,3")
                          @PathVariable Long[] ids) {
        return toAjax(payWalletTransactionService.deleteWithValidByIds(List.of(ids), true));
    }

    private void ensureHeadquartersAccess() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        boolean isHeadquarters = loginUser != null && ISysUserLoginPortService.HEADQUARTERS_PORT.equals(loginUser.getLoginPort());
        boolean isAdmin = LoginHelper.isSuperAdmin() || LoginHelper.isTenantAdmin();
        if (!isHeadquarters && !isAdmin) {
            throw new ServiceException("非总部端用户无权访问");
        }
    }
}
