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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.constants.huLaLaConst;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.third.OrderDetailDO;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.SfCityServer;
import com.bohuikeji.delivery.backstage.service.third.ThirdUtils;
import com.bohuikeji.delivery.backstage.service.third.base.ThirdBase;
import com.bohuikeji.delivery.backstage.util.capacity.*;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.sys.SysConfig;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.service.ITFranchiseeInformationService;
import com.bohuikeji.frame.module.admin.utils.GCJ2WGSUtils;
import com.bohuikeji.frame.module.admin.utils.MapUtils;
import com.bohuikeji.frame.module.admin.utils.SpringUtil;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

import static com.bohuikeji.delivery.backstage.service.third.base.ThirdBase.getCacheKeyPix;

/**
 * 货拉拉配送业务接口
 * @author Admin
 */
@Api(tags = {"【货拉拉】订单相关接口"})
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/huolala")
public class HuolalaApi {

    final ITConfigService configService;
    final ISysConfigService sysConfigService;
    final ITFranchiseeInformationService informationService;
    final ITCustomerService customerService;
    final ITCustomerTemplateService templateService;
    final ITOrderService orderService;
    final MqTool mqTool;
    final SfCityServer sfCityServer;
    final RedisUtil redisUtil;
    final ITCourierService courierService;
    final ThirdUtils thirdUtils;

    /**
     * 获取当前配置环境
     */
    @Value("${spring.profiles.active}")
    private String active;

    /**
     * 获取授权URL
     */
    @GetMapping("/get/url")
    @ApiOperation("获取请求连接")
    public APIEntity testGetOAuthUrl() {
        String redirectUri = "https://test.tcjskd.com/delivery/api/callback/hll/order/notice";
        String authURL = HllUtils.getAuthURL(redirectUri);
        return APIEntity.success(authURL);
    }

    @GetMapping("/get/token")
    @ApiOperation("获取货拉拉token")
    public APIEntity getToken(String code){
        SysConfig config = sysConfigService.getOneByKey(active);
        JSONObject res;
        log.info("货拉拉访问令牌信息：{}",config);
        if(config == null && StringUtils.isNotBlank(code)){
            res = HllUtils.getaccessToken(code,null);
        }else {
            res = HllUtils.getaccessToken(code,config.getConfigDataTwo());
        }
        return APIEntity.success(sysConfigService.getHuolalaToken(code,res));
    }

    /**
     * 获取已开通城市列表
     */
    @GetMapping("/get/city/list")
    @ApiOperation("判断客户所在城市是否开通")
    @ApiImplicitParams({
            @ApiImplicitParam(name="location",value="当前客户经纬度",dataType="String", paramType = "query",example = "111.665544,40.858289",defaultValue = "111.665544,40.858289")})
    public APIEntity getCityList(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,String location) {
        if(id == null){
            return APIEntity.fail("请登录后在操作。");
        }
        JSONObject jsonObject = null;
        if(StringUtils.isBlank(location)){
            return APIEntity.fail("您的定位未开启，请开启定位。");
        }
        Integer cityId = HllUtils.getCityId(location);
       if(cityId == null){
           return APIEntity.fail("您所在的城市尚未开通，无法提供服务。");
       }
        return APIEntity.success(jsonObject);
    }


    /**
     * 获取城市可选车型及增值服务
     */
    @GetMapping("/get/city/info")
    @ApiOperation("获取城市可选车型及增值服务")
    public APIEntity getCityInfo(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id, Integer cirtyId) {
        return APIEntity.success(HllUtils.getEcityInfo(cirtyId));
    }

    /**
     * 地址检索（新）
     * @param kw 地址关键字
     * @param city 城市
     * @return
     */
    @GetMapping("/get/poi/search/info")
    @ApiOperation("地址检索（新）")
    public APIEntity getPoiSearch(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,String kw,String city) {
        String token = orderService.getHuolalaToken();
        return APIEntity.success(HllUtils.getECitySearch(token,kw,city));
    }

    /**
     * 坐标系转换
     * @param id
     * @param location
     * @return
     */
    @GetMapping("/get/lonlat/coordinate/info")
    @ApiOperation("坐标系转换")
    @ApiImplicitParams({
            @ApiImplicitParam(name="location",value="当前派送员经纬度",dataType="String", paramType = "query",example = "111.665544,40.858289",defaultValue = "111.665544,40.858289")})
    public APIEntity getLonLat(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,String location) {
        AddressVo address= MapUtils.getAddressReGeo(location);
        return APIEntity.success(GCJ2WGSUtils.gcstoWGSLat(Double.parseDouble(address.getLat()),Double.parseDouble(address.getLng())));
    }

    /**
     * 货拉拉下单
     * @param id
     * @param orderId
     * @return
     */
    @GetMapping("/get/order/test/place ")
    @ApiOperation("货拉拉下单测试")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orderId",value="订单id",dataType="integer", paramType = "query",example = "147404",defaultValue = "")})
    public APIEntity placeOrder(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,Integer orderId) {
        TOrder order = orderService.getById(orderId);
        order.setHuoToken(orderService.getHuolalaToken());
        //mqTool.sendMsg(order.getOrderNum(), OrderCreateListener.class);
        return APIEntity.success(HllUtils.getEorderRequest(order));//HllUtils.getEorderRequest1(order)
    }

    /**
     * 获取货拉拉订单详情
     */
    @GetMapping("/get/order/info")
    @ApiOperation("获取货拉拉订单详情")
    public APIEntity getOrderInfo(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id, String orderNum) {
        String token = orderService.getHuolalaToken();
        return APIEntity.success(HllUtils.getEOrderDetail(token,orderNum));
    }

    /**
     * 确认货拉拉订单
     */
    @GetMapping("/get/order/confirm")
    @ApiOperation("确认货拉拉订单")
    public APIEntity getOrderconfirm(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id, String thirdNum) {
        return APIEntity.success(HllUtils.getEorderConfirm(thirdNum));
    }

    /**
     * 货拉拉下单
     * @param id
     * @param
     * @return
     */
    @GetMapping("/get/order/cancel/ ")
    @ApiOperation("取消货拉拉下单")
    @ApiImplicitParams({
            @ApiImplicitParam(name="displayid",value="订单id",dataType="integer", paramType = "query",example = "147404",defaultValue = "")})
    public APIEntity cancelOrder(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,String displayid) {
        TOrder order = orderService.getOne(new QueryWrapper<TOrder>().eq("third_num",displayid));
        if("HLL".equals(order.getThirdName())){
            String token = orderService.getHuolalaToken();
            Integer deductStatus = HllUtils.getEOrderDetail(token,order.getThirdNum()).getJSONObject("data").getJSONObject("order_detail_item").getJSONObject("order_item").getInteger("order_status");
            if(!huLaLaConst.contrast(deductStatus)){
                return APIEntity.success("尊敬的客户您好，订单只有在派送前可以取消");
            }
        }
        ThirdUtils.orderCancelAll(order.getOrderNum());
        return APIEntity.success();//HllUtils.getEorderRequest1(order)
    }

    @GetMapping("/get/poi/huolala/list")
    @ApiOperation("货拉拉优惠卷列表")
    public APIEntity getCouponlist(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id) {
        /*TOrder order = orderService.getById(orderId);
        if(ShanSongUtils.travelWay(order.getMailingAddress().getAdcode()) == null){
            //throw new WebVerifiedException("该城市暂未开通汽车配送服务!");
            return APIEntity.success("该城市暂未开通汽车配送服务!");
        }*/
        return APIEntity.success(HllUtils.getEcouponList(orderService.getHuolalaToken()));
    }


    @GetMapping("/get/sf/order/status")
    @ApiOperation("顺丰订单物流状态查询")
    public APIEntity getShunFengStatus (@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,String numm) {
        JSONObject sfRes= SFCityUtils.sfListorderFeed(numm);
        return APIEntity.success(sfRes.getJSONArray("feed"));
    }

    @GetMapping("/get/sf/order/info")
    @ApiOperation("顺电通调度信息")
    public APIEntity getShunFengInfo(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,String numm) {
        //JSONObject sfRes= SFCityUtils.getSfOrderStatus(numm);
        JSONArray sfRes=SfExpressUtils.orderScheduleInfo(null,numm);
        return APIEntity.success(sfRes);
    }

    @GetMapping("/get/sf/order/kd")
    @ApiOperation("顺丰快递下单")
    public APIEntity getsfList(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,String orderNum,String thirdNum) {
        return APIEntity.success(SfExpressUtils.cancelOrder(orderNum,thirdNum));
    }

    @GetMapping("/get/ss/order/quxiao")
    @ApiOperation("第三方取消")
    public APIEntity getList(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,String orderNum,String thirdName) {
        log.info("###################################:{}",orderNum.substring(0,3));
        OrderDetailDO detail= redisUtil.get(ThirdBase.getCacheKey(orderNum,thirdName),OrderDetailDO.class);
        /*RedisUtil rdsTmp= SpringUtil.getBean(RedisUtil.class);
        List<OrderDetailDO> doList=rdsTmp.getListByPattern(getCacheKeyPix(orderNum)+"*",OrderDetailDO.class);*/
        return APIEntity.success(detail);
    }

    /*@GetMapping("/get/time/test/sssss")
    @ApiOperation("@@@@@@@@@@时间比较s测试")
    public APIEntity getTimeList(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id) {
        log.info("当前时间：{}",LocalDateTime.now());
        log.info("固定时间：{}",LocalDateTime.of(LocalDateTime.now().getYear(),LocalDateTime.now().getMonth(),LocalDateTime.now().getDayOfMonth(),18,00,00,00));
        log.info("时间比较：{}",LocalDateTime.now().isBefore(LocalDateTime.of(LocalDateTime.now().getYear(),LocalDateTime.now().getMonth(),LocalDateTime.now().getDayOfMonth(),18,00,00)));
        if(LocalDateTime.now().isBefore(LocalDateTime.of(LocalDateTime.now().getYear(),LocalDateTime.now().getMonth(),LocalDateTime.now().getDayOfMonth(),18,00,00))){
            return APIEntity.success(LocalDateTime.of(LocalDateTime.now().getYear(),LocalDateTime.now().getMonth(),LocalDateTime.now().getDayOfMonth(),18,00,00));
        }else {
            return APIEntity.success("6bb4d8181f72da3dd20d9511343d415d");
        }
    }*/


}
