import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/data/address.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/down_order.dart';
import 'package:huixiang/retrofit/data/min_order_info.dart';
import 'package:huixiang/retrofit/data/wx_pay.dart';
import 'package:huixiang/view_widget/login_tips_dialog.dart';
import 'package:retrofit/retrofit.dart';

import 'data/activity_actRecord_details.dart';
import 'data/activity_area_list.dart';
import 'data/activity_details.dart';
import 'data/activity_order_list.dart';
import 'data/findMiNiGroupList.dart';
import 'data/home_recommend_list.dart';
import 'data/launch_join_act.dart';
import 'data/miNiDetail.dart';
import 'data/settleOrderInfo.dart';
import 'data/shoppingCart.dart';
import 'data/shopping_home_config.dart';

part 'min_api.g.dart';

// const base_url = "https://pos.api.lotus-wallet.com/app/"; ///正式
// const baseUrl = "https://pos.api.lotus-wallet.com/app/"; ///正式


// const base_url = "http://user.prod.kunqi.lotus-wallet.com/app/"; ///222
// const baseUrl = "http://user.prod.kunqi.lotus-wallet.com/app/"; ///222

// const base_url = "http://192.168.10.236:8765/app/";///费韬
// const baseUrl = "http://192.168.10.236:8765/app/";///费韬


const base_url = "http://192.168.10.96:8765/app/";///詹云久
const baseUrl = "http://192.168.10.96:8765/app/";///詹云久


// const base_url = "http://192.168.10.37:8766/app/";
// const baseUrl = "http://192.168.10.37:8766/app/";

///调用小程序的接口
@RestApi(baseUrl: baseUrl)
abstract class MinApiService {
  factory MinApiService(
    Dio dio, {
    String baseUrl,
    BuildContext context,
    String token,
    String tenant,
    String storeId,
    bool showLoading = false,
  }) {
    Map<String, dynamic> headers =
        (token == null || token == "") ? {} : {'token': "Bearer $token"};
    if (tenant != null && tenant != "") {
      headers["tenant"] = tenant;
    }
    if (storeId != null && storeId != "") {
      headers["store_id"] = storeId;
    }
    headers["Environment"] = "app";
    dio.options = BaseOptions(
      connectTimeout: 15000,
      receiveTimeout: 15000,
      headers: headers,
      responseType: ResponseType.json,
    );
    dio.interceptors.add(
      InterceptorsWrapper(onRequest: (RequestOptions options) {
        debugPrint(
            "\n======================= Min_请求数据 =======================");
        debugPrint("method = ${options.method.toString()}");
        debugPrint("url = ${options.uri.toString()}");
        debugPrint("headers = ${options.headers}");
        if (showLoading && !EasyLoading.isShow) {
          //是否显示loading
          EasyLoading.show(status: S.of(context).zhengzaijiazai);
        }
        if (options.data is FormData) {
          debugPrint("params data = FormData");
        } else {
          debugPrint("params data = ${jsonEncode(options.data)}");
        }
        debugPrint("params queryParameters = ${options.queryParameters}");
      }, onResponse: (Response response) {
        debugPrint(
            "\n======================= Min_响应数据开始 =======================");
        if (showLoading && EasyLoading.isShow) {
          EasyLoading.dismiss();
        }
        debugPrint("code = ${response.statusCode}");
        p(jsonEncode(response.data));

        // debugPrint(jsonEncode(response.data), wrapWidth: response.data.toString().length);

        Map map = response.data;
        if (map["code"] != 0) {
          EasyLoading.dismiss();
        }
        if (map["code"] == 40005 || map["code"] == 40001) {
          if (!LoginTipsDialog().isShow) {
            // print("show: ${LoginTipsDialog().isShow}");
            LoginTipsDialog().show(context);
          }
        } else if (map["code"] != 0 && response.request.baseUrl == baseUrl) {
          ///高德地图的poi服务请求不需要toast
          SmartDialog.showToast(map["msg"], alignment: Alignment.center);
        }
        debugPrint(
            "======================= Min_响应数据结束 =======================\n");
      }, onError: (DioError e) {
        if (EasyLoading.isShow) {
          EasyLoading.dismiss();
        }
        debugPrint(
            "\n======================= Min_错误响应数据 =======================");
        debugPrint("type = ${e.type}");
        debugPrint("message = ${e.message}");
        debugPrint("\n");
      }),
    );

    if (kReleaseMode) {
      baseUrl = base_url;
    }
    return _MinApiService(dio, baseUrl: baseUrl);
  }

  static void p(String msg) {
    int maxStrLength = 900;
    while (msg.length > maxStrLength) {
      debugPrint(msg.substring(0, maxStrLength), wrapWidth: maxStrLength);
      msg = msg.substring(maxStrLength);
    }
    debugPrint(msg, wrapWidth: maxStrLength);
  }

  /// 会员信息
  @GET("/member/info")
  Future<BaseData> memberInfo();

  ///小程序查询分组及商品列表
  @POST("product/findMiNiGroupList")
  Future<BaseData<List<FindMiNiGroupList>>> findMiNiGroupList(
      @Body() Map<String, dynamic> param);

  ///小程序查询商品详情/規格选择
  @GET("/product/queryMiNiProductDetail?id={id}")
  Future<BaseData<MiNiDetail>> miNiDetail(@Path("id") String id);

  ///添加购物车
  @POST("shoppingcart")
  Future<BaseData<List<ShoppingCart>>> addShoppingCart(@Body() Map<String, dynamic> param);

  ///获取购物车商品
  @GET("shoppingcart")  ///?tableId={tableId}
  Future<BaseData<List<ShoppingCart>>> getShoppingCart(@Query("tableId") int tableId);

  ///清空购物车商品
  @GET("shoppingcart/delCart")
  Future<BaseData<bool>> clearShoppingCart();

  ///修改购物车
  @PUT("shoppingcart")
  Future<BaseData<List<ShoppingCart>>> shoppingCart1(@Body() Map<String, dynamic> param);

  ///修改购物车商品数量
  @PUT("shoppingcart/single")
  Future<BaseData<List<ShoppingCart>>> shoppingCartSingle(@Body() Map<String, dynamic> param);

  ///订单结算信息
  @POST("order/getOrderInfo")
  Future<BaseData<SettleOrderInfo>> getOrderInfo(@Body() Map<String, dynamic> param);

  ///查看订单详情
  @POST("order/getOrderDetail")
  Future<BaseData<MinOrderInfo>> getOrderDetails(@Body() Map<String, dynamic> param);

  ///查询用户所有收货地址
  @GET("address/queryMemberAddress")
  Future<BaseData<List<Address>>> queryAddress();

  ///小程序下单
  @POST("order/placeOrderFirst")
  Future<BaseData<DownOrder>> placeOrderFirst(@Body() Map<String, dynamic> param);

  ///小程序下单加菜
  @POST("order/addOrder")
  Future<BaseData<DownOrder>> addOrder(@Body() Map<String, dynamic> param);

  /// 结算
  @POST("order/settlement")
  Future<BaseData<WxPay>> settlementWx(@Body() Map<String, dynamic> param);

  /// 结算
  @POST("order/settlement")
  Future<BaseData> settlementApi(@Body() Map<String, dynamic> param);

  ///查询店铺商家详情
  @POST("store/getStore")
  Future<BaseData> queryStoreInfo1(@Body() Map<String, dynamic> param);

  /// 父订单信息
  @GET("order/getParentInfo?tableId={tableId}")
  Future<BaseData> getParentInfo(@Path("tableId") String tableId);

  /// 小程序商品推荐/为你推荐
  @GET("product/recommendList")
  Future<BaseData<List<HomeRecommendList>>> recommendList();

  ///获取门店首页配置
  @GET("store/homeConfig")
  Future<BaseData<ShoppingHomeConfig>> homeConfig();

  ///活动专区,秒杀,砍价,拼团
  @GET("actTemplate/findActListByType?allDay={allDay}&type={type}")
  Future<BaseData<ActivityAreaList>> findActListByType(@Path("allDay") bool allDay,
      @Path("type") String type);

  /// APP、小程序点击查看活动列表的某一个活动详情
  @GET("actTemplate/viewProduct?actProductId={actProductId}&type={type}")
  Future<BaseData<ActivityDetails>> viewProduct(@Path("actProductId") String actProductId,
      @Path("type") String type);

  /// 发起活动
  @POST("actTemplate/launchAct")
  Future<BaseData<LaunchJoinAct>> launchAct(@Body() Map<String, dynamic> param);

  /// 参与活动
  @POST("actTemplate/joinAct")
  Future<BaseData<LaunchJoinAct>> joinAct(@Body() Map<String, dynamic> param);

  /// 活动付款
  @POST("actTemplate/actPay")
  Future<BaseData> actPay(@Body() Map<String, dynamic> param);

  /// 查看我的拼团、砍价、列表
  @POST("actTemplate/showMyActList")
  Future<BaseData<List<ActivityOrderList>>> showMyActList(@Body() Map<String, dynamic> param);

  /// 查看某一个发起的拼团、砍价详情
  @GET("actTemplate/showOneAct?actRecordId={actRecordId}")
  Future<BaseData<ActivityActRecordDetails>> showOneAct(@Path("actRecordId") String actRecordId);

}