package com.leromro.core.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.binarywang.wxpay.bean.result.WxPayRefundQueryResult;
import com.leromro.common.annotation.Log;
import com.leromro.common.core.controller.BaseController;
import com.leromro.common.core.domain.AjaxResult;
import com.leromro.common.core.domain.R;
import com.leromro.common.core.page.TableDataInfo;
import com.leromro.common.enums.BusinessType;
import com.leromro.common.utils.SecurityUtils;
import com.leromro.common.utils.poi.ExcelUtil;
import com.leromro.core.domain.MainOrders;
import com.leromro.core.domain.SecondOrder;
import com.leromro.core.domain.dto.*;
import com.leromro.core.domain.vo.*;
import com.leromro.core.facade.OrdersFacade;
import com.leromro.core.service.IAddressService;
import com.leromro.core.service.IMainOrderService;
import com.leromro.core.service.ISecondOrderService;
import com.leromro.core.service.IVolunteerInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 订单主Controller
 *
 * @author ruoyi
 * @date 2025-04-09
 */
@Slf4j
@RestController
@Api(tags = "用户订单")
@RequestMapping("/core/users/orders")
public class OrdersController extends BaseController {
    @Autowired
    private IMainOrderService mainOrderService;
    @Autowired
    private ISecondOrderService secondOrderService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private IVolunteerInfoService volunteerInfoService;
    @Autowired
    private OrdersFacade ordersFacade;


    /**
     * 后台管理web页面订单列表
     */
    @ApiOperation("后台管理web页面订单列表")
    @GetMapping("/web/mainOrderList")
    public TableDataInfo<webMainOrderListVO> webMainOrderList(WebMainOrdersDTO dto) {
        startPage();
        List<webMainOrderListVO> list = mainOrderService.webMainOrderList(dto);
        return getDataTable(list);
    }

    /**
     * 查询订单主列表
     */
    @ApiOperation(" 小程序端：用户查询订单列表")
    @GetMapping("/mainOrderList")
    public TableDataInfo<MainOrdersVO> selectOrderList(String[] orderStatus) {
        startPage();
        Long userId = SecurityUtils.getUserId();
        List<MainOrdersVO> list = mainOrderService.selectByUserId(orderStatus, userId);
        return getDataTable(list);
    }



    /**
     * 获取订单主详细信息
     */
    @ApiOperation("用户获取订单详细信息以及大订单所属小订单")
    @GetMapping("orderInfo/{mainOrderId}")
    public R<MainOrderInfoVO> getMainOrderInfo(@PathVariable("mainOrderId") Long mainOrderId) {
        MainOrderInfoVO mainOrderInfoVO = mainOrderService.selectOrderInfoByUserId(mainOrderId);

        List<SecondOrderInfoVO> secondOrderInfoVOList = secondOrderService.selectSecondOrderInfoVO(mainOrderId);

        mainOrderInfoVO.setSecondOrderList(secondOrderInfoVOList);


        return R.ok(mainOrderInfoVO);
    }

    /**
     * 新增订单主
     */
    @ApiOperation("用户创建订单")
    @Log(title = "创建订单", businessType = BusinessType.INSERT)
    @PostMapping("/createOrder")
    public R<OrderPaymentVO> createOrder(@RequestBody OrderRequestDTO orderRequest) throws Exception {

        return mainOrderService.createOrders(orderRequest);
    }

    /**
     * 用户点击完成订单 , 根据评价算钱。
     */
    @ApiOperation(value = "用户评价小订单",notes = "传入对象参数 包含： secondOrderId, 四个score, userReview, userPicture")
    @PostMapping("/userFinishOrder")
    public AjaxResult userFinish (@RequestBody UserOrderReviewDTO reviewDTO) {

        secondOrderService.userFinish(reviewDTO);
        return AjaxResult.success();
    }


    /**
     * 管理端 订单列表查询
     */
    @ApiOperation(value = "web管理端订单详情信息查询",notes = "传入订单mainOrderId")
    @GetMapping("/web/orderInfo/{mainOrderId}")
    public R<WebMainOrdersInfoVO> webOrderInfo (@PathVariable Long mainOrderId) {
        WebMainOrdersInfoVO webMainOrderInfoVO = mainOrderService.selectWebMainOrderInfoVO(mainOrderId);
        List<SecondOrder> secondOrderList = secondOrderService.list(new LambdaQueryWrapper<SecondOrder>().eq(SecondOrder::getMainOrderId, mainOrderId));
        webMainOrderInfoVO.setSecondOrderList(secondOrderList);
        return R.ok(webMainOrderInfoVO);
    }
/*
    */
/**
     * 后续拆分下单和支付接口
     *//*

    @ApiOperation("用户支付订单")
    @Log(title = "支付订单", businessType = BusinessType.INSERT)
    @PostMapping("/createOrder")
    public AjaxResult PayOrder(@RequestBody OrderRequestDTO orderRequest) {

        return AjaxResult.success();
    }
*/




    /**
     * 支付超时或取消
     */
    @ApiOperation(value = "支付超时或取消",notes = "传入订单mainOrderId")
    @PostMapping("/PayCancel")
    public AjaxResult PayCancel(@RequestBody MainOrders order) {
        return ordersFacade.PayCancel(order);
    }

    /**
     * 订单支付回调
     */
    @PostMapping("/payNotify")
    public String payNotify(@RequestBody String xmlData) {
        return ordersFacade.payNotify(xmlData);
    }

    /**
     * 申请退款回调
     */
    @PostMapping("/refundNotify")
    public String refundNotify(@RequestBody String xmlData) {
        return ordersFacade.refundNotify(xmlData);
    }

    /**
     * <pre>
     * 微信支付-查询退款
     * 应用场景：
     *  提交退款申请后，通过调用该接口查询退款状态。退款有一定延时，用零钱支付的退款20分钟内到账，
     *  银行卡支付的退款3个工作日后重新查询退款状态。
     * 以下四个参数四选一
     *
     * @param transactionId 微信订单号
     * @param outTradeNo    商户订单号
     * @param outRefundNo   商户退款单号
     * @param refundId      微信退款单号
     * @return 退款信息
     */
    @GetMapping("/refundQuery")
    public R<WxPayRefundQueryResult> refundQuery(@RequestParam(required = false) String transactionId,
                                              @RequestParam(required = false) String outTradeNo,
                                              @RequestParam(required = false) String outRefundNo,
                                              @RequestParam(required = false) String refundId) {
        return ordersFacade.refundQuery(transactionId, outTradeNo, outRefundNo, refundId);

    }


    /**
     * 获取结算订单列表
     */
    @ApiOperation("获取结算订单列表")
    @GetMapping("/web/settlementOrderList")
    public TableDataInfo<SettlementOrderListVO> selectSettlementOrderList(SettlementOrderListDTO settlementOrderListDTO) {
        List<SettlementOrderListVO> list = secondOrderService.selectSettlementOrderList(settlementOrderListDTO);
        return getDataTable(list);
    }

    /**
     * 获取订单的结算详情
     */
    @ApiOperation("获取订单的结算详情")
    @GetMapping("/web/settlementOrderDetail/{secondOrderId}")
    public R<SettlementOrderDetailVO> getSettlementOrderDetail(@PathVariable Long secondOrderId) {
        SettlementOrderDetailVO settlementOrderDetailVO = secondOrderService.getSettlementOrderDetail(secondOrderId);
        return R.ok(settlementOrderDetailVO);
    }

    /**
     * 导出订单费用结算列表
     */
    @ApiOperation("导出订单费用结算列表")
    @PreAuthorize("@ss.hasPermi('core:orderSettlementApplication:export')")
    @Log(title = "订单费用结算申请", businessType = BusinessType.EXPORT)
    @PostMapping("/settlementOrderList/export")
    public void export(HttpServletResponse response, SettlementOrderListDTO settlementOrderListDTO)
    {
        List<SettlementOrderListVO> list = secondOrderService.selectSettlementOrderList(settlementOrderListDTO);
        ExcelUtil<SettlementOrderListVO> util = new ExcelUtil<SettlementOrderListVO>(SettlementOrderListVO.class);
        // 如果当前是服务中心，则不导出区域公司结算信息
        // 获取当前用户部门类型
        String areaType = SecurityUtils.getAreaType();
        if ("4".equals(areaType)) {
            // 隐藏区域公司相关结算信息
            util.hideColumn("areaDistributionAmount","areaSettlementStatus", "areaSettlementTime");
        }
        util.exportExcel(response, list, "订单费用结算申请数据");
    }

    /**
     * 区域公司订单抽成结算
     */
    @ApiOperation("区域公司订单抽成结算")
    @PostMapping("/area/settlement")
    public R areaSettlement(@RequestBody @Validated SettlementOrderDTO settlementOrderDTO) {
        secondOrderService.areaSettlement(settlementOrderDTO);
        return R.ok();
    }

    /**
     * 服务中心订单抽成结算
     */
    @ApiOperation("服务中心订单抽成结算")
    @PostMapping("/serviceCentre/settlement")
    public R serviceCentreSettlement(@RequestBody @Validated SettlementOrderDTO settlementOrderDTO) {
        secondOrderService.serviceCentreSettlement(settlementOrderDTO);
        return R.ok();
    }

}
