package com.ylx.web.controller.massage;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylx.common.core.controller.BaseController;
import com.ylx.common.core.domain.R;
import com.ylx.common.core.domain.model.WxLoginUser;
import com.ylx.common.utils.SecurityUtils;
import com.ylx.massage.domain.ProductOrderInfo;
import com.ylx.massage.domain.dto.*;
import com.ylx.massage.domain.vo.*;
import com.ylx.massage.service.IProductOrderInfoService;
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.*;

/**
 * 商品订单控制器
 */
@Slf4j
@RestController
@RequestMapping("/product/order")
public class ProductOrderController extends BaseController {

    @Autowired
    private IProductOrderInfoService productOrderInfoService;

    /**
     * 创建商品订单
     *
     * @param request 订单创建请求
     * @return R<String> 订单编号
     */
    @PostMapping("/create")
    public R<String> createProductOrder(@RequestBody ProductOrderCreateRequest request) {
        try {
            log.info("创建商品订单，请求参数：{}", JSON.toJSONString(request));
            String orderNo = productOrderInfoService.createProductOrder(request);
            log.info("商品订单创建成功，订单编号：{}", orderNo);
            return R.ok(orderNo);
        } catch (Exception e) {
            log.error("商品订单创建失败：{}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 支付订单
     *
     * @param productOrderPayRequest 订单支付请求
     * @return R 订单支付结果
     */
    @PostMapping("/pay")
    public R payProductOrder(@RequestBody ProductOrderPayRequest productOrderPayRequest) {
        try {
            log.info("支付订单，请求参数的值：{}", JSON.toJSONString(productOrderPayRequest));
            return productOrderInfoService.payOrder(productOrderPayRequest);
        } catch (Exception e) {
            log.error("订单支付失败：{}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 查询我的订单列表（分页）
     *
     * @param page   分页参数
     * @param openId 用户openId
     * @return R<Page < ProductOrderListVo>> 订单分页列表
     */
    @GetMapping("/list")
    public R<Page<ProductOrderListVo>> getProductOrderList(Page<ProductOrderListVo> page, @RequestParam("openId") String openId) {
        try {
            log.info("查询用户订单列表，openId：{}", openId);
            Page<ProductOrderListVo> result = productOrderInfoService.getProductOrderList(page, openId);
            return R.ok(result);
        } catch (Exception e) {
            log.error("查询用户订单列表失败：{}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 查询商品订单详情
     *
     * @param orderNo 订单编号
     * @return R<ProductOrderDetailResponse> 订单详情
     */
    @GetMapping("/detail")
    public R<ProductOrderDetailResponse> getProductOrderDetail(@RequestParam("orderNo") String orderNo) {
        try {
            // 当前登录用户信息
            WxLoginUser wxLoginUser = SecurityUtils.getWxLoginUser();
            String openId = wxLoginUser.getCOpenid();
            log.info("查询商品订单详情，openId：{}，订单编号：{}", openId, orderNo);
            ProductOrderDetailResponse detail = productOrderInfoService.getProductOrderDetail(orderNo, openId);
            return R.ok(detail);
        } catch (Exception e) {
            log.error("查询商品订单详情失败：{}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 取消订单
     *
     * @param request 取消订单请求
     * @return R 取消结果
     */
    @PostMapping("/cancel")
    public R<?> cancelProductOrder(@RequestBody ProductOrderCancelRequest request) {
        try {
            log.info("取消商品订单，请求参数：{}", JSON.toJSONString(request));
            return productOrderInfoService.cancelOrder(request);
        } catch (Exception e) {
            log.error("取消商品订单失败：{}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 订单确认收货
     * @param dto
     * @return R
     */
    @ApiOperation("订单确认收货接口")
    @PutMapping("/confirm/receipt")
    public R confirmReceipt(@Validated @RequestBody ProductOrderOperateDTO dto) {
        this.productOrderInfoService.confirmReceipt(dto);
        return R.ok();
    }

    @PreAuthorize("@ss.hasPermi('product:order:query')")
    @PostMapping("/admin/page")
    @ApiOperation("积分订单管理分页接口")
    public R<Page<ProductOrderPageItemVo>> adminPage(Page<ProductOrderInfo> page, @RequestBody ProductOrderPageDTO dto) {
        Page<ProductOrderPageItemVo> pageData = this.productOrderInfoService.adminPage(page, dto);
        return R.ok(pageData);
    }

    @PreAuthorize("@ss.hasPermi('product:order:query')")
    @GetMapping("/admin/page/stats")
    @ApiOperation("积分订单管理统计接口")
    public R<ProductOrderCountVo> adminPageStats() {
        ProductOrderCountVo vo = this.productOrderInfoService.adminPageStats();
        return R.ok(vo);
    }

    @PreAuthorize("@ss.hasPermi('product:order:query')")
    @GetMapping("/admin/detail/{orderId}")
    @ApiOperation("积分订单管理详情接口")
    public R<ProductOrderDetailAdminVo> getOrderDetailForAdmin(@PathVariable Long orderId) {
        ProductOrderDetailAdminVo detailVO = productOrderInfoService.getOrderDetailForAdmin(orderId);
        return R.ok(detailVO);
    }

    @PreAuthorize("@ss.hasPermi('product:order:edit')")
    @PutMapping("/admin/edit/logisticsNo")
    @ApiOperation("积分订单管理详情修改物流单号接口")
    public R editLogisticsNo(@Validated @RequestBody ProductOrderEditLogisticsNo dto) {
        this.productOrderInfoService.editLogisticsNo(dto);
        return R.ok();
    }

    @PreAuthorize("@ss.hasPermi('product:order:edit')")
    @PutMapping("/admin/edit/consignees/info")
    @ApiOperation("积分订单管理详情修改收货人信息接口")
    public R editConsigneesInfo(@Validated @RequestBody ProductOrderOperateDTO dto) {
        this.productOrderInfoService.editConsigneesInfo(dto);
        return R.ok();
    }

}