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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.TPay;
import com.bohuikeji.delivery.backstage.entity.third.OrderDetailDO;
import com.bohuikeji.delivery.backstage.service.ITOrderService;
import com.bohuikeji.delivery.backstage.service.ITPayService;
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.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.vo.ShortUrlVo;
import com.bohuikeji.frame.module.admin.utils.CiphertextUtils;
import com.bohuikeji.frame.module.admin.utils.UrlUtils;
import com.bohuikeji.frame.module.admin.wxpay.WXPayUtil;
import com.bohuikeji.frame.module.admin.wxpayv3.WxPayV3Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * H5页面订单相关接口
 * @author 孙劲辉
 */
@Api(tags = {"H5订单相关接口"})
@RequiredArgsConstructor
@Slf4j
@RestController
@RequestMapping("/api/h5/order")
public class H5OrderApi {

    final JdServer jdServer;
    final SfExpressServer sfServer;
    final HuolalaServer huolalaServer;
    final ITOrderService orderService;
    final ITPayService payService;
    private static final DateTimeFormatter dt = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");


    /**
     * 获取补充支付订单信息
     * @param key 短地址参数key
     * @return
     */
    @ApiOperation(value = "获取补充支付订单信息",notes = "参数：[key]为地址栏后缀，如H5页面地址栏：https://su.tcjskd.com/00ibfs<br>则key值为：00ibfs")
    @GetMapping("/info")
    public APIEntity<JSONObject> supplyPay(@RequestParam("key") @ApiParam(value = "查询key",required = true,example = "00ibfs") String key){
        ShortUrlVo vo=UrlUtils.getSortUrlVo(key);
        JSONObject cost=null;
        if (vo==null){
            return APIEntity.fail("该链接已失效，您的订单已取消。");
        }
        String orderNum=vo.getData();

        TOrder order=orderService.getByNum(orderNum);
        //获取待支付差价
        BigDecimal price=null;
        if (SfExpressServer.NAME.equals(order.getThirdName())){
            APIEntity<OrderDetailDO> sfRes=sfServer.orderDetail(orderNum,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){
            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));
        //JSONObject cost=ThirdSmUtils.costInfo(order);
        supplyInfo.put("cost",cost);
        supplyInfo.put("reason","耗材使用或物品重量体积变化");
        if(cost.getBigDecimal("waitPrice").compareTo(new BigDecimal("0"))>0){
            //加密订单号，作为调起支付的识别key
            supplyInfo.put("payKey", CiphertextUtils.encrypt(orderNum));
            supplyInfo.put("payStatus",1);
        }
        else {
            supplyInfo.put("payStatus",0);
        }
        //获取时间差,减去48小时有效支付时间
        long l = (System.currentTimeMillis() - vo.getTimestamp()-(1000*60*60*48))/1000;
        //l为负，代表没到2小时，l为正代表已超过2小时，直接置为0
        l=l<0?-l:0;
        //计算剩余时
        long h=l/(60*60);
        //计算剩余分
        long m=(l%(60*60))/60;
        //计算剩余秒
        long s=l%60;
        JSONObject time=new JSONObject();
        time.put("hour",h);
        time.put("second",s);
        time.put("minute",m);
        LocalDateTime endTime =LocalDateTime.ofEpochSecond((vo.getTimestamp()+(1000*60*60*48))/1000,0, ZoneOffset.ofHours(8));
        time.put("endTime", dt.format(endTime));
        supplyInfo.put("payTime",time);
        return APIEntity.success(supplyInfo);
    }

    @ApiOperation("******第三方补充支付*******")
    @GetMapping("/third/suppl/pay")
    public APIEntity payBehalf(String payKey, HttpServletRequest request) throws Exception {
        log.info("参数：[{}]", payKey);
        String orderNum  = CiphertextUtils.decrypt(payKey);
        TOrder order = orderService.getOne(new QueryWrapper<TOrder>().eq("order_num",orderNum));
        if (order == null) {
            log.error("未找到该订单信息");
            return APIEntity.fail("未找到该订单信息！");
        }
        //获取待支付差价
        BigDecimal price=null;
        if (SfExpressServer.NAME.equals(order.getThirdName())){
            APIEntity<OrderDetailDO> sfRes=sfServer.orderDetail(orderNum,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);
            log.info("货拉拉金额核对：{}",price);
        }
        if (JdServer.NAME.equals(order.getThirdName())){//京东补付
            price=jdServer.computeSupplyPay(orderNum);
        }
        /*else {
            price=jdServer.computeSupplyPay(orderNum);
        }*/
        if (price==null){
            return APIEntity.fail("价格正在核对中，请稍后~");
        }
        if (price.compareTo(new BigDecimal("0"))<1){
            return APIEntity.fail("该订单已经补付成功");
        }
        TPay pay = payService.getOne(new QueryWrapper<TPay>().eq("merchant_num", order.getOrderNum()).in("pay_status", "待付款"));
        if(pay == null){
            pay = payService.createBeforePay(order, "第三方补充支付", "客户支付", "微信");
        }
        String h5Url = WxPayV3Util.V3H5(request,"v3/pay/transactions/h5", pay.getPayNum(), new BigDecimal(WXPayUtil.changeToFen(price)), "订单补充支付");
        return APIEntity.success(h5Url);
    }


}
