package com.bohuikeji.delivery.backstage.controller.test;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bohuikeji.delivery.backstage.controller.callback.ThirdCallBack;
import com.bohuikeji.delivery.backstage.entity.TCourier;
import com.bohuikeji.delivery.backstage.entity.TCourierCard;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.third.OrderDetailDO;
import com.bohuikeji.delivery.backstage.listener.order.OrderCheckPriceListener;
import com.bohuikeji.delivery.backstage.pay.AliPay;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.JdServer;
import com.bohuikeji.delivery.backstage.service.third.SfExpressServer;
import com.bohuikeji.delivery.backstage.service.third.ShansongServer;
import com.bohuikeji.delivery.backstage.service.third.UUServer;
import com.bohuikeji.delivery.backstage.thread.ThirdThread;
import com.bohuikeji.delivery.backstage.util.capacity.SfExpressUtils;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.config.MqConf;
import com.bohuikeji.frame.module.admin.entity.back.PageEntity;
import com.bohuikeji.frame.module.admin.thread.CachedThreadPool;
import com.bohuikeji.frame.module.admin.utils.JsonUtil;
import com.bohuikeji.frame.module.admin.utils.SpringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 通知推送测试
 * @author 10552
 */
@Slf4j
@RestController
@Api(tags = {"消息推送功能测试"})
@RequestMapping("/test")
@RequiredArgsConstructor
public class Test extends ApiController {

    @Autowired
    ITCourierService courierService;
    @Autowired
    ITCourierCardService courierCardService;

    final RabbitTemplate rabbitTemplate;

    final ITOrderService orderService;
    /*final IShanSongService shanSongService;*/

    final ThirdCallBack songCallBack;
    final ITCustomerService itCustomerService;
    final UUServer uuServer;
    final ShansongServer shansongServer;
    final RedisUtil redisUtil;
    final MqConf mqConf;
    final OrderCheckPriceListener orderCheckPriceListener;
    final JdServer jdServer;
    final ISocketService socketService;
    final ITOrderArrearsService arrearsService;



    @GetMapping("/ali")
    public PageEntity aliOAuth(String auth_code,String app_id,String scope,String state){
        log.error("支付宝授权回调成功，auth_code：[{}]，app_id=[{}]，scope=[{}],state=[{}]",auth_code,app_id,scope,state);
        TCourier courier=courierService.getById(state);
        if(courier==null){
            log.error("无法识别派送员：[{}]",state);
            return PageEntity.page("courier/ali_OAuth_fail");
        }
        AlipayUserInfoShareResponse response= AliPay.getUserInfo(auth_code);
        if(response==null){
            log.error("支付宝获取用户信息失败，用户：[{}]未授",courier.getCourierName());
            return PageEntity.page("courier/ali_OAuth_fail");
        }
        if(!response.isSuccess()){
            log.error("支付宝获取用户信息失败,支付宝信息：[{}]",response.getSubMsg());
            return PageEntity.page("courier/ali_OAuth_fail");
        }
        log.error("获取到支付宝用户信息：[{}]", JsonUtil.objToJson(response).toJSONString());
        TCourierCard courierCard=new TCourierCard();
        courierCard.setCourierId(courier.getCourierId());
        courierCard.setCardBank("支付宝");
        courierCard.setBankType("网商银行");
        courierCard.setCreateDate(LocalDateTime.now());
        courierCard.setCardNum(response.getUserId());
        courierCard.setCardName(response.getNickName());
        courierCard.setIdNumber(courier.getCourierCard());
        courierCardService.save(courierCard);
        return PageEntity.page("courier/ali_OAuth_success").add("courier",courier);
    }

    @Autowired MqTool mqTool;

    private static boolean LOOP=true;
    private static Long TIME=500L;

    /**
     * 消息发送测试
     * @return
     */
    @GetMapping("/test")
    public void test() throws InterruptedException {

       List<TOrder> orderList;
       while (true){
           if (!LOOP){
               return;
           }
           orderList=orderService.list(new QueryWrapper<TOrder>()
                   .eq("third_name","SS")
                   .eq("third_price",0)
                   .notIn("order_status","已取消","已退款","退款中")
                   .orderByDesc("order_id").last(" limit 50"));
           log.error("待处理订单大小：{}",orderList.size());
           if (orderList.size()<1){
               return;
           }
           for (TOrder order:orderList){
               OrderDetailDO detailDO=shansongServer.orderDetail(order.getOrderNum(),order.getThirdNum()).getBody();
               if (detailDO!=null){
                   orderService.update(new UpdateWrapper<TOrder>().eq("order_id",order.getOrderId()).set("third_price",detailDO.getOrderPrice()));
                    log.error("订单：{}，金额：{}",detailDO.getOrderNumber(),detailDO.getOrderPrice());
               }else {
                   log.error("订单异常：{}，状态：{}",order.getOrderNum(),order.getOrderStatus());
                   continue;
               }
               Thread.sleep(TIME);
           }
       }
    }

    @GetMapping("/sf/xd")
    public JSONObject xd(Integer id){
        return SfExpressUtils.placeOrder(orderService.getById(id));
    }
    @GetMapping("/sf/qx")
    public JSONObject qx(String orderNum,String sfNum){
        return SfExpressUtils.cancelOrder(orderNum,sfNum);
    }
    @GetMapping("/sf/xq")
    public JSONObject xq(String orderNum,String sfNum){
        return SfExpressUtils.orderDetail(orderNum,sfNum);
    }
    @GetMapping("/sf/record")
    public JSONArray record(String orderNum, String sfNum){
        return SfExpressUtils.orderRecord(orderNum,sfNum);
    }

    @GetMapping("/sf/rs")
    public JSONObject rs(String orderNum){
        return SfExpressUtils.orderCreateResult(orderNum);
    }

    @GetMapping("redis/scan")
    private Object scan(String key){
        return redisUtil.scan(key);
    }

    @GetMapping("redis/get")
    private Object get(String key){
        return redisUtil.getByFinalKey(key,Object.class);
    }
    @ApiOperation("顺丰下单测试")
    @GetMapping("/sf/order/xd")
    private Object shOrder(Integer orderId) throws Exception {
            SfExpressServer expressServer=SpringUtil.getBean(SfExpressServer.class);
            TOrder order=orderService.getById(orderId);
        CachedThreadPool.execute(new ThirdThread(expressServer,order));
        return redisUtil.get(expressServer.getCacheKey(order.getOrderNum()),OrderDetailDO.class);
    }
}
