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


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bohuikeji.delivery.backstage.controller.api.courier.CourierApi;
import com.bohuikeji.delivery.backstage.controller.api.customer.CustomerV2Api;
import com.bohuikeji.delivery.backstage.entity.TOpen;
import com.bohuikeji.delivery.backstage.entity.TOpenCallback;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.service.ITOpenService;
import com.bohuikeji.delivery.backstage.service.ITOrderService;
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.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import static com.bohuikeji.delivery.backstage.service.impl.TOpenServiceImpl.OPEN_CACHE_KEY;

/**
 * 开放平台客户配置开发接口
 * @author 孙劲辉
 */
@RequiredArgsConstructor
@Slf4j
@RestController
@RequestMapping("/api/open/config")
public class ConfigOpenApi extends ApiController {
    final ITOpenService openService;
    final RedisUtil redisUtil;
    final ITOrderService orderService;
    final CourierApi courierApi;
    final CustomerV2Api customerV2Api;

    /**
     * 设置订单通知回调地址
     * @param id
     * @param url
     * @return
     */
    @GetMapping("/get/notice")
    APIEntity orderBinding(@ApiIgnore @RequestAttribute("JwtOpenId") Integer id, String url){
        if(StringUtils.isBlank(url)){
            return APIEntity.fail("参数[url]为空");
        }
        try {
            url= URLDecoder.decode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            return APIEntity.fail("url解码失败，请检查参数是否正确！");
        }
        if(!StringUtils.isURL(url)){
            return APIEntity.fail("参数[url]无法识别，请检查是否为URL格式，或确认是否已对原始链接进行UrlCode编码。");
        }
        openService.update(new UpdateWrapper<TOpen>().set("notice_url",url).eq("id",id));
        redisUtil.del(OPEN_CACHE_KEY+id);
        return APIEntity.success("绑定更新成功！");
    }

    /**
     * 订单回调模拟
     * @param id
     * @param orderNum
     * @return
     */
    @GetMapping("/get/test")
    APIEntity noticeTest(@ApiIgnore @RequestAttribute("JwtOpenId") Integer id, String orderNum,Integer orderStatusCode){
        TOpen open=openService.getCacheById(id);
        TOrder order=orderService.getByNum(orderNum);
        if (order==null){
            return APIEntity.fail("无法找到订单："+orderNum);
        }
        if (!order.getTest()){
            return APIEntity.fail("非测试订单无法使用，回调模拟接口！");
        }
        if (open==null){
            return APIEntity.fail("无法找到开放平台账户，请先注册账号！");
        }
        //推送开放平台消息
        TOpenCallback callback=TOpenCallback.createInstance(order.getOrderNum(),order.getPlayerId());
        if (callback!=null){
            String setStatus;
            switch (orderStatusCode){
                //接单
                case 1:{
                    APIEntity res=courierApi.receipt(55,order.getOrderId(),order.getMailingAddress().getLocation(),"9999");
                    if (res.getStatus()!=200){
                        return res;
                    }
                    return  APIEntity.success();
                }
                //取消订单
                case -1:{
                    APIEntity res=customerV2Api.cancel(order.getOrderId()+"",open.getCustemerId(),"open");
                    if (res.getStatus()!=200){
                        return res;
                    }
                    return  APIEntity.success();
                }
                case 2:setStatus="去取件";break;//去取件
                case 3:setStatus="确认取件";break;//取件完成
                case 4:setStatus="去派送";break;//开始配送
                case 5:setStatus="确认收货";break;//确认送达
                default:
                    return APIEntity.fail("无法识别您的订单状态");
            }
            APIEntity res=courierApi.stateFlow(order.getOrderId(),55,setStatus,null,null,null);
            if (res.getStatus()!=200){
                return res;
            }
            return  APIEntity.success();
        }
        else {
            return APIEntity.fail("该订单尚未绑定回调地址，请先绑定地址！");
        }
    }
}
