package com.hotwj.platform.pay.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.hotwj.platform.pay.domain.bo.PayWalletBatchRechargeBo;
import com.hotwj.platform.pay.domain.bo.PayWalletBo;
import com.hotwj.platform.pay.domain.bo.PayWalletFreezeBo;
import com.hotwj.platform.pay.domain.vo.PayCompanyWalletBalanceVo;
import com.hotwj.platform.pay.domain.vo.PayWalletVo;
import com.hotwj.platform.pay.service.IPayWalletService;
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/wallet")
@Tag(name = "会员钱包", description = "会员钱包管理")
public class PayWalletController extends BaseController {

    private final IPayWalletService payWalletService;

    /**
     * 查询会员钱包列表
     */
    @SaCheckPermission("platform:wallet:list")
    @GetMapping("/list")
    @Operation(summary = "分页查询会员钱包列表")
    public TableDataInfo<PayWalletVo> list(PayWalletBo bo, PageQuery pageQuery) {
        return payWalletService.queryPageList(bo, pageQuery);
    }

    /**
     * 分页查询企业钱包余额列表
     */
    @SaCheckPermission("platform:wallet:list")
    @GetMapping("/companyBalanceList")
    @Operation(summary = "分页查询企业钱包余额列表")
    public TableDataInfo<PayCompanyWalletBalanceVo> companyBalanceList(
            @Parameter(name = "keyword", description = "企业名/负责人/手机号关键词")
            @RequestParam(required = false) String keyword,
            PageQuery pageQuery) {
        return payWalletService.queryCompanyWalletPage(keyword, pageQuery);
    }

    /**
     * 总部端按钱包ID查询钱包余额
     */
    @SaCheckPermission("platform:wallet:query")
    @GetMapping("/headquarters/balance")
    @Operation(summary = "总部端按钱包ID查询钱包余额")
    public R<PayWalletVo> headquartersBalance(
            @NotNull(message = "钱包ID不能为空")
            @Parameter(name = "walletId", description = "钱包ID", required = true, example = "1")
            @RequestParam Long walletId) {
        ensureHeadquartersAccess();
        return R.ok(payWalletService.queryById(walletId));
    }

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

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

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

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

    /**
     * 删除会员钱包
     *
     * @param ids 主键串
     */
    @SaCheckPermission("platform:wallet: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(payWalletService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 总部批量充值企业钱包
     */
    @SaCheckPermission("platform:wallet:recharge")
    @Log(title = "会员钱包", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping("/batchRechargeCompany")
    @Operation(summary = "总部批量充值企业钱包")
    public R<Integer> batchRechargeCompany(@Validated @RequestBody PayWalletBatchRechargeBo bo) {
        return R.ok(payWalletService.batchRechargeCompanyWallet(bo));
    }

    /**
     * 冻结/解冻钱包
     */
    @SaCheckPermission("platform:wallet:edit")
    @Log(title = "会员钱包", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping("/freeze")
    @Operation(summary = "冻结/解冻钱包")
    public R<Void> freeze(@Validated @RequestBody PayWalletFreezeBo bo) {
        return toAjax(payWalletService.changeFreezeStatus(bo));
    }

    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("非总部端用户无权访问");
        }
    }
}
