import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_alibc/flutter_alibc.dart';
import 'package:jdsdk/jdsdk.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:zhiying_comm/register.dart';
import 'package:zhiying_comm/util/shared_prefe_util.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

import 'taobao_image_viewer.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    BaseWidgetRegister.init();
    Jdsdk.init(
            appKey: '9fc3dec00b9b40cc950dfba5262cd6d3',
            appSecret: 'f785613e5fd54a129d0f0359a4e25c23')
        .then((result) {
      Logger.debug('京东初始化:${result.toString()}');
    });
    FlutterAlibc.initAlibc(version: "", appName: "").then((result) {
      Logger.debug('${result.errorCode}  ${result.errorMessage}');
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  netPost() async {
    dynamic result =
    await NetUtil.post('/api/v1/rec/featured?page=1', params: null);
    print("result === ${result?.toString()}");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('智莺-基础库'),
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Wrap(
            spacing: 10,
            children: <Widget>[
              RaisedButton(
                onPressed: () {
                  // d75d2fc6592f4526e297643446416581bd89e837
                  // cc455e0c0b6a75ff09aeb966c211fb967d69b63d
                  SharedPreferencesUtil.setStringValue(
                      GlobalConfig.SHARED_KEY_TOKEN,
                      'd75d2fc6592f4526e297643446416581bd89e837');
                },
                child: Text('登录'),
              ),
              RaisedButton(
                onPressed: () {
                  SharedPreferencesUtil.setStringValue(
                      GlobalConfig.SHARED_KEY_TOKEN, '');
                },
                child: Text('退出登录'),
              ),
              RaisedButton(
                onPressed: () {
                  NetUtil.request('/api/v1/rec/featured?page=1', params: null,
                      onError: (msg) {
                        print('onERROR = ${msg?.toString() ?? 'onError'}');
                      }, onSuccess: (json) {
                        print('onSuccess = ${json?.toString() ?? 'onSuccess'}');
                      }, onCache: (json) {
                        print('onCache = ${json?.toString() ?? 'onCache'}');
                      });
                },
                child: Text('网络异步请求(带缓存)'),
              ),
              RaisedButton(
                onPressed: () {
                  netPost();
                },
                child: Text('网络同步请求(无缓存)'),
              ),
              RaisedButton(
                onPressed: () {
                  // LogUtil.test();
                },
                child: Text('显示日志'),
              ),
              RaisedButton(
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (_) {
                    return Logger();
                  }));
                },
                child: Text('打开日志视图'),
              ),
              RaisedButton(
                onPressed: () {
//                NetUtil.request('/api/v1/mod', params: {'ids': [6] } ,method: NetMethod.POST,
//                    onSuccess: (params){
//                  Logger.log("onSuccess#$params");
//                },
//                onCache: (params){
//                  Logger.log("onCache#$params");
//                });

                  testPost();
                },
                child: Text('测试接口'),
              ),
              RaisedButton(
                onPressed: () {
                  Navigator.push(context, MaterialPageRoute(builder: (_) {
                    return TaobaoImageView();
                  }));
                },
                child: Text('抓淘宝图片'),
              ),
              RaisedButton(
                onPressed: () {
                  TaobaoAuth.auth(context);
                },
                child: Text('淘宝授权'),
              ),
              RaisedButton(
                onPressed: () {
//
                  Dio dio = Dio();
                  dio.get(
                      'http://www.hairuyi.com/?mod=appapi&act=gotojingdong&gid=60291609161&yhq_url=http%3A%2F%2Fcoupon.m.jd.com%2Fcoupons%2Fshow.action%3Fkey%3Dd97e1472a8a24c39a9463dbe72b3fa32%26roleId%3D38088450%26to%3Ditem.jd.com%2F60291609161.html')
                      .then((value) {
                    Logger.debug(value.realUri.toString());
                  });
                },
                child: Text('获取重定向地址'),
              ),
              RaisedButton(
                onPressed: () {
                  Jdsdk.openUrl(
                      url: 'http://www.hairuyi.com/?mod=appapi&act=gotojingdong&gid=60291609161&yhq_url=http%3A%2F%2Fcoupon.m.jd.com%2Fcoupons%2Fshow.action%3Fkey%3Dd97e1472a8a24c39a9463dbe72b3fa32%26roleId%3D38088450%26to%3Ditem.jd.com%2F60291609161.html');
                },
                child: Text('打开京东详情'),
              ),
              RaisedButton(
                onPressed: () async {
                  // String detailUrl = 'http://www.hairuyi.com/?mod=appapi&act=gotojingdong&gid=60291609161&yhq_url=http%3A%2F%2Fcoupon.m.jd.com%2Fcoupons%2Fshow.action%3Fkey%3Dd97e1472a8a24c39a9463dbe72b3fa32%26roleId%3D38088450%26to%3Ditem.jd.com%2F60291609161.html';
                  // String baseUrl = detailUrl.getBaseUrl();
                  // if (!baseUrl.contains('jd.com')) {
                  //   Dio dio = Dio();
                  //   var responds = await dio.get(detailUrl);
                  //   detailUrl = responds.realUri.toString();
                  // }
                  // Logger.debug(detailUrl);
                  // Jdsdk.openUrl(
                  //     url
                  //         :
                  //     detailUrl
                  // );
                },
                child: Text('嗨如意转链打开京东'),
              ),
              RaisedButton(
                onPressed: () async {
                  const url = 'weixin://';

                  if (await canLaunch(url)) {
                    await launch(url);
                  } else {
                    throw 'Could not launch $url';
                  }
                },
                child: Text('url scheme打开app'),
              ),
              RaisedButton(
                onPressed: () async {
                  Logger.error('打印日志测试');
                },
                child: Text('打印日志'),
              ),
              RaisedButton(
                onPressed: () async {
                  List<PreviewImageData> previewImageDatas = List();
                  for (var index = 0; index < 5; index++) {
                    previewImageDatas.add(PreviewImageData(
                        previewImageType: PreviewImageType.netUrl,
                        data:
                        "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1604924972652&di=2849a989df574db3fbb7a8994ea87fc3&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2Fc%2F574420055d0b9.jpg"));
                  }

                  PhotoPreview.showPhotoPreview(context, previewImageDatas,currentIndex: 0);
                },
                child: Text('预览图片'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void testPost() async {
    var cached = await NetUtil.getRequestCachedData('/api/v1/mod', params: {
      'ids': [7]
    });
    print("cahced ${cached?.toString()}");
    var param = await NetUtil.post('/api/v1/mod',
        params: {
          'ids': [7]
        },
        method: NetMethod.POST);
    print('apapapsdjfdsjf: ${param?.toString()}');
  }
}