package com.yonge.cooleshow.portal.controller;

import com.yonge.cooleshow.mall.common.api.CommonPage;
import com.yonge.cooleshow.mall.common.api.CommonResult;
import com.yonge.cooleshow.mall.common.enums.OrderCacheEnum;
import com.yonge.cooleshow.mbg.model.OmsOrder;
import com.yonge.cooleshow.portal.domain.ConfirmOrderResult;
import com.yonge.cooleshow.portal.domain.OmsOrderDetail;
import com.yonge.cooleshow.portal.domain.OrderParam;
import com.yonge.cooleshow.portal.service.OmsPortalOrderService;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.util.StringUtil;
import com.yonge.toolset.payment.util.DistributedLock;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 订单管理Controller
 * Created by macro on 2018/8/30.
 */
@Controller
@Api(tags = "OmsPortalOrderController 订单管理")
@RequestMapping("/order")
public class OmsPortalOrderController {
    @Autowired
    private OmsPortalOrderService portalOrderService;



    @Value("${message.debugMode}")
    private boolean debugMode;

    @Autowired
    private RedissonClient redissonClient;

    @ApiOperation("根据购物车信息生成确认单")
    @RequestMapping(value = "/generateConfirmOrder", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<ConfirmOrderResult> generateConfirmOrder(@RequestParam String cartIds) {
        List<Long> list = StringUtil.toLongList(cartIds);
        ConfirmOrderResult confirmOrderResult = portalOrderService.generateConfirmOrder(list);
        return CommonResult.success(confirmOrderResult);
    }


    @ApiOperation("再来一单")
    @RequestMapping(value = "/oneOrder", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<ConfirmOrderResult> anotherList(@RequestParam Long orderId) {
        OmsOrder order = portalOrderService.getOrderById(orderId);
        List<Long> list = StringUtil.toLongList(order.getCartIds());
        if (CollectionUtils.isEmpty(list)) {
            return CommonResult.failed("库存不足");
        }
        ConfirmOrderResult confirmOrderResult = portalOrderService.generateConfirmOrder(list);
        return CommonResult.success(confirmOrderResult);
    }

    @ApiOperation("根据购物车信息生成订单")
    @RequestMapping(value = "/generateOrder", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult generateOrder(@RequestBody OrderParam orderParam) {
        Map<String, Object> result = portalOrderService.generateOrder(orderParam);
        return CommonResult.success(result, "下单成功");
    }

    @ApiOperation("用户支付成功的回调")
    @RequestMapping(value = "/paySuccess", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult paySuccess(@RequestParam Long orderId,@RequestParam Integer payType) {
        Integer count = portalOrderService.paySuccess(orderId,payType);
        return CommonResult.success(count, "支付成功");
    }

    @ApiOperation("自动取消超时订单")
    @RequestMapping(value = "/cancelTimeOutOrder", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult cancelTimeOutOrder() {
        portalOrderService.cancelTimeOutOrder();
        return CommonResult.success(null);
    }

    @ApiOperation("取消单个超时订单")
    @RequestMapping(value = "/cancelOrder", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult cancelOrder(Long orderId) {
        portalOrderService.sendDelayMessageCancelOrder(orderId);
        return CommonResult.success(null);
    }

    @ApiOperation("按状态分页获取用户订单列表")
    @ApiImplicitParam(name = "status", value = "订单状态：-1->全部；0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭",
            defaultValue = "-1", allowableValues = "-1,0,1,2,3,4", paramType = "query", dataType = "string")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<OmsOrderDetail>> list(@RequestParam String status,
                                                   @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                   @RequestParam(required = false, defaultValue = "5") Integer pageSize) {
        CommonPage<OmsOrderDetail> orderPage = portalOrderService.list(status,pageNum,pageSize);
        return CommonResult.success(orderPage);
    }

    @ApiOperation("根据ID获取订单详情")
    @RequestMapping(value = "/detail/{orderId}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<OmsOrderDetail> detail(@PathVariable Long orderId) {
        OmsOrderDetail orderDetail = portalOrderService.detail(orderId);
        return CommonResult.success(orderDetail);
    }


    @ApiOperation("根据订单号获取订单详情")
    @RequestMapping(value = "/detail/sn/{orderSn}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<OmsOrderDetail> detail(@PathVariable String orderSn) {
        OmsOrderDetail orderDetail = portalOrderService.detail(orderSn);
        return CommonResult.success(orderDetail);
    }

    @ApiOperation("用户取消订单")
    @RequestMapping(value = "/cancelUserOrder", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult cancelUserOrder(Long orderId) {
        OmsOrder omsOrder = portalOrderService.getOrderById(orderId);
        if (omsOrder == null) {
            return CommonResult.failed("未找到订单");
        }

        DistributedLock.of(redissonClient)
                       .runIfLockCanGet(OrderCacheEnum.LOCK_ORDER_NO_MALL.getRedisKey(omsOrder.getOrderSn())
                               , () -> {
                                   portalOrderService.cancelOrder(orderId, "用户取消订单", null);
                               }, 60L, TimeUnit.SECONDS);
        return CommonResult.success(null);
    }

    @ApiOperation("用户确认收货")
    @RequestMapping(value = "/confirmReceiveOrder", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult confirmReceiveOrder(Long orderId) {
        OmsOrder omsOrder = portalOrderService.getOrderById(orderId);
        if (omsOrder == null) {
            return CommonResult.failed("未找到订单");
        }

        DistributedLock.of(redissonClient)
                       .runIfLockCanGet(OrderCacheEnum.LOCK_ORDER_NO_MALL.getRedisKey(omsOrder.getOrderSn())
                               , () -> portalOrderService.confirmReceiveOrder(orderId), 60L, TimeUnit.SECONDS);
        return CommonResult.success(null);
    }

    @ApiOperation("用户删除订单")
    @RequestMapping(value = "/deleteOrder", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult deleteOrder(Long orderId) {
        portalOrderService.deleteOrder(orderId);
        return CommonResult.success(null);
    }

    @ApiOperation("用户支付成功的回调")
    @RequestMapping(value = "/paySuccess/test", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult paySuccessTest(@RequestParam Long orderId,@RequestParam Integer payType) {
        if (!debugMode) {
            return CommonResult.failed("当前环境不可使用");
        }
        OmsOrder omsOrder = portalOrderService.getOrderById(orderId);
        if (omsOrder == null) {
            return CommonResult.failed("未找到订单");
        }

        DistributedLock.of(redissonClient)
                       .runIfLockCanGet(OrderCacheEnum.LOCK_ORDER_NO_MALL.getRedisKey(omsOrder.getOrderSn())
                               , () -> {
                                       if (omsOrder.getStatus() == 0 || omsOrder.getStatus() == 6) {
                                           portalOrderService.paySuccess(orderId, payType);

                                       } else {
                                           throw new BizException("订单已支付或已取消");
                                       }
                               }, 60L, TimeUnit.SECONDS);
        return CommonResult.success("支付成功");
    }

    @ApiOperation("用户取消订单")
    @GetMapping(value = "/cancelUserOrder/test")
    @ResponseBody
    public CommonResult cancelUserOrderTest(@RequestParam Long orderId) {

        if (!debugMode) {
            return CommonResult.failed("当前环境不可使用");
        }

        OmsOrder omsOrder = portalOrderService.getOrderById(orderId);
        if (omsOrder == null) {
            return CommonResult.failed("未找到订单");
        }

        DistributedLock.of(redissonClient)
                       .runIfLockCanGet(OrderCacheEnum.LOCK_ORDER_NO_MALL.getRedisKey(omsOrder.getOrderSn())
                               , () -> {
                                   portalOrderService.cancelOrder(orderId, "用户取消订单", null);
                               }, 60L, TimeUnit.SECONDS);
        return CommonResult.success(null);
    }
}
