package com.yiqi.admin.controller.order;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yiqi.app.domain.vo.AppUserInfoVO;
import com.yiqi.app.service.IAppUserService;
import com.yiqi.common.enums.*;
import com.yiqi.common.exception.ServiceException;
import com.yiqi.common.annotation.Log;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.controller.BaseController;
import com.yiqi.common.core.domain.AjaxResult;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.core.page.TableDataInfo;
import com.yiqi.common.utils.CurrencyUtil;
import com.yiqi.common.utils.SecurityUtils;
import com.yiqi.common.utils.bean.BeanUtils;
import com.yiqi.common.utils.poi.ExcelUtil;
import com.yiqi.order.domain.OrderGoods;
import com.yiqi.order.domain.OrderRecharge;
import com.yiqi.order.domain.OrderRechargeInstalment;
import com.yiqi.order.domain.dto.OrderRechargeCreateDTO;
import com.yiqi.order.domain.dto.OrderRechargeQueryDTO;
import com.yiqi.order.domain.vo.*;
import com.yiqi.order.domain.vo.weapp.AppOrderRechargeResultVO;
import com.yiqi.order.service.IOrderRechargeInstalmentService;
import com.yiqi.order.service.IOrderRechargeService;
import com.yiqi.recharge.domain.RechargePasswordCard;
import com.yiqi.recharge.service.IRechargePasswordCardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
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 javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/**
 * 订单充值记录管理Controller
 *
 * @author ruoyi
 * @date 2023-09-27
 */
@Api(tags = "管理后台 - 订单充值记录管理")
@RestController
@RequestMapping(UrlConstants.managerApi + "/recharge/order")
public class OrderRechargeController extends BaseController {
    @Autowired
    private IOrderRechargeService orderRechargeService;

    @Autowired
    IOrderRechargeInstalmentService orderRechargeInstalmentService;

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private IRechargePasswordCardService rechargePasswordCardService;

    /**
     * 查询充值订单列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "查询充值订单列表")
    public TableDataInfo list(OrderRechargeQueryDTO orderRechargeQueryDTO) {
        startPage();
        List<OrderRechargeListVO> list = orderRechargeService.selectOrderRechargeList(orderRechargeQueryDTO);
        return getDataTable(list);
    }


    /**
     * 导出充值订单列表
     */
    @PreAuthorize("@ss.hasPermi('recharge:order:export')")
    @Log(title = "充值订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出充值订单列表")
    public void export(HttpServletResponse response, OrderRechargeQueryDTO orderRechargeQueryDTO) {
        orderRechargeQueryDTO.setPageSizeExport(50000);
        List<OrderRechargeListVO> list = orderRechargeService.selectOrderRechargeList(orderRechargeQueryDTO);
        ExcelUtil<OrderRechargeListVO> util = new ExcelUtil<OrderRechargeListVO>(OrderRechargeListVO.class);
        util.exportExcel(response, list, "充值订单数据");
    }

    /**
     * 获取充值订单详细信息
     */
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取充值订单详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(orderRechargeService.selectOrderRechargeById(id));
    }

    /**
     * 获取零售商品订单详细信息
     */
    @GetMapping(value = "/print/{id}")
    @ApiOperation(value = "充值订单打印")
    public R<OrderRechargePrintVO> getPrintInfo(@PathVariable("id") Long id) {
        OrderRechargePrintVO orderRechargePrintVO = new OrderRechargePrintVO();
        OrderRecharge orderRecharge = orderRechargeService.selectOrderRechargeById(id);
        BeanUtils.copyProperties(orderRecharge, orderRechargePrintVO);
        AppUserInfoVO userInfo = appUserService.getAppUserInfoById(orderRecharge.getAppUserId());
        orderRechargePrintVO.setAppUserInfoVO(userInfo);
        RechargePasswordCard rechargePasswordCard = rechargePasswordCardService.selectTotalBalanceGroupByAppUser(orderRecharge.getAppUserId(), null);
        orderRechargePrintVO.setMemberChangeAmount(CurrencyUtil.add(orderRecharge.getRechargeAmount(), orderRecharge.getWelfareAmount(), orderRecharge.getGiveAmount()));
        orderRechargePrintVO.setMemberAfterBalance(rechargePasswordCard.getTotalBalance());
        orderRechargePrintVO.setMemberBeforeBalance(CurrencyUtil.add(rechargePasswordCard.getTotalBalance(), orderRechargePrintVO.getMemberChangeAmount()));
        return R.ok(orderRechargePrintVO);
    }

    /**
     * 新增充值订单
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('recharge:order:add')")
    @Log(title = "充值订单", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增充值订单")
    public R<OrderPayResultVO> add(@RequestBody OrderRechargeCreateDTO orderRechargeCreateDTO) {
        orderRechargeCreateDTO.setOrderSource(OrderSourceType.OFFLINE.getCode());
        orderRechargeCreateDTO.setOrgId(SecurityUtils.getLoginUser().getOrgId());
        // 2. 创建并处理充值订单
        OrderPayResultVO resultVO = orderRechargeService.createRechargeOrder(orderRechargeCreateDTO);
        return R.ok(resultVO);
    }

    @ApiOperation("根据订单编号获取订单状态")
    @GetMapping(value = "/getOrderPayResult")
    public R<OrderPayResultVO> getOrderPayResult(@RequestParam @ApiParam("订单编号") String orderNo) throws Exception {
        OrderRecharge orderRecharge = orderRechargeService.getOrderRechargeByOrderNo(orderNo);
        if (orderRecharge == null) {
            throw new ServiceException("未查询到订单支付记录");
        }
        if (orderRecharge.getOrderStatus().equals(OrderRechargeStatus.YES_PAY.getCode())) {
            return R.ok(OrderPayResultVO.paySuccess(orderNo));
        }
        if (orderRecharge.getOrderStatus().equals(OrderRechargeStatus.NO_PAY.getCode())) {
            return R.ok(OrderPayResultVO.payWait(orderNo));
        }
        if (orderRecharge.getOrderStatus().equals(OrderRechargeStatus.CANCEL.getCode())) {
            return R.ok(OrderPayResultVO.payError("已取消支付"));
        }
        return R.ok(OrderPayResultVO.payWait(orderNo));
    }

    @ApiOperation("根据订单编号获取订单状态")
    @GetMapping(value = "/getOrderStatusByOrderNo")
    public R<String> getOrderStatusByOrderNo(@RequestParam @ApiParam("订单编号") String orderNo) throws Exception {
        OrderRecharge orderRecharge = orderRechargeService.getOrderRechargeByOrderNo(orderNo);
        if (orderRecharge == null) {
            throw new ServiceException("未查询到订单支付记录");
        }
        return R.ok(orderRecharge.getOrderStatus());
    }

    @ApiOperation("根据订单编号获取订单是否支付完成")
    @GetMapping(value = "/getOrderIsAllPayByOrderNo")
    public R<Boolean> getOrderIsAllPayByOrderNo(@RequestParam @ApiParam("订单编号") String orderNo) throws Exception {
        LambdaQueryWrapper<OrderRechargeInstalment> queryWrapper = new QueryWrapper<OrderRechargeInstalment>().lambda().eq(OrderRechargeInstalment::getOrderNo, orderNo);
        OrderRechargeInstalment orderRechargeInstalment = orderRechargeInstalmentService.getOne(queryWrapper);
        if (orderRechargeInstalment == null) {
            throw new ServiceException("未查询到订单支付记录");
        }
        OrderRecharge orderRecharge = orderRechargeService.getOne(new QueryWrapper<OrderRecharge>().lambda()
                .eq(OrderRecharge::getOrderNo, orderRechargeInstalment.getMstrOrderNo()), false);
        if (orderRecharge == null) {
            throw new ServiceException("未查询到订单");
        }
        // 已支付 总和
        BigDecimal totalPayAmount = orderRechargeInstalmentService.getTotalPayAmount(orderRecharge.getOrderNo());
        if (totalPayAmount == null) {
            return R.ok(false);
        }
        if (orderRecharge.getPayAmount().compareTo(totalPayAmount) < 0) {
            throw new ServiceException("当前支付金额不能超过需要支付的金额");
        }
        return R.ok(orderRecharge.getPayAmount().compareTo(totalPayAmount) == 0);

    }

    /**
     * 查询支付详情明细
     */
    @GetMapping(value = "/getPayDetailById")
    @ApiOperation(value = "查询支付详情明细")
    public R<List<OrderRechargeInstalment>> getPayDetailById(@RequestParam Long id) {
        return R.ok(orderRechargeService.getPayDetailById(id, null));
    }

    /**
     * 查询门店会员充值记录
     */
    @GetMapping(value = "/getRechargeRecordByUserId")
    @ApiOperation(value = "查询门店会员充值记录")
    public R<List<OrderRechargeRecordVO>> getRechargeRecordByUserId(@RequestParam("userId") Long userId) {
        return R.ok(orderRechargeService.getRechargeRecordByUserId(userId));
    }


}
