package com.gree.mall.manager.controller.order;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.gree.mall.manager.bean.order.BatchRemarkBean;
import com.gree.mall.manager.bean.order.OrderDetailBean;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.helper.ResponseHelper;
import com.gree.mall.manager.logic.order.OrderLogic;
import com.gree.mall.manager.plus.entity.OrderInfo;
import com.gree.mall.manager.plus.entity.OrderRefundCliaims;
import com.gree.mall.manager.utils.CommonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@RestController
@Api(value = "订单管理", tags = {"订单管理"})
@RequestMapping(value = "/order", produces = "application/json; charset=utf-8")
public class OrderController {


    @Autowired
    OrderLogic orderLogic;
    @Autowired
    RedisLockRegistry redisLockRegistry;

    @GetMapping("/list")
    @ApiOperation("列表")
    public ResponseHelper<Page<OrderDetailBean>> list(
            @ApiParam(value = "用户id", required = false) @RequestParam(required = false) String userId,
            @ApiParam(value = "订单号", required = false) @RequestParam(required = false) String orderId,
            @ApiParam(value = "产品名称", required = false) @RequestParam(required = false) String productName,
            @ApiParam(value = "用户名", required = false) @RequestParam(required = false) String userName,
            @ApiParam(value = "手机号", required = false) @RequestParam(required = false) String phone,
            @ApiParam(value = "兑换码", required = false) @RequestParam(required = false) String exchangeCode,
            @ApiParam(value = "订单状态 NOPAY:待付款 DFH:待发货 YFH:已发货 OVER:已完成 CLOSE:已关闭", required = false) @RequestParam(required = false) String orderStatus,
            @ApiParam(value = "开始创建时间", required = false) @RequestParam(required = false) String startCreateTime,
            @ApiParam(value = "结束创建时间", required = false) @RequestParam(required = false) String endCreateTime,
            @ApiParam(value = "开始支付时间", required = false) @RequestParam(required = false) String startPayTime,
            @ApiParam(value = "结束支付时间", required = false) @RequestParam(required = false) String endPayTime,
            @ApiParam(value = "网点id", required = false) @RequestParam(required = false) String websitId,
            @ApiParam(value = "页号", required = true) @RequestParam(required = true) Integer pageNum,
            @ApiParam(value = "页大小", required = true) @RequestParam(required = true) Integer pageSize,
            @ApiParam(value = "是否是差评订单0:未评价订单 1:差评订单 2:好评订单 3：已评价订单  不传都有", required = false) @RequestParam(required = false) String isNegative,
            @ApiParam(value = "派工异常 true为派工异常订单", required = false) @RequestParam(required = false) String abnormalDispatch,
            @ApiParam(value = "信息编号", required = false) @RequestParam(required = false) String workerOrderNo,
            @ApiParam(value = "套购商品id", required = false) @RequestParam(required = false) String goodsId,
             HttpServletRequest request
    ) throws RemoteServiceException {
        IPage<OrderDetailBean> list = orderLogic
                .list(request,userId,orderId, productName, userName, phone,exchangeCode, orderStatus, startCreateTime,
                        endCreateTime, startPayTime, endPayTime,websitId,pageNum, pageSize,isNegative,abnormalDispatch,workerOrderNo,goodsId);
        return ResponseHelper.success(list);
    }

    @GetMapping("/detail")
    @ApiOperation("订单详情")
    public ResponseHelper<OrderDetailBean> detail(
            @ApiParam(value = "订单号", required = true) @RequestParam(required = true) String orderId
    ) {
        OrderDetailBean detail = orderLogic.detail(orderId);
        return ResponseHelper.success(detail);
    }


    @PostMapping("/comment/show")
    @ApiOperation("显示评价")
    public ResponseHelper showComment(
            @ApiParam(value = "订单号", required = true) @RequestParam(required = true) String orderId,
            @ApiParam(value = "true=显示 false=不显示", required = true) @RequestParam(required = true) Boolean isShow
    ) {
        orderLogic.updateShowComment(orderId,isShow);
        return ResponseHelper.success();
    }

    @PostMapping("/remark")
    @ApiOperation("备注")
    public ResponseHelper remark(
            @ApiParam(value = "订单号", required = true) @RequestParam(required = true) String orderId,
            @ApiParam(value = "备注", required = true) @RequestParam(required = true) String remark
    ) {
        orderLogic.remark(orderId, remark);
        return ResponseHelper.success();
    }

    @PostMapping("/express/update")
    @ApiOperation("修改物流单号")
    public ResponseHelper updateExpress(
            @ApiParam(value = "订单号", required = true) @RequestParam(required = true) String orderId,
            @ApiParam(value = "物流单号", required = true) @RequestParam(required = true) String logisticsNo,
            @ApiParam(value = "物流公司code", required = true) @RequestParam(required = true) String companyCode
    ) throws RemoteServiceException {
        orderLogic.updateExpress(orderId, logisticsNo,companyCode);
        return ResponseHelper.success();
    }

    @GetMapping("/expressInfo/select")
    @ApiOperation("查看物流")
    public ResponseHelper queryExpressInfo(
            @ApiParam(value = "物流单号", required = true) @RequestParam(required = true) String logisticsNo
    ) throws RemoteServiceException {
        orderLogic.queryExpressInfo(logisticsNo);
        return ResponseHelper.success();
    }


    @PostMapping("/cancel")
    @ApiOperation("取消订单")
    public ResponseHelper remark(
            @ApiParam(value = "订单号", required = true) @RequestParam(required = true) String orderId
    ) throws RemoteServiceException, WxPayException {
        orderLogic.cancel(orderId);
        return ResponseHelper.success();
    }

    @PostMapping("/ack")
    @ApiOperation("确认收款")
    public ResponseHelper ack(
            @ApiParam(value = "订单号", required = true) @RequestParam(required = true) String orderId
    ) {
        orderLogic.ackPay(orderId);
        return ResponseHelper.success();
    }



    @PostMapping("/detail/refund")
    @ApiOperation("订单详情主动退款")
    public ResponseHelper<BigDecimal> notice(
            @ApiParam(value = "订单详情id",required = true) @RequestParam String orderDetailId,
            @ApiParam(value = "数量",required = true) @RequestParam Integer num,
            @ApiParam(value = "退款密码") @RequestParam(required = false) String refundPassword
    ) throws Exception {
        BigDecimal refund = orderLogic.refund(orderDetailId, num, refundPassword);
        return ResponseHelper.success(refund);
    }

    @GetMapping("/cliaims/list")
    @ApiOperation("理赔列表")
    public ResponseHelper<List<OrderRefundCliaims>> cliaimslist(
            @ApiParam(value = "订单id",required = true) @RequestParam String orderId
    ) throws RemoteServiceException, WxPayException {
        List<OrderRefundCliaims> orderRefundCliaims = orderLogic.cliaimsList(orderId);
        return ResponseHelper.success(orderRefundCliaims);
    }

    @PostMapping("/cliaims/refund")
    @ApiOperation("订单详情理赔")
    public ResponseHelper refundcliaims(
            @ApiParam(value = "订单详情id",required = true) @RequestParam String orderDetailId,
            @ApiParam(value = "数量",required = true) @RequestParam Integer num,
            @ApiParam(value = "退款金额",required = true) @RequestParam BigDecimal refundAmount,
            @ApiParam(value = "登录人帐号id",required = true) @RequestParam String adminUserId,
            @ApiParam(value = "理赔备注",required = true) @RequestParam String remark,
            @ApiParam(value = "退款密码") @RequestParam(required = false) String refundPassword
    ) throws Exception {
        orderLogic.refundCliaims(orderDetailId, num, refundAmount, adminUserId, remark, refundPassword);
        return ResponseHelper.success();
    }


    @PostMapping("/price/update")
    @ApiOperation("修改价格")
    public ResponseHelper upatePrice(
            @ApiParam(value = "订单号", required = true) @RequestParam(required = true) String orderId,
            @ApiParam(value = "价格", required = true) @RequestParam(required = true) BigDecimal price
    ) throws RemoteServiceException {
        orderLogic.updatePrice(orderId, price);
        return ResponseHelper.success();
    }

    @PostMapping("/rece/info/update")
    @ApiOperation("收货信息修改")
    public ResponseHelper updateReceInfo(
            @ApiParam(value = "订单", required = true) @RequestBody OrderInfo orderInfo
    ) throws RemoteServiceException {
        orderLogic.updateReceInfo(orderInfo);
        return ResponseHelper.success();
    }

    @PostMapping("/goods/deliver")
    @ApiOperation("发货")
    public ResponseHelper deliverGoods(
            @ApiParam(value = "订单号", required = true) @RequestParam(required = true) String orderId,
            @ApiParam(value = "快递单号", required = true) @RequestParam(required = true) String logisticsNo,
            @ApiParam(value = "货仓id", required = true) @RequestParam(required = true) String storageId,
            @ApiParam(value = "快递公司编号", required = true) @RequestParam(required = true) String companyCode,
            @ApiParam(value = "是否需要派单 true=是 false=否", required = false) @RequestParam(required = false) Boolean workOrder,
            @ApiParam(value = "是否退换单 true=是 false=否", required = false) @RequestParam(required = false) Boolean exchange
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + orderId);
        if(!obtain.tryLock(10,TimeUnit.SECONDS)){
            return ResponseHelper.error("系统繁忙，请稍后再试");
        }
        try {
            orderLogic.deliverGoods(orderId, logisticsNo, companyCode, storageId, workOrder, exchange);
        }finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @PostMapping("/goods/batch/deliver")
    @ApiOperation("批量发货")
    public ResponseHelper deliverBatchGoods(
            HttpServletRequest request,
            @ApiParam(required = true, value = "excel文件") @RequestParam(required = true) MultipartFile file
    ) throws Exception {
        orderLogic.deliverBatchGoods(request, file);
        return ResponseHelper.success();
    }


    @GetMapping("/goods/deliver/excel")
    @ApiOperation("批量发货excel示例表格下载")
    public void excelDownload(
            HttpServletResponse response
    ) throws RemoteServiceException, IOException {
        CommonUtils.downloadFile("批量发货模板.xlsx", response);
    }


    @PostMapping("/batch/remark")
    @ApiOperation("卖家批量设置备注")
    public ResponseHelper batchRemark(
            @ApiParam(value = "备注信息", required = true) @RequestBody BatchRemarkBean batchRemarkBean
    ) throws RemoteServiceException {
        orderLogic.batchRemark(batchRemarkBean);
        return ResponseHelper.success();
    }


    @GetMapping("/export")
    @ApiOperation("导出excel")
    public void downloadFile2 (HttpServletRequest request, HttpServletResponse response,
                               @ApiParam(value = "用户id", required = false) @RequestParam(required = false) String userId,
                               @ApiParam(value = "订单号", required = false) @RequestParam(required = false) String orderId,
                               @ApiParam(value = "产品名称", required = false) @RequestParam(required = false) String productName,
                               @ApiParam(value = "用户名", required = false) @RequestParam(required = false) String userName,
                               @ApiParam(value = "手机号", required = false) @RequestParam(required = false) String phone,
                               @ApiParam(value = "兑换码", required = false) @RequestParam(required = false) String exchangeCode,
                               @ApiParam(value = "订单状态 NOPAY:待付款 DFH:待发货 YFH:已发货 OVER:已完成 CLOSE:已关闭", required = false)
                                   @RequestParam(required = false) String orderStatus,
                               @ApiParam(value = "开始创建时间", required = false) @RequestParam(required = false) String startCreateTime,
                               @ApiParam(value = "结束创建时间", required = false) @RequestParam(required = false) String endCreateTime,
                               @ApiParam(value = "开始支付时间", required = false) @RequestParam(required = false) String startPayTime,
                               @ApiParam(value = "结束支付时间", required = false) @RequestParam(required = false) String endPayTime,
                               @ApiParam(value = "团购团长名称", required = false) @RequestParam(required = false) String promotionGroupUser,
                               @ApiParam(value = "团购活动id", required = false) @RequestParam(required = false) String promotionGroupId,
                               @ApiParam(value = "团购团长id", required = false) @RequestParam(required = false) String promotionGroupUserId,
                               @ApiParam(value = "网点id", required = false) @RequestParam(required = false) String websitId,
                               @ApiParam(value = "商品id", required = false) @RequestParam(required = false) String goodsId

    ) throws Exception {

        orderLogic.export2( request,  response,
                userId,  orderId,  productName,  userName,
                phone,  exchangeCode,  orderStatus,
                startCreateTime,  endCreateTime,
                startPayTime,  endPayTime,  promotionGroupUser,promotionGroupId,promotionGroupUserId,websitId,goodsId);
    }


    @GetMapping("/test/query/share/result")
    @ApiOperation("测试查询分账结果")
    public ResponseHelper testQueryShareResult(
            @ApiParam(value = "分账id", required = false) @RequestParam(required = false) String orderShareId
    ) throws Exception {
        orderLogic.testQueryShareResult(orderShareId);
        return ResponseHelper.success();
    }

}
