package com.ruoyi.app.pay;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.ruoyi.app.pay.dto.WithDrawalDto;
import com.ruoyi.app.service.WalletService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.Auth;
import com.ruoyi.system.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 钱包
 */
@RestController
@RequestMapping("/wallet")
public class WalletController extends BaseController {

    @Autowired
    private WalletService walletService;

    @Autowired
    private IUserWalletService userWalletService;
//    @Autowired
//    private IWithdrawExtendService withdrawExtendService;
//    @Autowired
//    private IRechargeService rechargeService;
    @Autowired
    private IInfoUserService infoUserService;
    @Autowired
    private IUserBillingService userBillingService;
    @Autowired
    private IPosOrderService posOrderService;


    /**
     * 骑手、商家获取钱包明细
     *
     * @param token
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getUserBills")
    @Anonymous
    @Auth
    public AjaxResult getUserBills(@RequestHeader String token, @RequestParam int pageNum, @RequestParam int pageSize, @RequestParam(defaultValue = "") String type) {
        JwtUtil jwtUtil = new JwtUtil();
        String userId = jwtUtil.getusid(token);
        IPage<UserBilling> pageInput = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<UserBilling> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserBilling::getUserId, userId)
                .in(UserBilling::getType, Arrays.asList("0", "1", "2","6"));
       //0 收入,包含分成、抽成返还
        if("0".equals(type)){
            queryWrapper.in( UserBilling::getType, Arrays.asList("0","6"));
        }
        if(!StrUtil.isEmpty(type) && !"0".equals(type)){
            queryWrapper.eq(UserBilling::getType,type);
        }

        queryWrapper.orderByDesc(UserBilling::getId);
        IPage<UserBilling> result = userBillingService.page(pageInput, queryWrapper);

        if (!result.getRecords().isEmpty()) {
            List<String> orderDdIds = result.getRecords().stream().filter(x -> x.getType().equals("0")).map(x -> x.getDdId()).collect(Collectors.toList());
            List<String> withDrawalDdIds = result.getRecords().stream().filter(x -> x.getType().equals("2")).map(UserBilling::getDdId).collect(Collectors.toList());
            List<String> rechargeDdIds = result.getRecords().stream().filter(x -> x.getType().equals("1")).map(UserBilling::getDdId).collect(Collectors.toList());

            // 只有当列表不为空时才执行查询，避免生成无效的 SQL (IN ())
            List<PosOrder> orders;
            if (!orderDdIds.isEmpty()) {
                orders = posOrderService.list(new LambdaQueryWrapper<PosOrder>().in(PosOrder::getDdId, orderDdIds));
            } else {
                orders = new ArrayList<>();
            }

//            List<WithdrawExtend> withdraws;
//            if (!withDrawalDdIds.isEmpty()) {
//                withdraws = withdrawExtendService.list(new LambdaQueryWrapper<WithdrawExtend>().in(WithdrawExtend::getDdId, withDrawalDdIds));
//            } else {
//                withdraws = new ArrayList<>();
//            }
//
//            List<Recharge> recharges;
//            if (!rechargeDdIds.isEmpty()) {
//                recharges = rechargeService.list(new LambdaQueryWrapper<Recharge>().in(Recharge::getDdId, rechargeDdIds));
//            } else {
//                recharges = new ArrayList<>();
//            }

//            result.getRecords().forEach(x -> {
//                if (x.getType().equals("0")) {
//                    orders.stream().filter(o -> x.getDdId().equals(o.getDdId().toString())).findFirst().ifPresent(o -> x.setPayType(o.getPayType()));
//                }
//                if (x.getType().equals("1")) {
//                    recharges.stream().filter(o -> x.getDdId().equals(o.getDdId())).findFirst().ifPresent(o -> x.setPayType(o.getPayType()));
//                }
//                if (x.getType().equals("2")) {
//                    withdraws.stream().filter(o -> x.getDdId().equals(o.getDdId())).findFirst().ifPresent(o -> {
//                        String payType = "1".equals(o.getWithdrawType()) ? "3" : "5";
//                        x.setPayType(payType);
//                    });
//                }
//            });
        }
        return AjaxResult.success(result);

    }

    /**
     * 获取钱包信息
     *
     * @param token
     * @return
     */
    @GetMapping("/getWalletInfo")
    @Anonymous
    @Auth
    public AjaxResult getWalletInfo(@RequestHeader String token) {
        JwtUtil jwtUtil = new JwtUtil();
        String userId = jwtUtil.getusid(token);
        UserWallet userWallet = userWalletService.selectByUserId(Long.valueOf(userId));
        return AjaxResult.success(userWallet);
    }

    /**
     * 骑手、商家获取提现列表
     *
     * @param token
     * @param pageNum
     * @param pageSize
     * @return
     */
//    @GetMapping("/getWithdrawalList")
//    @Anonymous
//    @Auth
//    public AjaxResult getWithdrawalList(@RequestHeader String token, @RequestParam int pageNum, @RequestParam int pageSize) {
//        JwtUtil jwtUtil = new JwtUtil();
//        String userId = jwtUtil.getusid(token);
//        IPage<WithdrawExtend> pageInput = new Page<>(pageNum, pageSize);
//        LambdaQueryWrapper<WithdrawExtend> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(WithdrawExtend::getUserId, userId);
//        queryWrapper.orderByDesc(WithdrawExtend::getId);
//        IPage<WithdrawExtend> result = withdrawExtendService.page(pageInput, queryWrapper);
//        return AjaxResult.success(result);
//    }

    /**
     * 骑手、商家获取充值列表
     *
     * @param token
     * @param pageNum
     * @param pageSize
     * @return
     */
//    @GetMapping("/getRechargeList")
//    @Anonymous
//    @Auth
//    public AjaxResult getRechargeList(@RequestHeader String token, @RequestParam int pageNum, @RequestParam int pageSize) {
//        JwtUtil jwtUtil = new JwtUtil();
//        String userId = jwtUtil.getusid(token);
//        IPage<Recharge> pageInput = new Page<>(pageNum, pageSize);
//        LambdaQueryWrapper<Recharge> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Recharge::getUserId, userId);
//        queryWrapper.ne(Recharge::getStatus, "0");
//        queryWrapper.orderByDesc(Recharge::getId);
//        IPage<Recharge> result = rechargeService.page(pageInput, queryWrapper);
//        return AjaxResult.success(result);
//    }


    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:wallet:query')")
    @GetMapping("/list")
    public TableDataInfo list(UserWallet userWallet) {
        startPage();
        List<UserWallet> list = userWalletService.selectUserWalletList(userWallet);
        if (!list.isEmpty()) {
            List<Long> userIds = list.stream().map(UserWallet::getUserId).collect(Collectors.toList());
            List<InfoUser> users = infoUserService.list(new LambdaQueryWrapper<InfoUser>().in(InfoUser::getUserId, userIds));
            list.forEach(x -> {
                users.stream().filter(u -> u.getUserId().equals(x.getUserId())).findFirst().ifPresent(y -> {
                    String name = StrUtil.isEmpty(y.getNickName()) ? y.getUserName() : y.getNickName();
                    x.setUserName(name);
                    if ("0".equals(y.getUserType())) {
                        x.setUserName(y.getPhone());
                    }
                    x.setUserType(y.getUserType());
                });
            });

        }
        return getDataTable(list);
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:wallet:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        UserWallet result = userWalletService.selectUserWalletById(id);
        if (result != null) {
            InfoUser user = infoUserService.getById(result.getUserId());
            result.setUserName(user.getUserName());
            if ("0".equals(user.getUserType())) {
                result.setUserName(user.getPhone());
            }
            result.setUserType(user.getUserType());
        }
        return success(result);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:wallet:export')")
    @Log(title = "userWallet", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserWallet userWallet) {
        List<UserWallet> list = userWalletService.selectUserWalletList(userWallet);
        if (!list.isEmpty()) {
            List<Long> userIds = list.stream().map(UserWallet::getUserId).collect(Collectors.toList());
            List<InfoUser> users = infoUserService.list(new LambdaQueryWrapper<InfoUser>().in(InfoUser::getUserId, userIds));
            list.forEach(x -> {
                users.stream().filter(u -> u.getUserId().equals(x.getUserId())).findFirst().ifPresent(y -> {
                    String name = StrUtil.isEmpty(y.getNickName()) ? y.getUserName() : y.getNickName();
                    x.setUserName(name);
                    if ("0".equals(y.getUserType())) {
                        x.setUserName(y.getPhone());
                    }
                    x.setUserType(y.getUserType());
                });
            });
        }

        ExcelUtil<UserWallet> util = new ExcelUtil<UserWallet>(UserWallet.class);
        util.exportExcel(response, list, "用户钱包数据");
    }


}
