package com.ruoyi.web.bst;

import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.bst.areaJoin.domain.enums.AreaJoinPermission;
import com.ruoyi.bst.order.domain.OrderQuery;
import com.ruoyi.bst.order.domain.OrderVO;
import com.ruoyi.bst.order.domain.dto.OrderDeductDTO;
import com.ruoyi.bst.order.domain.dto.OrderEndDTO;
import com.ruoyi.bst.order.domain.dto.OrderRefundDTO;
import com.ruoyi.bst.order.domain.dto.OrderUpdatePriceDTO;
import com.ruoyi.bst.order.domain.dto.OrderVerifyDTO;
import com.ruoyi.bst.order.domain.enums.OrderReturnType;
import com.ruoyi.bst.order.domain.vo.OrderEndVO;
import com.ruoyi.bst.order.service.OrderAssembler;
import com.ruoyi.bst.order.service.OrderService;
import com.ruoyi.bst.order.service.OrderValidator;
import com.ruoyi.common.annotation.Log;
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.enums.LogBizType;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 订单Controller
 *
 * @author ruoyi
 * @date 2025-03-24
 */
@RestController
@RequestMapping("/bst/order")
public class OrderController extends BaseController
{
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderAssembler orderAssembler;

    @Autowired
    private OrderValidator orderValidator;

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('bst:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(OrderQuery query)
    {
        startPage();
        startOrderBy();
        query.setScope(true);
        query.addAreaPermission(AreaJoinPermission.ORDER_VIEW.getCode());
        List<OrderVO> list = orderService.selectOrderList(query);
        orderAssembler.assembleOrderDeviceList(list);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('bst:order:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OrderQuery query)
    {
        query.setScope(true);
        query.addAreaPermission(AreaJoinPermission.ORDER_VIEW.getCode());
        List<OrderVO> list = orderService.selectOrderList(query);
        ExcelUtil<OrderVO> util = new ExcelUtil<OrderVO>(OrderVO.class);
        util.exportExcel(response, list, "订单数据");
    }

    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('bst:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id,
        @RequestParam(required = false, defaultValue = "false") Boolean assembleOrderDeviceList)
    {
        OrderVO order = orderService.selectOrderById(id, true);
        if (assembleOrderDeviceList) {
            orderAssembler.assembleOrderDeviceList(Collections.singletonList(order));
        }
        return success(order);
    }

    /**
     * 结束订单（辅助还车）
     */
    @Log(title = "结束订单（辅助还车）", businessType = BusinessType.UPDATE, bizIdName = "arg0", bizType = LogBizType.ORDER)
    @PreAuthorize("@ss.hasPermi('bst:order:end')")
    @PutMapping("/end")
    public AjaxResult end(@RequestBody @Validated OrderEndDTO dto) {
        if (!orderValidator.canOperate(dto.getOrderId())) {
            return error("您无权结束ID为" + dto.getOrderId() + "的订单");
        }
        dto.setReturnType(OrderReturnType.AUXILIARY.getCode());
        dto.setEndReason("管理员【" + getNickName() + "】辅助还车");
        dto.setRequiredIot(false);
        if (dto.getNeedDispatchFee() == null) {
            dto.setNeedDispatchFee(false);
        }
        OrderEndVO vo = orderService.endOrder(dto);
        if (vo.getDb() > 0) {
            return success(vo);
        }
        return error("订单关闭失败");
    }

    @Log(title = "订单退款", businessType = BusinessType.UPDATE, bizIdName = "arg0", bizType = LogBizType.ORDER)
    @PreAuthorize("@ss.hasPermi('bst:order:refund')")
    @PutMapping("/refund")
    public AjaxResult refund(@RequestBody @Validated OrderRefundDTO dto) {
        if (!orderValidator.canOperate(dto.getOrderId())) {
            return error("您无权退款ID为" + dto.getOrderId() + "的订单");
        }
        dto.setUserId(getUserId());
        dto.setUserName(getNickName());
        int count = orderService.refund(dto);
        if (count == 0) {
            return error("退款失败");
        }
        return success(count);
    }

    /**
     * 还车审核
     */
    @Log(title = "还车审核", businessType = BusinessType.UPDATE, bizIdName = "arg0", bizType = LogBizType.ORDER)
    @PreAuthorize("@ss.hasPermi('bst:order:verify')")
    @PutMapping("/verify")
    public AjaxResult verify(@RequestBody @Validated OrderVerifyDTO dto) {
        if (!orderValidator.canOperate(dto.getId())) {
            return error("您无权审核ID为" + dto.getId() + "的订单");
        }
        return toAjax(orderService.verify(dto));
    }

    /**
     * 押金抵扣
     */
    @Log(title = "押金抵扣", businessType = BusinessType.UPDATE, bizIdName = "arg0", bizType = LogBizType.ORDER)
    @PreAuthorize("@ss.hasPermi('bst:order:deduct')")
    @PutMapping("/deduct")
    public AjaxResult deduct(@RequestBody @Validated OrderDeductDTO dto) {
        if (!orderValidator.canOperate(dto.getId())) {
            return error("您无权押金抵扣ID为" + dto.getId() + "的订单");
        }
        dto.setIsAdmin(true);
        return toAjax(orderService.deduct(dto));
    }

    /**
     * 改价
     */
    @Log(title = "订单改价", businessType = BusinessType.UPDATE, bizIdName = "arg0", bizType = LogBizType.ORDER)
    @PreAuthorize("@ss.hasPermi('bst:order:updatePrice')")
    @PutMapping("/updatePrice")
    public AjaxResult updatePrice(@RequestBody @Validated OrderUpdatePriceDTO dto) {
        if (!orderValidator.canOperate(dto.getId())) {
            return error("您无权改价ID为" + dto.getId() + "的订单");
        }
        dto.setUserId(getUserId());
        return toAjax(orderService.updatePrice(dto));
    }

}
