package com.younike.member;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.younike.common.core.controller.BaseController;
import com.younike.common.core.domain.AjaxResult;
import com.younike.common.utils.StringUtils;
import com.younike.framework.config.AnonymousAccess;
import com.younike.framework.config.MemberAccess;
import com.younike.hlpay.dto.OrderParam;
import com.younike.hlpay.dto.PaymentParam;
import com.younike.system.domain.Order;
import com.younike.system.domain.vo.MemberOrderVo;
import com.younike.system.enums.UjdChangeTypeEnum;
import com.younike.system.mapper.UjdChangeRecordMapper;
import com.younike.system.param.OrderGroupParam;
import com.younike.system.param.OrderPublishParam;
import com.younike.system.param.OredrRefundParam;
import com.younike.system.service.*;
import com.younike.wxpay.params.RefundNotificationParams;
import com.younike.wxpay.params.TransactionNotificationParams;
import com.younike.wxpay.responses.NotificationResponse;
import com.younike.wxpay.service.IMerchantPayService;
import com.younike.wxpay.service.ISupplierPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 会员订单Controller
 *
 * @author dail
 * @date 2022-01-10
 */
@Api("会员订单接口")
@RestController
@RequestMapping("/member/order")
@Log4j2
public class MemberOrderController extends BaseController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderRecordService orderRecordService;

    @Autowired
    private IServerTimeService serverTimeService;

    @Autowired
    private ISupplierPayService supplierPayService;

    @Autowired
    private IMerchantPayService merchantPayService;


    /**
     * 查询会员订单列表
     */
    @ApiOperation("查询会员订单列表")
//    @AnonymousAccess
    @MemberAccess
//    @PreAuthorize("@ss.hasPermi('member:order:list')")
    @GetMapping("/list")
    public Object list(Order order) {
        if (order == null || order.getMemberId() == null) {
            return AjaxResult.error("参数错误");
        }
        startPage();
        List<MemberOrderVo> list = orderService.listMemberOrderByOrderState(order);
        return getDataTable(list);
    }

    /**
     * 查询会员订单详情
     */
    @ApiOperation("查询会员订单详情")
//    @AnonymousAccess
    @MemberAccess
//    @PreAuthorize("@ss.hasPermi('member:order:query')")
    @GetMapping(value = "/{orderId}")
    public AjaxResult getMemberOrderByOrderId(@PathVariable("orderId") Long orderId) {
        return AjaxResult.success(orderService.getMemberOrderByOrderId(orderId));
    }

    /**
     * 查询会员订单详情
     */
    @ApiOperation("查询会员订单支付状态")
    @MemberAccess
    @GetMapping(value = "payState/{orderId}")
    public AjaxResult payState(@PathVariable("orderId") Long orderId) {
        return orderService.payState(orderId);
    }

    @ApiOperation("订单接口：会员下单")
    @MemberAccess
    @PostMapping
    public AjaxResult addOrder(@RequestBody OrderParam param) {
        //数据校验
        if(ObjectUtils.isEmpty(param)){
            return AjaxResult.error("参数错误");
        }
        if(param.getMemberId()==null || param.getGoodsId()==null || param.getMerchantId()==null || param.getServerId()==null || StringUtils.isNull(param.getAppointmentStartTime()) || param.getOrderAmount()==null || param.getGoodsCounts()==null || StringUtils.isNull(param.getOrderType()) ){
            return AjaxResult.error("参数错误");
        }

        if(param.getTotalAmount()==null || param.getAddressId()==null || param.getPrice()==null || param.getSingleTime()==null){
            return AjaxResult.error("参数错误");
        }

        return  orderService.addOrder(param);
    }

    @PutMapping("/payment")
    @AnonymousAccess
    @ApiOperation("订单支付")
    public AjaxResult payment(@RequestBody PaymentParam param) {

        //参数验证
        if(ObjectUtils.isEmpty(param)){
            return AjaxResult.error("参数错误");
        }
        //验证会员d 实付总价，支付方式不能为空
        if(StringUtils.isNull(param.getOrderId()) || StringUtils.isNull(param.getPayWay()) || param.getTotalAmount()==null){
            return AjaxResult.error("参数错误(订单id、实付总价、支付方式不能为空)");
        }
        return orderService.payment(param);
    }

    /**
     * 申请平台介入（申请退款）
     * @param param
     * @return
     */
    @PutMapping("/applyForRefund")
    @MemberAccess
    @ApiOperation("申请平台介入（申请退款）")
    public AjaxResult applyForRefund(@RequestBody OredrRefundParam param) {

        //参数验证
        if(ObjectUtils.isEmpty(param) || param.getOrderId()==null){
            return AjaxResult.error("参数错误");
        }
        return orderService.applyForRefund(param);
    }

    /**
     * 取消申请平台介入
     * @param param
     * @return
     */
    @PutMapping("/cancelRefund")
    @MemberAccess
    @ApiOperation("取消申请平台介入")
    public AjaxResult cancelRefund(@RequestBody OrderParam param) {

        //参数验证
        if(ObjectUtils.isEmpty(param) || param.getOrderId()==null){
            return AjaxResult.error("参数错误");
        }
        return orderService.cancelRefund(param);
    }

    /**
     * 申请取消订单
     * @param param
     * @return
     */
    @PutMapping("/cancal")
    @MemberAccess
    @ApiOperation("申请取消订单")
    public AjaxResult cancal(@RequestBody OredrRefundParam param) {

        //参数验证
        if(ObjectUtils.isEmpty(param)|| param.getOrderId()==null){
            return AjaxResult.error("参数错误");
        }
        return orderService.cancal(param);
    }

    /**
     * 确认完成
     * @param param
     * @return
     */
    @PutMapping("/affirm")
    @MemberAccess
    @ApiOperation("确认完成")
    public AjaxResult affirm(@RequestBody OredrRefundParam param) {

        //参数验证
        if(ObjectUtils.isEmpty(param)|| param.getOrderId()==null){
            return AjaxResult.error("参数错误");
        }
        return orderService.affirm(param);
    }

    /**
     * 追加服务
     * @param param
     * @return
     */
    @PutMapping("/addServer")
    @AnonymousAccess
    @ApiOperation("追加服务")
    public AjaxResult addServer(@RequestBody OrderParam param) {

        //参数验证
        if(ObjectUtils.isEmpty(param) || param.getOrderId() == null){
            return AjaxResult.error("参数错误");
        }
        Order order = orderService.selectOrderByOrderId(param.getOrderId());
        if(order.getAddPayStatus() !=null && order.getAddPayStatus() == 1){
            return AjaxResult.error("Order不可重复支付");
        }

        if("001".equals(order.getOrderType())){
            //实付总价，支付方式不能为空
            if( StringUtils.isNull(param.getOrderId()) || param.getAddAmount()==null || StringUtils.isNull(param.getAddPayWay()) || param.getAddCounts()==null ){
                log.error("参数---》 " + JSONObject.toJSONString(param));
                return AjaxResult.error("参数错误(订单id、追加服务金额、支付方式、追加服务数量不能为空)");
            }
        //  家政追加服务
            return orderService.addServer(param);
        }else {
            //实付总价，支付方式不能为空
            if( StringUtils.isNull(param.getOrderId()) || StringUtils.isNull(param.getAddPayWay()) ){
                return AjaxResult.error("参数错误(订单id、支付方式不能为空)");
            }
            if(ObjectUtils.isEmpty(order.getAddPayStatus()) || order.getAddPayStatus() == 0){
                //  支付维修配件费
                return orderService.addMaintenanceServer(param);
            }
            return AjaxResult.error("订单已经付款，不可重复付款");
        }
    }

    /**
     * 查询会员订单追踪信息
     */
    @ApiOperation("查询会员订单追踪信息")
    @MemberAccess
//    @PreAuthorize("@ss.hasPermi('member:orderRecord:query')")
    @GetMapping(value = "/getMemberOrderRecord")
    public AjaxResult getMemberOrderRecord(@RequestParam("orderId") Long orderId) {
        if (orderId == null) {
            return AjaxResult.error("参数错误(订单id不能为空)");
        }
        return AjaxResult.success(orderRecordService.getMemberOrderRecord(orderId));
    }

    /**
     * 查询会员订单追踪信息
     */
    @ApiOperation("查询服务人员服务预约列表")
    @MemberAccess
    @GetMapping(value = "/server-time-section")
    public AjaxResult getServerTimeSections(@RequestParam("serverId") Long serverId, @RequestParam("goodsId") Long goodsId,
                                            @RequestParam("goodsCount") Long goodsCount) {
        if (serverId == null) {
            return AjaxResult.error("参数错误(服务人员id不能为空)");
        }
        if (goodsId == null) {
            return AjaxResult.error("参数错误(服务id不能为空)");
        }
        if (goodsCount == null) {
            return AjaxResult.error("参数错误(服务次数不能为空)");
        }
        return AjaxResult.success(serverTimeService.getServerTimeSection(serverId, goodsId, goodsCount));
    }

    /**
     * 查询会员订单追踪信息
     */
    @ApiOperation("查询服务人员服务预约列表")
    @MemberAccess
    @GetMapping(value = "/server-time-publish")
    public AjaxResult getServerTimePublish(@RequestParam("serverId") Long serverId, @RequestParam("quoteId") Long quoteId) {
        if (serverId == null) {
            return AjaxResult.error("参数错误(服务人员id不能为空)");
        }
        if (quoteId == null) {
            return AjaxResult.error("参数错误(报价id不能为空)");
        }
        return AjaxResult.success(serverTimeService.getServerTimePublish(serverId, quoteId));
    }

    @ApiOperation("下单支付回调")
    @PostMapping("/payment/cb")
    @AnonymousAccess
    public NotificationResponse paymentCb(HttpServletRequest request) throws Exception{
        String params = supplierPayService.decrypt(request);
        log.info("下单支付回调：" + params);
        return orderService.paymentCb(JSON.parseObject(params, TransactionNotificationParams.class));
    }

    @ApiOperation("追加服务支付回调")
    @PostMapping("/addServer/cb")
    @AnonymousAccess
    public NotificationResponse paymentAddServerCb(HttpServletRequest request) throws Exception{
        String params = supplierPayService.decrypt(request);
        log.info("追加服务支付回调：" + params);
        return orderService.paymentAddServerCb(JSON.parseObject(params, TransactionNotificationParams.class));
    }

    @ApiOperation("追加服务支付回调")
    @PostMapping("/addMaintenance/cb")
    @AnonymousAccess
    public NotificationResponse paymentAddMaintanceCb(HttpServletRequest request) throws Exception{
        String params = supplierPayService.decrypt(request);
        log.info("维修配件费支付回调：" + params);
        return orderService.paymentAddMaintanceCb(JSON.parseObject(params, TransactionNotificationParams.class));
    }

    @ApiOperation("退款回调")
    @PostMapping("/refund/cb")
    @AnonymousAccess
    public NotificationResponse refundCb(HttpServletRequest request) throws Exception{
        String params = supplierPayService.decrypt(request);
        log.info("订单退款回调：" + params);
        return orderService.refundCb(JSON.parseObject(params, RefundNotificationParams.class));
    }

    @ApiOperation("保证金充值支付回调")
    @PostMapping("/bond/cb")
    @AnonymousAccess
    public NotificationResponse bondCb(HttpServletRequest request) throws Exception{
        String params = supplierPayService.decrypt(request);
        log.info("保证金充值支付回调：" + params);
        return orderService.bondCb(JSON.parseObject(params, TransactionNotificationParams.class));
    }

    /**
     * 查询会员订单查询追加服务支付结果
     */
    @ApiOperation("查询会员订单追加服务支付状态")
    @AnonymousAccess
    @GetMapping(value = "addServer/{orderId}")
    public AjaxResult addServerCb(@PathVariable("orderId") Long orderId) {
        return orderService.addServerCb(orderId);
    }


    /**
     *发布需求：预约提交订单
     */
    @ApiOperation("订单接口：（发布需求）预约提交订单")
//    @AnonymousAccess
    @MemberAccess
    @PostMapping("/addPublishOrder")
    public AjaxResult addPublishOrder(@RequestBody OrderPublishParam param) {
        //数据校验
        if (ObjectUtils.isEmpty(param)) {
            return AjaxResult.error("参数错误");
        }
        if (param.getPublishId() == null || param.getQuoteId() == null || ObjectUtils.isEmpty(param.getOrderAmount()) || ObjectUtils.isEmpty(param.getTotalAmount()) || ObjectUtils.isEmpty(param.getAppointmentStartTime())) {
            return AjaxResult.error("参数错误");
        }

        return orderService.addPublishOrder(param);
    }

    /**
     * 团购服务：预约提交订单
     */
    @ApiOperation("订单接口：（团购服务）预约提交订单")
    @AnonymousAccess
//    @MemberAccess
    @PostMapping("/addGroupOrder")
    public AjaxResult addGroupOrder(@RequestBody OrderGroupParam param) {
        //数据校验
        if (ObjectUtils.isEmpty(param)) {
            return AjaxResult.error("参数错误");
        }
        if (param.getMemberId() == null || param.getGoodsId() == null || param.getGoodsSpecificationId() == null) {
            return AjaxResult.error("参数错误");
        }

        return orderService.addGroupOrder(param);
    }

    /**
     * 查询会员团购订单详情
     */
    @ApiOperation("查询会员团购订单详情")
    @AnonymousAccess
//    @MemberAccess
    @GetMapping(value = "/groupOrder/{orderId}")
    public AjaxResult getMemberGroupOrderByOrderId(@PathVariable("orderId") Long orderId) {
        return AjaxResult.success(orderService.getMemberGroupOrderByOrderId(orderId));
    }
}
