package com.ruoyi.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.annotations.UserLoginToken;
import com.ruoyi.code.DictConstant;
import com.ruoyi.code.Token;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.page.PageResult;
import com.ruoyi.controller.req.*;
import com.ruoyi.controller.resp.OrderDataResp;
import com.ruoyi.controller.resp.OrderDetailResp;
import com.ruoyi.controller.resp.OrderPageResp;
import com.ruoyi.frequency.customer.entity.Customer;
import com.ruoyi.frequency.customer.service.CustomerService;
import com.ruoyi.frequency.order.entity.Order;
import com.ruoyi.frequency.order.service.OrderService;
import com.ruoyi.frequency.workstype.service.WorksTypeService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.utils.BusinessUtil;
import com.ruoyi.vo.BodyIdReq;
import com.ruoyi.vo.PayVo;
import com.ruoyi.vo.RyController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 订单
 */
@CrossOrigin
@RestController
@RequestMapping("/api/order")
@Api(tags = "订单")
public class ApiOrderController extends RyController {


    @Autowired
    private OrderService orderService;


    @PostMapping("/orderRelease")
    @ApiOperation(value = "发布订单", notes = "发布订单")
    @UserLoginToken
    public ResponseData orderRelease(@RequestBody OrderReleaseReq req) {
        return orderService.orderRelease(req, getUserVo());
    }

    @PostMapping("/customerPay")
    @ApiOperation(value = "表现师发布订单--设计师支付", notes = "表现师发布订单--设计师支付")
    @UserLoginToken
    public ResponseData customerPay(@RequestBody CustomerPayReq req) {
        return orderService.customerPay(req, getUserVo());
    }

    @PostMapping("/orderPage")
    @ApiOperation(value = "订单列表", notes = "订单列表")
    @UserLoginToken
    public ResponseData<PageResult<Page<OrderPageResp>>> orderPage(@RequestBody OrderPageReq req) {
        return orderService.orderPage(req, getUserVo());
    }


    @PostMapping("/orderDetail")
    @ApiOperation(value = "订单详情", notes = "订单详情")
    @UserLoginToken
    public ResponseData<OrderDetailResp> orderDetail(@RequestBody BodyIdReq req) {
        return orderService.orderDetail(req.getId(), getUserVo());
    }


    @PostMapping("/isNeedGetOrderDetail")
    @ApiOperation(value = "是否需要重新调用订单详情接口", notes = "是否需要重新调用订单详情接口")
    @UserLoginToken
    public ResponseData<Boolean> isNeedGetOrderDetail(@RequestBody IsNeedGetOrderDetailReq req) {
        return orderService.isNeedGetOrderDetail(req);
    }


    @PostMapping("/storeOrderReceiving")
    @ApiOperation(value = "表现师接单", notes = "表现师接单")
    @UserLoginToken
    @RepeatSubmit
    public ResponseData storeOrderReceiving(@RequestBody BodyIdReq req) {
        return orderService.storeOrderReceiving(req.getId(), getUserVo());
    }

    @PostMapping("/orderCancel")
    @ApiOperation(value = "取消订单", notes = "取消订单")
    @UserLoginToken
    public ResponseData orderCancel(@RequestBody BodyIdReq req) {
        return orderService.orderCancel(req.getId(), getUserVo());
    }

    @PostMapping("/confirmStore")
    @ApiOperation(value = "确认师傅(表现师)", notes = "确认师傅(表现师)")
    @UserLoginToken
    public ResponseData confirmStore(@RequestBody ConfirmStoreReq req) {
        return orderService.confirmStore(req, getUserVo());
    }

    @PostMapping("/orderAppeal")
    @ApiOperation(value = "订单申诉", notes = "订单申诉")
    @UserLoginToken
    public ResponseData orderAppeal(@RequestBody OrderAppealReq req) {
        return orderService.orderAppeal(req, getUserVo());
    }

    @PostMapping("/cancelOrderAppeal")
    @ApiOperation(value = "取消订单申诉", notes = "取消订单申诉")
    @UserLoginToken
    public ResponseData cancelOrderAppeal(@RequestBody BodyIdReq req) {
        return orderService.cancelOrderAppeal(req, getUserVo());
    }

    @PostMapping("/orderAdjustPricePayCount")
    @ApiOperation(value = "计算订单调价支付定金金额(超出现在价格)", notes = "计算订单调价支付定金金额(超出现在价格)")
    @UserLoginToken
    public ResponseData<PayVo> orderAdjustPricePayCount(@RequestBody OrderAdjustPricePayCountReq req) {
        return orderService.orderAdjustPricePayCount(req, getUserVo());
    }

    @PostMapping("/orderAdjustPrice")
    @ApiOperation(value = "订单调价", notes = "订单调价")
    @UserLoginToken
    public ResponseData orderAdjustPrice(@RequestBody OrderAdjustPriceReq req) {
        return orderService.orderAdjustPrice(req, getUserVo());
    }

    @PostMapping("/orderAdjustPriceConfirm")
    @ApiOperation(value = "订单调价确认", notes = "订单调价确认")
    @UserLoginToken
    public ResponseData orderAdjustPriceConfirm(@RequestBody OrderAdjustPriceConfirmReq req) {
        return orderService.orderAdjustPriceConfirm(req, getUserVo());
    }

    @PostMapping("/orderAdjustPriceRefuse")
    @ApiOperation(value = "订单调价拒绝", notes = "订单调价拒绝")
    @UserLoginToken
    public ResponseData orderAdjustPriceRefuse(@RequestBody RefuseReq req) {
        return orderService.orderAdjustPriceRefuse(req, getUserVo());
    }

    @PostMapping("/orderExtension")
    @ApiOperation(value = "订单延期", notes = "订单延期")
    @UserLoginToken(userTokenPre = {Token.store})
    public ResponseData orderExtension(@RequestBody OrderExtensionReq req) {
        return orderService.orderExtension(req, getUserVo());
    }

    @PostMapping("/orderExtensionCancel/{orderId}")
    @ApiOperation(value = "订单延期取消", notes = "订单延期取消")
    @UserLoginToken(userTokenPre = {Token.store})
    public ResponseData orderExtensionCancel(@PathVariable("orderId") Long orderId) {
        return orderService.orderExtensionCancel(orderId);
    }

    @PostMapping("/orderExtensionConfirm")
    @ApiOperation(value = "订单延期确认", notes = "订单延期确认")
    @UserLoginToken
    public ResponseData orderExtensionConfirm(@RequestBody BodyIdReq req) {
        return orderService.orderExtensionConfirm(req.getId(), getUserVo());
    }

    @PostMapping("/orderExtensionRefuse")
    @ApiOperation(value = "订单延期拒绝", notes = "订单延期拒绝")
    @UserLoginToken
    public ResponseData orderExtensionRefuse(@RequestBody RefuseReq req) {
        return orderService.orderExtensionRefuse(req, getUserVo());
    }

    @PostMapping("/receiveDrawingsAndPay")
    @ApiOperation(value = "支付尾款", notes = "支付尾款")
    @UserLoginToken
    public ResponseData receiveDrawingsAndPay(@RequestBody ReceiveDrawingsAndPayReq req) {
        return orderService.receiveDrawingsAndPay(req, getUserVo());
    }

    @PostMapping("/sampleImagesUpload")
    @ApiOperation(value = "上传大图", notes = "上传大图")
    @UserLoginToken
    public ResponseData sampleImagesUpload(@RequestBody SampleImagesUploadReq req) {
        return orderService.sampleImagesUpload(req, getUserVo());
    }

    @PostMapping("/sampleImagesAddendum")
    @ApiOperation(value = "追加大图", notes = "追加大图")
    @UserLoginToken
    public ResponseData sampleImagesAddendum(@RequestBody SampleImagesUploadReq req) {
        return orderService.sampleImagesAddendum(req, getUserVo());
    }

    @PostMapping("/evaluate")
    @ApiOperation(value = "评价", notes = "评价")
    @UserLoginToken
    public ResponseData evaluate(@RequestBody EvaluateReq req) {
        return orderService.evaluate(req, getUserVo());
    }


    @PostMapping("/evaluateCountStar")
    @ApiOperation(value = "评价计算评分", notes = "评价计算评分")
    @UserLoginToken
    public ResponseData evaluateCountStar(@RequestBody EvaluateReq req) {
        return orderService.evaluateCountStar(req, getUserVo());
    }

    @Autowired
    private WorksTypeService worksTypeService;

    @PostMapping("/projectHallPage")
    @ApiOperation(value = "项目大厅", notes = "项目大厅")
    public ResponseData<PageResult<Page<OrderPageResp>>> projectHallPage(@RequestBody OrderPageReq req) {
        if (ObjectUtil.isNotEmpty(req.getTypeId())) {
            //根据类型id获取三级id
            List<Long> typeIdList = worksTypeService.getIdsByTypeId(req.getTypeId());
            if (typeIdList.isEmpty()) {
                return ResponseData.success(new PageResult<>(new Page<>(req.getPageNo(), req.getPageSize())));
            }
            req.setTypeIds(typeIdList);
        }

        req.setIsHall(true);

        return orderService.orderPage(req, getUserVo());
    }

    @PostMapping("/orderData")
    @ApiOperation(value = "订单列表上方统计", notes = "订单列表上方统计")
    @UserLoginToken()
    public ResponseData<OrderDataResp> orderData(@RequestBody(required = false) OrderPageReq orderPageReq) {
        return orderService.orderData(orderPageReq == null ? new OrderPageReq() : orderPageReq, getUserVo());
    }


    @Autowired
    private BusinessUtil businessUtil;

    @Autowired
    private CustomerService customerService;

    @PostMapping("/calculateFirstAmount")
    @ApiOperation(value = "计算订单首款支付金额", notes = "计算订单首款支付金额")
    @UserLoginToken
    public ResponseData<PayVo> calculateFirstAmount(@RequestBody CalculateFirstAmountReq req) {

        PayVo payVo = new PayVo();
        BigDecimal firstPrice = null;
        BigDecimal maxGivePrice = null;
        if (req.getOrderId() != null) {
            Order order = orderService.getById(req.getOrderId());
            firstPrice = order.getFirstPrice();
            maxGivePrice = order.getFirstGivePrice();
        } else {

            SysDictData dict = businessUtil.getDict(DictConstant.OrderDict.首款支付占比);
            //首款支付比例
            BigDecimal ratio = BigDecimal.ZERO;

            if (dict != null && ObjectUtil.isNotEmpty(dict.getDictValue())) {
                ratio = new BigDecimal(dict.getDictValue());
            }

            firstPrice = req.getAmount().multiply(ratio).setScale(2, BigDecimal.ROUND_HALF_UP);
            maxGivePrice = businessUtil.userMaxGivePrice(getUserVo(), firstPrice);
        }

        payVo.setPrice(firstPrice);
        //赠送最大支付金额
        payVo.setMaxGivePrice(maxGivePrice);

        return ResponseData.success(payVo);
    }

    @PostMapping("/calculateFinalAmount/{orderId}")
    @ApiOperation(value = "计算订单尾款支付金额", notes = "计算订单尾款支付金额")
    public ResponseData<PayVo> calculateFinalAmount(@PathVariable Long orderId) {

        //查询订单
        Order order = orderService.getById(orderId);

        PayVo payVo = new PayVo();

        //尾款支付金额
        BigDecimal finalPrice = order.getAmount().subtract(order.getFirstPrice());
        payVo.setPrice(finalPrice);

        //赠送金额使用最大比例
        SysDictData give_dict = businessUtil.getDict(DictConstant.OrderDict.赠送金额支付占比);
        //首款支付比例
        BigDecimal give_ratio = BigDecimal.ZERO;

        if (give_dict != null && ObjectUtil.isNotEmpty(give_dict.getDictValue())) {
            give_ratio = new BigDecimal(give_dict.getDictValue());
        }

        //赠送最大支付金额
        BigDecimal maxGivePrice = finalPrice.multiply(give_ratio).setScale(2, BigDecimal.ROUND_HALF_UP);

        //查询用户抵用金
        Customer customer = customerService.getById(getUserVo().getUserId());

        maxGivePrice = customer.getGiveBalance().compareTo(maxGivePrice) == 1 ? maxGivePrice : customer.getGiveBalance();

        payVo.setMaxGivePrice(maxGivePrice);

        return ResponseData.success(payVo);
    }

    @PostMapping("/getLakalaPaySuccess")
    @ApiOperation(value = "获取拉卡拉支付是否成功", notes = "获取拉卡拉支付是否成功")
    public ResponseData getLakalaPaySuccess(@RequestBody LakalaPaySuccessReq req) {
        Boolean paySuccess = businessUtil.isPaySuccess(req.getOutOrderNo());
        return ResponseData.success(paySuccess);
    }

}
