
import 'package:fake_push/fake_push.dart';
import 'package:flustars/flustars.dart' as f;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/common/user_db.dart';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/click_item.dart';
import 'package:liftmanager/widgets/my_button.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/internal/bbs/provide/websocket.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'dart:math';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:liftmanager/internal/account/model/user_info_entity.dart';
import 'package:liftmanager/internal/wode/model/version_item.dart';
import 'package:liftmanager/widgets/update_dialog.dart';
import 'dart:async';
import 'package:package_info/package_info.dart';
import 'package:liftmanager/cache/cache_manager.dart';
import 'package:liftmanager/internal/wode/wode_router.dart';
import 'package:liftmanager/utils/theme_utils.dart';

class SettingPage extends StatefulWidget{

  SettingPage(this.indexNow);

  final String indexNow;
  @override
  State<StatefulWidget> createState() {
    return SettingPageState();
  }
}

class SettingPageState extends State<SettingPage>{
  WebSocketProvide provider = WebSocketProvide();
  Push _push = Push();
  int indexNow;
  String checkFalse = "tab_first/check_false";
  String checkTrue = "tab_first/check_true";
  StreamSubscription<fluwx.WeChatAuthResponse> _wxlogin;
  VersionItem versionItem = VersionItem();
  PackageInfo packageInfo;
  bool _isWechatInstalled = false;
  UserInfoEntity userInfoEntity = UserInfoEntity();
  String sizeStr = "";
  // void removeSocket () async{
  //   SharedPreferences prefs = await SharedPreferences.getInstance();
  //   prefs.remove("sessionIdObj");
  // }

  @override
  void initState() {
    if(mounted){
      setState(() {
        indexNow = int.tryParse(widget.indexNow);
      });
    }
    
    
    super.initState();

    _initFluwx();
    getSize();
    getInfo();
    _wxlogin = fluwx.responseFromAuth.listen((res) {
      switch (res.errCode) {
        case -4:
          {
            //拒绝
            toasts("已拒绝");
            break;
          }
        case -2:
          {
            //取消
            toasts("已取消");
            break;
          }
        case 0:
          {
            if (res.type != 2) {
              bindMobile(res.code);
            }
            break;
          }
      }
    });
    getUserInfo();
    getNewVersion();
  }

  getNewVersion(){
    ApiService(context: context).version(onSuccess: (res){
      if(res !=null){
        versionItem = res;
        setState(() {

        });
      }
    },onError: (code,msg){
      toasts(msg);
    });
  }

  getInfo() async {
    packageInfo = await PackageInfo.fromPlatform();
  }

  _initFluwx() async {
    await fluwx.registerWxApi(
        appId: "wx0f10e6386fb9969e",
        doOnAndroid: true,
        doOnIOS: true,
        universalLink: "https://www.edtyun.com/");
    var result = await fluwx.isWeChatInstalled();
    _isWechatInstalled = result;
    setState(() {});
  }

  void getUserInfo() {
    ApiService(context: context).userInfo(
        onSuccess: (data) {
          userInfoEntity = data;
          setState(() {});
        },
        onError: (code, msg) {});
  }

  bindMobile(authCode) {
    ApiService(context: context).accountAppBindMobile(authCode,
        onSuccess: (res) {
      userInfoEntity.wxBindFlag = true;
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  getSize() async {
    int size = await getCacheSize();
    if (size < 1024) {
      sizeStr = "${size}Kb";
    } else if (size < 1024 * 1024) {
      sizeStr = "${size / 1024}Mb";
    }
  }

  void _showUpdateDialog() {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return UpdateDialog(content: versionItem.content,url:versionItem.url,version: versionItem.version,forceUpdate: versionItem.forceUpdate==1?true:false,);
        }
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _wxlogin.cancel();
  }

  updateUser(alipayAccount){
    NewApiService().updateUser({
          "userId":FlutterStars.SpUtil.getString(Constant.userId),
          "showWhichName":alipayAccount
        }, onSuccess: (res) {
          String initThisUserInfomation = randomInt(1111, 9999).toString() +
            DateTime.now().millisecondsSinceEpoch.toString();
        FastNotification.push("initUserInfomation", initThisUserInfomation);
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  randomInt(int min, int max) {
    return new Random().nextInt(max) % (max - min + 1) + min;
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;

    String theme = FlutterStars.SpUtil.getString(Constant.theme);
    String themeMode;
    switch (theme) {
      case "Dark":
        themeMode = "开启";
        break;
      case "Light":
        themeMode = "关闭";
        break;
      default:
        themeMode = "跟随系统";
        break;
    }
    
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: MyAppBar(
        centerTitle: "系统设置",
      ),
      body: Stack(
          children: <Widget>[
            Container(
              // padding: EdgeInsets.only(top:70),
              child:ListView(
                children:<Widget>[
                  Container(
                          decoration: BoxDecoration(
                            border: Border(
                              bottom: BorderSide(width: 1, color:Color(0xfff5f5f5)),
                            ),
                          ),
                          padding: EdgeInsets.only(left:ScreenUtil().setWidth(15),right:ScreenUtil().setWidth(15)),
                          height:ScreenUtil().setWidth(60),
                          child:Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children:<Widget>[
                              Text(
                                    "昵称/名称切换",
                                    style: TextStyle(
                                      // fontSize:ScreenUtil().setSp(14)
                                    ),
                                    textAlign:TextAlign.start,
                                  ),
                              Row(
                                children: <Widget>[
                                  
                                  GestureDetector(
                                    child: Container(
                                      // padding: EdgeInsets.only(top:10,left:5,right:5,bottom:10),
                                      child:Row(
                                        children:<Widget>[
                                           LoadAssetImage(
                                              // image: AssetImage(i['img']),
                                              indexNow == 1?checkTrue:checkFalse,
                                              width: ScreenUtil().setWidth(20),
                                              height:ScreenUtil().setWidth(20),
                                              // alignment: Alignment.centerLeft,
                                          ),
                                          Container(
                                            width:5,
                                            child:null
                                          ),
                                          Text(
                                            "昵称",
                                            style: TextStyle(
                                              // color:Color(0xff000000),
                                              // fontSize:ScreenUtil().setSp(14)
                                            ),
                                            textAlign:TextAlign.start,
                                          ),
                                        ]
                                      )
                                    ),
                                    onTap: (){
                                      setState(() {
                                        indexNow = 1;
                                        updateUser(1);
                                      });
                                      print(indexNow);
                                    },
                                  ),
                                  Container(
                                    width:15,
                                    child:null
                                  ),
                                  GestureDetector(
                                    child: Container(
                                      // padding: EdgeInsets.only(top:10,left:5,right:5,bottom:10),
                                      child:Row(
                                        children:<Widget>[
                                           LoadAssetImage(
                                              // image: AssetImage(i['img']),
                                              indexNow == 2?checkTrue:checkFalse,
                                              width: ScreenUtil().setWidth(20),
                                              height:ScreenUtil().setWidth(20),
                                              // alignment: Alignment.centerLeft,
                                          ),
                                          Container(
                                            width:5,
                                            child:null
                                          ),
                                          Text(
                                            "名称",
                                            style: TextStyle(
                                              // color:Colors.black,
                                              // fontSize:ScreenUtil().setSp(14)
                                            ),
                                            textAlign:TextAlign.start,
                                          ),
                                        ]
                                      )
                                    ),
                                    onTap: (){
                                      setState(() {
                                        indexNow = 2;
                                        updateUser(2);
                                      });
                                      print(indexNow);
                                    },
                                  ),
                                ],
                              ),
                              
                            ]
                          )
                        ),
                  // ClickItem(title: "修改密码", content: "",onTap: (){
                  //   // NavigatorUtils.push(context, BbsRouter.videoDetail);
                  // },),
                  // ClickItem(title: "帮助与反馈", content: "",onTap: (){
                  //   // NavigatorUtils.push(context, BbsRouter.videoDetail);
                  // },),
                  ClickItem(
                    title: "清理缓存",
                    content: sizeStr,
                    onTap: () {
                      showAlert(
                          context,
                          "提示",
                          "清除所有的保养暂存记录？",
                          "清除",
                          () {
                            NavigatorUtils.goBack(context);
                            clearCache();
                            getSize();
                            toasts("已清除");
                          },
                          txt2: "取消",
                          onPre2: () {
                            NavigatorUtils.goBack(context);
                          });
                    },
                  ),
                  Offstage(
                      offstage: !_isWechatInstalled,
                      child: ClickItem(
                        title: "微信绑定",
                        content: userInfoEntity.wxBindFlag ? '已绑定' : '未绑定',
                        onTap: () {
                          if (userInfoEntity.wxBindFlag) {
                            return;
                          }
                          fluwx.sendWeChatAuth(
                            scope: "snsapi_userinfo",
                          );
                        },
                      )),
                  ClickItem(
                      title: "夜间模式",
                      content: themeMode,
                      onTap: () => NavigatorUtils.push(context, WodeRouter.themePage)),
                  ClickItem(
                    title: "版本",
                    content: packageInfo?.version??"",
                    onTap: (){
                      if(versionItem.code > int.parse(packageInfo?.buildNumber)){
                        _showUpdateDialog();
                      }else{
                        toasts("已是最新版本。");
                      }

                    },
                  ),
                ]
              )
            ),
            Positioned(
              bottom:0,
              left:0,
              child:Container(
                width: width,
                padding: EdgeInsets.only(top:ScreenUtil().setWidth(15),bottom:ScreenUtil().setWidth(15),left:ScreenUtil().setWidth(25),right:ScreenUtil().setWidth(25)),
                color:ThemeUtils.getTabsBg(context),
                child: Container(
                      height:ScreenUtil().setWidth(44),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(ScreenUtil().setWidth(22)),
                        border: Border.all(
                          width:0.5,
                          color:Colors.black,
                        )
                      ),
                      child: FlatButton(
                        // padding: EdgeInsets.all(15.0),
                        child: Text("退出登录"),
                        // textColor: Colors.white,
                        onPressed: () {
                          
                          showAlert(context, "提示", "是否确定退出？", "确定", () {
                            User().clearUser();
                            FlutterStars.SpUtil.putBool('isInitLink', false);
                            Provider.of<WebSocketProvide>(context,listen: false).cancelTimer();
                            Provider.of<WebSocketProvide>(context,listen: false).closeWebSocket();
                            
                            // removeSocket();
                            _push.unbindAccount(account: f.SpUtil.getString(Constant.phone));
                            NavigatorUtils.push(context, AccountRouter.loginPage, clearStack: true);
                          },txt2: "取消",onPre2: (){
                            NavigatorUtils.goBack(context);
                          });
                          
                        },
                      ),
                    ),
              )
            )
          ]
      // ListView(padding: EdgeInsets.all(0.0), children: <Widget>[
      //     ClickItem(title: "清理缓存", content: "0M"),
      //   Padding(
      //     padding: const EdgeInsets.all(16),
      //     child: MyButton(
      //       onPressed: (){
      //         showAlert(context, "提示", "是否确定退出？", "确定", (){
      //           User().clearUser();
      //           _push.unbindAccount(account: f.SpUtil.getString(Constant.phone));
      //           NavigatorUtils.push(context, AccountRouter.loginPage, clearStack: true);
      //         },txt2: "取消",onPre2: (){
      //           NavigatorUtils.goBack(context);
      //         });

      //       },
      //       text: "退出当前账号",
      //     ),
      //   )
      //   ])
      )
    );
  }
}
