/**
 * 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.base.entity.BaseResponse;
import cn.freemud.entities.dto.order.CreateCashierOrderDto;
import cn.freemud.entities.dto.order.InvoiceCreateResponseVo;
import cn.freemud.entities.dto.order.OrderInvoiceConfigVo;
import cn.freemud.entities.vo.*;
import cn.freemud.entities.vo.encircle.CreateReserveOrderVo;
import cn.freemud.entities.vo.encircle.EncircleReserveBaseVo;
import cn.freemud.entities.vo.order.*;
import cn.freemud.handler.CouponOrderAutoRefundHandler;
import cn.freemud.handler.OrderReportJobHandler;
import cn.freemud.service.EncircleOrderService;
import cn.freemud.service.Orderservice;
import cn.freemud.service.PointsMallOrderService;
import cn.freemud.service.RefundService;
import cn.freemud.service.impl.MallOrderServiceImpl;
import cn.freemud.service.impl.OrderAdapterServiceImpl;
import cn.freemud.utils.AppLogUtil;
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 io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
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;


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

    @Autowired
    private Orderservice orderservice;
    @Autowired
    private OrderAdapterServiceImpl orderAdapterService;
    @Autowired
    private EncircleOrderService encircleOrderService;
    @Autowired
    private MallOrderServiceImpl mallOrderService;
    @Autowired
    private OrderReportJobHandler orderReportJobHandler;
    @Autowired
    private OrderCountJobHandler orderCountJobHandler;
    @Autowired
    private CouponOrderAutoRefundHandler couponOrderAutoRefundHandler;
    @Autowired
    private PointsMallOrderService pointsMallOrderService;
    @Autowired
    private RefundService refundService;

    /**
     * 废弃，不在使用
     * 创建订单之前校验前面排队的订单数
     */
    @ApiAnnotation(logMessage = "checkBeforeCreateOrder")
    @PostMapping("/checkBeforeCreateOrder")
    public BaseResponse checkBeforeCreateOrder(@Validated @LogParams @RequestBody CheckBeforeCreateOrderRequestVo checkBeforeCreateOrderRequestVo) {
        return ResponseUtil.success();
    }

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

    /**
     * 创建收银订单（无商品单）
     */
    @IsConvertEN
    @ApiAnnotation(logMessage = "createCashierOrder")
    @PostMapping("/createCashierOrder")
    public BaseResponse<CreateOrderResponseVo> createCashierOrder(@Validated @LogParams @RequestBody CreateCashierOrderVo request) {
        CreateCashierOrderDto dto = new CreateCashierOrderDto();
        BeanUtils.copyProperties(request, dto);
        return ResponseUtil.success(orderAdapterService.createCashierOrder(dto));
    }

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

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

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

    /**
     * 订单支付成功后通知 老支付回掉，已不用废弃
     */
    @ApiAnnotation(logMessage = "paySuccessCallback")
    @PostMapping("/paySuccessCallback")
    public String paySuccessCallback(@LogParams @RequestBody PaysuccessNoticeMessage message) {
        return orderAdapterService.paySuccessCallback(message);
    }

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

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

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

    /**
     * 查询订单列表(野翠山发票订单列表查询)
     */
    @PostMapping("/queryOrdersNew")
    @ApiAnnotation(logMessage = "queryOrdersNew")
    public BaseResponse queryOrdersNew(@Validated @LogParams @RequestBody QueryOrderVo queryOrderVo) {
        return orderservice.queryOrdersNew(queryOrderVo);
    }

    /**
     * 围餐-预览订单
     * @param queryOrderVo
     * @return
     */
    @IsConvertEN
    @ApiAnnotation(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
    @ApiAnnotation(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);
    }

    /**
     * 获取订单详情
     */
    @ApiAnnotation(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()
                ,queryOrderVo.getIsQueryAfterPay(),queryOrderVo.getPayGiftVer());
    }


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

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

    /**
     * 用户申请退款
     */
    @ApiAnnotation(logMessage = "refund")
    @PostMapping("/refund")
    public BaseResponse<Void> refund(@Validated @LogParams @RequestBody OrderRefundVo reqVo) {
        // 微商城因为没有退款原因选项 所以将用户退款说明用户作为退款原因
        String reason = StringUtils.isBlank(reqVo.getReason())
                ? reqVo.getRemarks() : reqVo.getReason();
        refundService.refundOrder(reqVo.getPartnerId(), reqVo.getOid(), reqVo.getRefundAmount(), reason, reqVo.getRemarks(), reqVo.getRefundMode());
        return ResponseUtil.success();
    }


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


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

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

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

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

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

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

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

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

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


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

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

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

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

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

    /**
     * 开个店积分商城-积分兑换记录查询
     */
    @ApiAnnotation(logMessage = "scoreRecords")
    @PostMapping("/scoreRecords")
    public BaseResponse scoreRecords(@Validated @LogParams @RequestBody QueryOrderVo queryOrderVo) {
        return pointsMallOrderService.scoreRecords(queryOrderVo);
    }

    /**
     * 积分兑换记录查询详情
     */
    @ApiAnnotation(logMessage = "scoreRecord")
    @PostMapping("/scoreRecordInfo")
    public BaseResponse scoreRecordDetail(@Validated @LogParams @RequestBody QueryOrderVo queryOrderVo) {
        return pointsMallOrderService.scoreRecordDetail(queryOrderVo);
    }

    /**
     * 订单申诉结果查询
     */
    @ApiAnnotation(logMessage = "queryOrderAppeal")
    @PostMapping("/queryOrderAppeal")
    public BaseResponse queryOrderAppeal(@Validated @LogParams @RequestBody OrderAppealVo orderAppealVo) {
        return orderservice.queryOrderAppeal(orderAppealVo);
    }

    /**
     * 订单申诉
     */
    @ApiAnnotation(logMessage = "submitAppeal")
    @PostMapping("/submitAppeal")
    public BaseResponse submitAppeal(@Validated @LogParams @RequestBody OrderAppealVo orderAppealVo) {
        return orderservice.submitAppeal(orderAppealVo);
    }


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


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

    /**
     * 2021年9月15日-开票历史列表接口+详情接口+发票所含订单接口-黄兆良
     * 查询开票历史列表
     */
    @PostMapping("/queryInvoiceList")
    @ApiAnnotation(logMessage = "queryInvoiceList")
    public BaseResponse queryInvoiceList(@Validated @LogParams @RequestBody QueryInvoiceReq queryInvoiceReq) {
        return orderservice.queryInvoiceList(queryInvoiceReq);
    }

    /**
     *  开订单发票，对接百望
     * @param
     * @return
     */
    @ApiAnnotation(logMessage = "createOrderInvoice")
    @PostMapping("/createOrderInvoice")
    public BaseResponse<InvoiceCreateResponseVo> createOrderInvoice(@Validated @LogParams @RequestBody CreateOrderInvoiceRequest request) {
        return orderservice.createAndGetOrderInvoice(request);
    }

    /**
     *  查询发票配置
     * @param
     * @return
     */
    @ApiAnnotation(logMessage = "queryInvoiceConfig")
    @PostMapping("/queryInvoiceConfig")
    public BaseResponse<OrderInvoiceConfigVo> queryInvoiceConfig(@Validated @LogParams @RequestBody GetInvoiceConfigRequest request) {
        return orderservice.queryInvoiceConfig(request);
    }



    /**
     * 一元捐插件获取支付配置
     * @param createOrderVo
     * @return
     */
    @ApiAnnotation(logMessage = "paymentConfig")
    @PostMapping("/paymentConfig")
    public BaseResponse paymentConfig(@Validated @LogParams @RequestBody PaymentConfigVo createOrderVo) {
        return orderAdapterService.getPaymentConfig(createOrderVo);
    }


    /**
     * 卖券订单申请退款
     */
    @ApiAnnotation(logMessage = "couponOrderRefund")
    @PostMapping("/couponOrderRefund")
    public BaseResponse couponOrderRefund(@Validated @LogParams @RequestBody OrderRefundVo orderRefundVo) {
        return orderservice.couponOrderRefund(orderRefundVo,0);
    }


    /**
     * 卖券订单申请退款
     */
    @ApiAnnotation(logMessage = "couponOrderRefundRetry")
    @PostMapping("/couponOrderRefundRetry")
    public BaseResponse couponOrderRefundRetry(@Validated @LogParams @RequestBody OrderRefundRetryVo orderRefundRetryVo) {
        return orderservice.couponOrderRefundRetry(orderRefundRetryVo);
    }

    /**
     *  卖券订单券过期自动退款
     * @param
     * @return
     */
    @ApiAnnotation(logMessage = "couponOrderAutoRefund")
    @GetMapping("/couponOrderAutoRefund")
    public BaseResponse couponOrderAutoRefund() throws Exception {
        AppLogUtil.infoLog("卖券订单券过期自动退款 ",null,null);
        couponOrderAutoRefundHandler.execute(null);
        return ResponseUtil.success();
    }

    /**
     * 无单收银使用储值卡混合支付校验余额
     */
    @ApiAnnotation(logMessage = "cashierCheck")
    @PostMapping("/cashierCheck")
    public BaseResponse<CashierCheckResponseVo> cashierCheck(@Validated @LogParams @RequestBody CashierCheckVo request) {
        CreateCashierOrderDto dto = new CreateCashierOrderDto();
        BeanUtils.copyProperties(request, dto);
        return ResponseUtil.success(orderAdapterService.cashierCheck(dto));
    }

    /**
     * 获取餐盒费配置
     */
    @PostMapping("/orderConfig/get")
    @ApiAnnotation(logMessage = "/orderConfig/get")
    public BaseResponse<String> getOrderConfig(@Validated @LogParams @RequestBody GetOrderConfigRequestVo request){
        return ResponseUtil.success(orderAdapterService.getOrderConfig(request));
    }


    /**
     *  华莱士临时对接百事抽奖活动
     * @param request
     * @return 是否需要弹框,跳转百事
     */
    @ApiAnnotation(logMessage = "/order/temp/activity")
    @PostMapping("/temp/activity/query")
    public BaseResponse wallaceTempActivity(@Validated @LogParams @RequestBody WallaceTempActivityRequest request) {
        return orderAdapterService.wallaceTempActivity(request);
    }
}

