/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: OrderController
 * @Package cn.freemud.controller
 * @Description:
 * @author: liming.guo
 * @date: 2018/5/17 17:14
 * @version V1.0
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
package cn.freemud.controller;

import cn.freemud.annotations.IsConvertEN;
import cn.freemud.annotations.LogIgnore;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.entities.vo.*;
import cn.freemud.entities.vo.encircle.CreateReserveOrderVo;
import cn.freemud.entities.vo.encircle.EncircleReserveBaseVo;
import cn.freemud.handler.OrderReportJobHandler;
import cn.freemud.monitorcenter.tools.HealthUtil;
import cn.freemud.service.EncircleOrderService;
import cn.freemud.service.MCCafeOrderService;
import cn.freemud.service.OrderAdapterService;
import cn.freemud.service.Orderservice;
import cn.freemud.service.impl.MallOrderServiceImpl;
import cn.freemud.utils.LogUtil;
import cn.freemud.utils.ResponseUtil;
import cn.freemud.xxljob.OrderCountJobHandler;
import com.freemud.application.sdk.api.log.ApiAnnotation;
import com.freemud.application.sdk.api.log.LogParams;
import com.freemud.application.sdk.api.ordercenter.request.OrderCountReqs;
import com.freemud.application.sdk.api.ordercenter.response.OrderCountResp;
import com.freemud.application.sdk.api.ordercenter.service.OrderSdkService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


@Slf4j
@RequestMapping("/order")
@RestController
@Validated
public class OrderController {

    @Autowired
    private Orderservice orderservice;
    @Autowired
    private OrderAdapterService orderAdapterService;
    @Autowired
    private EncircleOrderService encircleOrderService;
    @Autowired
    private MallOrderServiceImpl mallOrderService;
    @Autowired
    private MCCafeOrderService mcCafeOrderService;
    @Autowired
    private OrderReportJobHandler orderReportJobHandler;
    @Autowired
    private OrderCountJobHandler orderCountJobHandler;

    /**
     * 创建订单之前校验前面排队的订单数
     */
    @LogIgnore(logMessage = "checkBeforeCreateOrder")
    @PostMapping("/checkBeforeCreateOrder")
    public BaseResponse checkBeforeCreateOrder(@Validated @LogParams @RequestBody CheckBeforeCreateOrderRequestVo checkBeforeCreateOrderRequestVo) {
        long start = System.currentTimeMillis();
        BaseResponse result = null;
        try {
            result = orderservice.checkBeforeCreateOrder(checkBeforeCreateOrderRequestVo);
        } catch (Exception e) {
            HealthUtil.logHealthInfo("checkBeforeCreateOrder", (System.currentTimeMillis() - start), e.getMessage());
        }
        return result;
    }

    /**
     * 创建订单
     */
    @IsConvertEN
    @LogIgnore(logMessage = "createOrder")
    @PostMapping("/createOrder")
    public BaseResponse createOrder(@Validated @LogParams @RequestBody CreateOrderVo createOrderVo) {
        return orderAdapterService.createOrderNew(createOrderVo);
    }

    /**
     * 通用创建订单
     */
    @LogIgnore(logMessage = "createOrderUniversal")
    @PostMapping("/createOrderUniversal")
    public BaseResponse createOrderUniversal(@Validated @LogParams @RequestBody Map<String, Object> param) {
        return orderAdapterService.createOrderUniversal(param);
    }

    /**
     * 扫脸支付下单
     */
    @LogIgnore(logMessage = "scanFaceCreateOrder")
    @PostMapping("/scanFaceCreateOrder")
    public BaseResponse scanFaceCreateOrder(@Validated @LogParams @RequestBody CreateOrderVo createOrderVo) {
        return orderservice.scanFaceCreateOrder(createOrderVo);
    }

    /**
     * APP下单，下单带商品信息，不经过购物车服务，不唤起支付
     */
    @LogIgnore(logMessage = "appCreateOrder")
    @PostMapping("/app/create")
    public BaseResponse appCreateOrder(@Validated @LogParams @RequestBody AppCreateOrderVo createOrderVo, BindingResult bindingResult) {
        return orderAdapterService.appCreateOrder(createOrderVo);
    }

    /**
     * 订单支付成功后通知
     */
    @LogIgnore(logMessage = "paySuccessCallback")
    @PostMapping("/paySuccessCallback")
    public String paySuccessCallback(@LogParams @RequestBody PaysuccessNoticeMessage message) {
        return orderAdapterService.paySuccessCallback(message);
    }

    /**
     * 订单支付成功后通知
     */
    @LogIgnore(logMessage = "newPaySuccessCallback")
    @PostMapping({"/newPaySuccessCallback","/openStoreQueryPaymentCallback"})
    public String newPaySuccessCallback(@LogParams @RequestBody NewPaysuccessNoticeMessage message) {
        return orderservice.newPaySuccessCallback(message);
    }

    /**
     * 退款回掉通知
     */
    @LogIgnore(logMessage = "refundNotifyCallback")
    @PostMapping("/refundNotifyCallback")
    public String refundNotifyCallback(@LogParams @RequestBody RefundNotifyCallbackRequestVo requestVo) {
        return orderservice.refundNotifyCallback(requestVo);
    }

    /**
     * 查询订单列表
     */
//    @ApiAnnotation(logMessage = "queryOrders")
    @PostMapping("/queryOrders")
    @LogIgnore(logMessage = "queryOrders")
    public BaseResponse queryOrders(@Validated @LogParams @RequestBody QueryOrderVo queryOrderVo) {
        return orderservice.queryOrders(queryOrderVo);
    }

    /**
     * 围餐-预览订单
     * @param queryOrderVo
     * @return
     */
    @IsConvertEN
    @LogIgnore(logMessage = "previewOrderInfo")
    @PostMapping("/previewOrderInfo")
    public BaseResponse previewOrderInfo(@Validated @LogParams @RequestBody QueryOrderVo queryOrderVo){
        CreateReserveOrderVo createReserveOrderVo =  new CreateReserveOrderVo();
        createReserveOrderVo.setSessionId(queryOrderVo.getSessionId());
        createReserveOrderVo.setActivityCode(queryOrderVo.getActivityCode());
        createReserveOrderVo.setCouponCode(queryOrderVo.getCouponCode());
        createReserveOrderVo.setUseCustomerScore(queryOrderVo.getUseCustomerScore());
        return encircleOrderService.queryOrderInfo(createReserveOrderVo);
    }

    /**
     * 围餐-svc卡支付调用接口-预览订单
     * @param queryOrderVo
     * @return
     */
    @IsConvertEN
    @LogIgnore(logMessage = "previewOrderInfoSvcCheck")
    @PostMapping("/previewOrderInfoSvcCheck")
    public BaseResponse previewOrderInfoSvcCheck(@Validated @LogParams @RequestBody QueryOrderVo queryOrderVo){
        CreateReserveOrderVo createReserveOrderVo =  new CreateReserveOrderVo();
        createReserveOrderVo.setSessionId(queryOrderVo.getSessionId());
        createReserveOrderVo.setActivityCode(queryOrderVo.getActivityCode());
        createReserveOrderVo.setCouponCode(queryOrderVo.getCouponCode());
        createReserveOrderVo.setUseCustomerScore(queryOrderVo.getUseCustomerScore());
        createReserveOrderVo.setCardCode(queryOrderVo.getCardCode());
        createReserveOrderVo.setPartnerId(queryOrderVo.getPartnerId());
        return encircleOrderService.previewOrderInfoSvcCheck(createReserveOrderVo);
    }

    /**
     * 获取订单详情
     */
    @LogIgnore(logMessage = "queryOrderById")
    @PostMapping("/queryOrderById")
    public BaseResponse queryOrderById(@Validated @LogParams @RequestBody QueryOrderVo queryOrderVo) {
        return orderservice.queryOrderById(queryOrderVo.getOperation(),queryOrderVo.getSessionId(), queryOrderVo.getOid(),queryOrderVo.getPartnerId(),queryOrderVo.getChannelType());
    }


    /**
     * 取消支付订单
     */
    @LogIgnore(logMessage = "cancelPayOrder")
    @PostMapping("/cancelPayOrder")
    public BaseResponse cancelPayOrder(@Validated @LogParams @RequestBody DeleteOrderVo deleteOrderVo) {
        return orderservice.cancelPayOrder(deleteOrderVo);
    }

    /**
     * 取消支付删除订单
     */
    @LogIgnore(logMessage = "deleteOrder")
    @PostMapping("/deleteOrder")
    public BaseResponse deleteOrder(@Validated @LogParams @RequestBody DeleteOrderVo deleteOrderVo) {
        return orderservice.deleteOrder(deleteOrderVo);
    }

    /**
     * 取消支付删除订单
     */
    @LogIgnore(logMessage = "deleteOrderById")
    @PostMapping("/deleteOrderById")
    public BaseResponse deleteOrderById(@Validated @LogParams @RequestBody DeleteOrderVo deleteOrderVo) {
        //return orderservice.deleteOrderById(deleteOrderVo);
        return orderservice.cancelPayOrder(deleteOrderVo);
    }

    /**
     * 用户申请退款
     */
    @LogIgnore(logMessage = "refund")
    @PostMapping("/refund")
    public BaseResponse refund(@Validated @LogParams @RequestBody OrderRefundVo orderRefundVo) {
        return orderservice.orderRefund(orderRefundVo);
    }

    /**
     * 获取订单排队号
     */
    @LogIgnore(logMessage = "queueIndex")
    @PostMapping("/queueIndex")
    public BaseResponse getOrderQueueIndex(@Validated @LogParams @RequestBody QueryOrderQueueIndexVo queryOrderQueueIndexVo) {
        return orderservice.queryOrderQueueIndex(queryOrderQueueIndexVo);
    }


    /**
     * 获取申请退款理由 1.9后作废
     */
    @LogIgnore(logMessage = "getOrderRefundReason")
    @ApiOperation(value = "获取申请退款理由", notes = "获取申请退款理由", produces = "application/json")
    @PostMapping("/getOrderRefundReason")
    public BaseResponse getRefundReason(@LogParams @RequestBody GetRefundReasonVo getRefundReasonVo) {
        return orderservice.getRefundReason(getRefundReasonVo);
    }

    /**
     * 获取申请退款理由
     */
    @LogIgnore(logMessage = "getNewOrderRefundReason")
    @ApiOperation(value = "获取申请退款理由", notes = "获取申请退款理由", produces = "application/json")
    @PostMapping("/getNewOrderRefundReason")
    public BaseResponse getNewRefundReason(@LogParams @RequestBody GetRefundReasonVo getRefundReasonVo) {
        return orderservice.getNewRefundReason(getRefundReasonVo);
    }

    /**
     * 查询桌号是否开台
     */
    @IsConvertEN
    @LogIgnore(logMessage = "queryTableNumberStatus")
    @ApiOperation(value = "查询桌号是否开台", notes = "查询桌号是否开台", produces = "application/json")
    @PostMapping("/queryTableNumberStatus")
    public BaseResponse queryTableNumberStatus(@LogParams @RequestBody EncircleReserveBaseVo encircleReserveBaseVo) {
        return encircleOrderService.queryTableNumberStatus(encircleReserveBaseVo);
    }

    /**
     * 查询30分钟未支付的优惠券订单
     */
    @LogIgnore(logMessage = "queryOrderWithCoupon")
    @ApiOperation(value = "查询30分钟未支付的优惠券订单", notes = "查询30分钟未支付的优惠券订单", produces = "application/json")
    @PostMapping("/queryOrderWithCoupon")
    public BaseResponse queryOrderWithCoupon(@LogParams @RequestBody QueryOrderWithCouponVo orderWithCouponVo) {
        return ResponseUtil.success();
    }

    /**
     * 订单确认完成
     */
    @LogIgnore(logMessage = "affirm")
    @PostMapping("/affirm")
    public BaseResponse orderAffirm(@Validated @LogParams @RequestBody OrderAffirmRequestVO request) {
        return mallOrderService.orderAffirm(request);
    }

    /**
     * 创建预支付
     */
    @LogIgnore(logMessage = "createPrepay")
    @PostMapping("/createPrepay")
    public BaseResponse createPrepay(@Validated @LogParams @RequestBody CreatePrepayVo request) {
        return orderAdapterService.createPrepay(request);
    }

    @ApiOperation(value = "创建积分订单", notes = "创建积分订单", produces = "application/json")
    @LogIgnore(logMessage = "createIntegralOrder")
    @PostMapping("/createIntegralOrder")
    public BaseResponse createIntegralOrder(@Validated @LogParams @RequestBody IntegralOrderVo request) {
        return orderservice.createIntegralOrder(request);
    }

    /**
     * 查询用户积分订单列表
     */
    @LogIgnore(logMessage = "queryOrderByConditions")
    @PostMapping("/queryOrderByConditions")
    public BaseResponse queryOrderByConditions(@Validated @LogParams @RequestBody QueryOrderByConditionsRequestVo queryOrderByConditionsRequestVo) {
        return orderservice.queryOrderByConditions(queryOrderByConditionsRequestVo);
    }

    /**
     * timeOutRefund
     * @param timeOutOrderVo
     * @return
     */
    @LogIgnore(logMessage = "timeOutOrderRefund")
    @PostMapping("/timeOutOrderRefund")
    public BaseResponse timeOutOrderRefund(@Validated @LogParams @RequestBody TimeOutOrderVo timeOutOrderVo){
        return orderservice.timeOutOrderRefund(timeOutOrderVo);
    }
    /**
     * 根据订单号查询配送操作日志及骑手位置
     * @param requestVo
     * @return
     */
    @LogIgnore(logMessage = "queryOrderRider")
    @PostMapping("/queryOrderRider")
    public BaseResponse queryOrderRider(@Validated @LogParams @RequestBody OrderRiderRequestVo requestVo){
        return orderservice.queryOrderRider(requestVo);
    }


    /**
     * 统计商户当日订单数
     */
    @LogIgnore(logMessage = "queryTodayOrders")
    @PostMapping("/queryTodayOrders")
    public BaseResponse queryTodayOrders(@Validated @LogParams @RequestBody QueryOrderByConditionsRequestVo queryOrderByConditionsRequestVo) {
        return orderservice.queryTodayOrders(queryOrderByConditionsRequestVo);
    }

    /**
     * 订单确认收货
     */
    @LogIgnore(logMessage = "receive")
    @PostMapping("/receive")
    public BaseResponse orderReceive(@Validated @LogParams @RequestBody OrderReceiveRequestVO request) {
        return mallOrderService.orderReceive(request);
    }

    /**
     * 退货快递信息
     */
    @LogIgnore(logMessage = "refundExpress")
    @PostMapping("/refundExpress")
    public BaseResponse refundExpress(@Validated @LogParams @RequestBody EditAfterSalesExpressVo editAfterSalesExpressVo) {
        return mallOrderService.saveAfterSalesExpress(editAfterSalesExpressVo);
    }

    /**
     * 拼团失败批量退款
     */
    @LogIgnore(logMessage = "spellGroupBatchRefund")
    @PostMapping("/spellGroupFailRefund")
    public BaseResponse spellGroupFailRefund(@Validated @LogParams @RequestBody SpellGroupFailRefundVo refundVo) {
        return orderservice.spellGroupOrderFailRefund(refundVo);
    }

    /**
     * 积分兑换记录查询（农工商）
     */
    @LogIgnore(logMessage = "scoreRecord")
    @PostMapping("/scoreRecord")
    public BaseResponse scoreRecord(@Validated @LogParams @RequestBody QueryOrderVo queryOrderVo) {
        return orderservice.scoreRecord(queryOrderVo);
    }


    /**
     *  订单统计 上报数据
     * @param
     * @return
     */
    @LogIgnore(logMessage = "reportSendOrderCount")
    @GetMapping("/reportSendOrderCount")
    public BaseResponse reportSendOrderCount() throws Exception {
        LogUtil.info("触发订单上报",null,null);
        orderCountJobHandler.execute(null);
        return ResponseUtil.success();
    }


    /**
     * TLS定时器 每天凌晨 上报昨天 门店支付记录 到 门店服务去
     */
    @LogIgnore(logMessage = "sendYesterDayStoreMsg")
    @GetMapping("/sendYesterDayStoreMsg")
    public BaseResponse sendYesterDayStoreMsg() {
        orderReportJobHandler.sendYesterDayStoreMsg();
        return ResponseUtil.success();
    }
}

