package com.bohuikeji.delivery.backstage.controller.api.customer;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.constants.payConst;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.third.OrderDetailDO;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.HuolalaServer;
import com.bohuikeji.delivery.backstage.service.third.JdServer;
import com.bohuikeji.delivery.backstage.service.third.SfExpressServer;
import com.bohuikeji.delivery.backstage.util.ThirdSmUtils;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.service.ITFranchiseeInformationService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.List;



@Api(tags = {"第三方订单客户补充支付相关接口"})
@RestController
@Slf4j
@RequestMapping("/api/third/order")
@RequiredArgsConstructor
public class ThirdOrderSmPayApi extends ApiController {

    final ITOrderService orderService;
    final RedisUtil redisUtil;
    final RabbitTemplate rabbitTemplate;
    final ISysConfigService sysConfigService;
    final ITCourierService courierService;
    final ITNewsService newsService;
    final ITPayService payService;
    final ITRefundService refundService;
    final ITCustomerService customerService;
    final ITGiveDetailService giveDetailService;
    final ITCustomerWalletService customerWalletService;
    final ITCustomerPayService customerPayService;
    final ITwxtransfersService twxtransfersService;
    final ITwalletDetailService twalletDetailService;
    final ITFranchiseeInformationService franServer;
    final ITCustomerBigService customerBigService;
    final ITCustomerTemplateService customerTemplateService;
    final ITDiscountMallService discountMallService;
    final ITDiscountRecordService discountRecordService;
    final ITDiscountOrderService orderDiscountService;
    final IWxUserService wxUserService;
    final ITConfigService configService;
    final SfExpressServer sfServer;
    final JdServer jdServer;
    final HuolalaServer huolalaServer;
    final ITOrderArrearsService orderArrearsService;
    private static final DateTimeFormatter dt = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");

    /**
     * 查询欠费订单
     * @return
     */
    @ApiOperation("查询欠费订单")
    @GetMapping("/get/arrears/order")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    public APIEntity getArrearsOrder(@RequestAttribute("JwtUserId") Integer id){
        List<TOrderArrears> orderNums = orderArrearsService.list(new QueryWrapper<TOrderArrears>().eq("player_user",id).eq("arrears_status","欠费"));
        if(orderNums.size()<1){
            return APIEntity.fail("暂无欠费订单");
        }
        //List<TOrder> orderNums = orderService.list(new QueryWrapper<TOrder>().select("order_num").in("order_id",ids));
        return APIEntity.success(orderNums).setMessage("您有"+orderNums.size()+"个欠费订单待支付");
    }


    /**
     * 获取补充支付订单信息
     * @param
     * @return
     */
    @ApiOperation(value = "获取补充支付订单信息",notes = "参数：[key]为地址栏后缀，如H5页面地址栏：https://su.tcjskd.com/00ibfs<br>则key值为：00ibfs")
    @GetMapping("/get/info")
    public APIEntity<JSONObject> supplyPay(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,String orderNum){
        TOrder order=orderService.getByNum(orderNum);
        JSONObject cost=null;
        //获取待支付差价
        BigDecimal price=null;
        if (SfExpressServer.NAME.equals(order.getThirdName())){
            APIEntity<OrderDetailDO> sfRes=sfServer.orderDetail(order.getOrderNum(),order.getThirdNum());
            if (sfRes.checkSuccess()){
                price=sfRes.getBody().getOrderPrice().subtract(order.getOrderFactPrice().add(order.getPrefAmount()));
            }
        }
        if (HuolalaServer.NAME.equals(order.getThirdName())){//货拉拉确认账单补付
            price=huolalaServer.huoLaLaSupplyPay(orderNum);
            order.setAllPrice(price);
            cost=ThirdSmUtils.huolalaCostInfo(order,orderService.getHuolalaToken());
        }
        if (JdServer.NAME.equals(order.getThirdName())){//京东补付
            price=jdServer.computeSupplyPay(orderNum);
            cost=ThirdSmUtils.costInfo(order);
        }
        if (price==null){
            log.info("它咋就到这了呢1：{}",price);
            return APIEntity.fail("价格正在核对中，请稍后~");
        }
        if (price.compareTo(new BigDecimal("0"))<1){
            return APIEntity.fail("您的订单已补付完成！");
        }
        switch (order.getOrderStatus()){
            case "已取消":
            case "已退款":
            case "退款中":
                return APIEntity.fail("您的订单已经取消！");
            default:
                break;
        }

        JSONObject supplyInfo=new JSONObject();
        supplyInfo.put("order", ThirdSmUtils.orderInfo(order));
        supplyInfo.put("cost",cost);
        supplyInfo.put("reason","耗材使用或物品重量体积变化");
        if(cost.getBigDecimal("waitPrice").compareTo(new BigDecimal("0"))>0){
            supplyInfo.put("payStatus",1);
        }
        else {
            supplyInfo.put("payStatus",0);
        }
        return APIEntity.success(supplyInfo);
    }

    /**
     * 系统内第三方补充支付
     * 此为第三方补充支付接口
     * 还有一个H5的
     * @param
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation("******第三方补充支付*******")
    @GetMapping("/third/order/suppl/pay")
    public APIEntity payBehalf(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,String orderNum,String type, HttpServletRequest request) throws Exception {
        TCustomer customer = customerService.getById(id);
        TOrder order = orderService.getOne(new QueryWrapper<TOrder>().eq("order_num",orderNum));
        String openId = null;
        if (order == null) {
            log.error("未找到该订单信息");
            return APIEntity.fail("未找到该订单信息！");
        }
        //获取待支付差价
        BigDecimal price=null;
        if (SfExpressServer.NAME.equals(order.getThirdName())){
            APIEntity<OrderDetailDO> sfRes=sfServer.orderDetail(order.getOrderNum(),order.getThirdNum());
            if (sfRes.checkSuccess()){
                price=sfRes.getBody().getOrderPrice().subtract(order.getOrderFactPrice().add(order.getPrefAmount()));
            }
        }
        if (HuolalaServer.NAME.equals(order.getThirdName())){//货拉拉确认账单补付
            price=huolalaServer.huoLaLaSupplyPay(orderNum);
            order.setAllPrice(price);
        }
        if (JdServer.NAME.equals(order.getThirdName())){//京东补付
            price=jdServer.computeSupplyPay(orderNum);
            log.info("京东金额核对：{}",price);
        }
        if (price==null){
            return APIEntity.fail("价格正在核对中，请稍后~");
        }
        if (price.compareTo(new BigDecimal("0"))<1){
            return APIEntity.fail("该订单已经补付成功");
        }
        TPay pay  =payService.createBeforePay(order,"第三方补充支付","客户支付",payConst.getway(type));
        if("JSAPI".equals(type)){
            openId = customer.getOpenId();
        }
        if("aliClient".equals(type)){
            TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id",customer.getCustomerId()).eq("wx_app_type","ALICLIENT"));
            if(wxUser == null){
                return APIEntity.fail("请用户授权");
            }
            openId = wxUser.getWxUserOpenid();
        }
        if("kuaiShou".equals(type)){
            TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id",customer.getCustomerId()).eq("wx_app_type","KUAISHOU"));
            if(wxUser == null){
                return APIEntity.fail("请用户授权");
            }
            openId = wxUser.getWxUserOpenid();
        }
        String payNum = pay.getPayNum();
        JSONObject object = payConst.getObject(type,payNum,openId,price,request);
        return object==null?APIEntity.fail("客户调起"+payConst.getway(order.getType())+"支付错误"):APIEntity.success(object);
    }

}
