import 'dart:convert';
import 'dart:io';

import 'package:amos_iot_login_tpl/amos_iot_login_tpl.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg_provider/flutter_svg_provider.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:open_file/open_file.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import 'package:progress_dialog/progress_dialog.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';

import '../../consts/color.dart';
import '../../consts/global_config.dart';
import '../../consts/share_prefers_key_const.dart';

import '../../model/configuration_item_model.dart';
import '../../routes/routes.dart';
import '../../services/application.dart';
import '../../utils/GetConfig.dart';
import '../../utils/flutter_toast.dart';
import '../../utils/http.dart';
import '../../utils/numer_util.dart';
import '../../utils/request.dart';
import '../../utils/user_info_manager.dart';
import '../../widgets/loading_dialog.dart';
import '../index.dart';

class Login extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: LoginContent(),
      ),
      resizeToAvoidBottomInset: false,
    );
  }
}

class LoginContent extends StatefulWidget {
  @override
  _LoginContentState createState() => _LoginContentState();
}

class _LoginContentState extends State<LoginContent> {
  final TextEditingController _accountTextController = TextEditingController();
  final TextEditingController _pwdTextController = TextEditingController();

  final FocusNode _accountFocus = FocusNode();
  final FocusNode _pwdFocus = FocusNode();
  bool isAnimating = false;
  bool rememberPwd = false;
  String theme = '';

  ProgressDialog pr;

  @override
  void initState() {
    super.initState();
    initConfig();
    getToken();
    _accountTextController.addListener(() {
      setState(() {});
    });
    _pwdTextController.addListener(() {
      setState(() {});
    });
    getBaseInfo();
  }

  Future<void> initConfig() async {
    final SharedPreferences sp = await SharedPreferences.getInstance();
    theme = sp.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
  }

  Future<void> getToken() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    if (sp.getBool('offline') == null) {
      sp.setBool('offline', false);
    }
    if (sp.getBool('offline') && sp.get('user_token') != null) {
      Navigator.of(context)
          .pushAndRemoveUntil(MaterialPageRoute(builder: (context) => Index()), (route) => route == null);
    }
  }

  // 获取初始化信息
  void getBaseInfo() async {
    final userName = await UserInfoManager.getUserName();
    final pwd = await UserInfoManager.getUserPwd();

    if (userName != null) {
      _accountTextController.text = userName;
    }
    if (pwd != null) {
      _pwdTextController.text = pwd;
      rememberPwd = true;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    final children = <Widget>[
      buildContent(context),
    ];

    /// 显示系统配置
    if (GlobalConfig.showSysConfig) {
      children.add(Positioned(
        right: 20.px,
        top: 20.px,
        child: IconButton(
          icon: const Icon(Icons.add_to_queue),
          onPressed: () {
            Application.navigateTo(context, Routes.serviceConfig).then((value) => initConfig());
          },
        ),
      ));
    }
    children.add(buildFooter(context));

    final modalProgressHUD = ModalProgressHUD(
      child: SingleChildScrollView(
        child: Stack(
          children: children,
        ),
      ),
      inAsyncCall: isAnimating,
      opacity: 0.7,
      progressIndicator: const CircularProgressIndicator(),
    );
    return GestureDetector(
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Scaffold(backgroundColor: const Color.fromRGBO(242, 246, 249, 1), body: modalProgressHUD));
  }

  // 主体内容
  Widget buildContent(context) {
    return Column(
      children: <Widget>[
        SizedBox(
          height: 88.px,
        ),
        Image.asset(
          'assets/images/login/logo_' + theme + '.png',
          width: 130.0,
          height: 119.0,
        ),
        Text(
          GlobalConfig.loginSysName,
          style: Theme.of(context).textTheme.headline1.copyWith(letterSpacing: 2.px),
        ),
        Text(
          'Safety pre-control system',
          style: Theme.of(context).textTheme.subtitle2,
        ),
        SizedBox(
          height: 28.px,
        ),
        Padding(
          padding: EdgeInsets.only(left: 60.5.px, right: 60.5.px),
          child: Column(
            children: <Widget>[
              LoginInput(
                theme: theme,
                focusNode: _accountFocus,
                icon: _accountFocus.hasFocus
                    ? Image(
                        image: const Svg('assets/images/icon_person_selected.svg', size: Size(16, 16)),
                        gaplessPlayback: true,
                        color: GetConfig.getColor(theme),
                      )
                    : const Image(
                        image: Svg('assets/images/icon_person.svg', size: Size(16, 16)),
                        gaplessPlayback: true,
                      ),
                controller: _accountTextController,
                hintText: '账号',
              ),
              SizedBox(
                height: 16.px,
              ),
              LoginInput(
                theme: theme,
                security: true,
                focusNode: _pwdFocus,
                icon: _pwdFocus.hasFocus
                    ? Image(
                        image: const Svg('assets/images/icon_pwd_selected.svg', size: Size(16, 16)),
                        gaplessPlayback: true,
                        color: GetConfig.getColor(theme))
                    : const Image(image: Svg('assets/images/icon_pwd.svg', size: Size(16, 16)), gaplessPlayback: true),
                controller: _pwdTextController,
                hintText: '密码',
              ),
              SizedBox(
                height: 18.px,
              ),
              InkWell(
                child: Row(
                  children: <Widget>[
                    rememberPwd
                        ? Image.asset(
                            'assets/images/icon_check_selected_' + this.theme + '.png',
                            width: 12,
                            height: 12,
                          )
                        : Image(
                            image: Svg('assets/images/icon_check_unselected.svg',
                                size: Size(12.px.toDouble(), 12.px.toDouble())),
                            gaplessPlayback: true,
                            color: GetConfig.getColor(theme),
                          ),
                    SizedBox(
                      width: 8.px,
                    ),
                    Text(
                      '记住密码',
                      style: Theme.of(context).textTheme.bodyText1.copyWith(color: Color(0xFFB2B2B2)),
                    )
                  ],
                  crossAxisAlignment: CrossAxisAlignment.center,
                ),
                onTap: () {
                  setState(() {
                    rememberPwd = !rememberPwd;
                  });
                },
                highlightColor: Colors.transparent,
                splashColor: Colors.transparent,
              ),
              SizedBox(
                height: 20.px,
              ),
              Container(
                  height: 40.px,
                  width: double.infinity,
                  child: RaisedButton(
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(3.px)),
                    color: GetConfig.getColor(theme),
                    onPressed: () => login(context),
                    child: Text(
                      '登录',
                      style: Theme.of(context).textTheme.bodyText1.copyWith(color: Colors.white),
                    ),
                  ))
            ],
          ),
        )
      ],
    );
  }

  // 底部提示文字
  Widget buildFooter(context) {
    return Align(
        alignment: Alignment.bottomCenter,
        child: Padding(
          padding: EdgeInsets.only(top: MediaQuery.of(context).size.height - 40),
          child: Text(
            GlobalConfig.loginFooter,
            style: Theme.of(context).textTheme.subtitle2,
          ),
        ));
  }

//版本更新
  showUpdate(BuildContext context) async {
    setState(() {
      isAnimating = false;
    });
    pr = ProgressDialog(
      context,
      type: ProgressDialogType.Download,
      isDismissible: false,
      showLogs: true,
    );
    getDownload(context);
  }

  void getDownload(BuildContext context) async {
    //下载时显示下载进度dialog
    if (!pr.isShowing()) {
      pr.show();
    }
    //存放路径
    final path = await _apkLocalPath;
    File file = File(path + '/' + 'firerescue.apk');
    if (await file.exists()) await file.delete();
    String url = await APIUrlManager.getUpdateApkUrl();

    HttpManager().download(
        url: url,
        savePath: file.path,
        onReceiveProgress: (int count, int total) {
          pr.update(progress: num.parse(NumberUtil.formatNum(count / total * 100)), message: '文件下载中，请稍后…');
        },
        successCallback: (data) => {pr.hide(), install()},
        errorCallback: (data) => {hideDialog()});
  }

  //下载结束打开文件
  Future<void> install() async {
    pr.hide();
    String path = await _apkLocalPath;
    OpenFile.open(path + '/' + 'firerescue.apk').then((value) => pr.hide());
  }

  void hideDialog() {
    if (pr.isShowing()) {
      pr.hide();
    }
  }

  //存储路径
  Future<String> get _apkLocalPath async {
    final directory = await getExternalStorageDirectories(type: StorageDirectory.downloads);
    return directory[0].path;
  }

  // 登录
  void login(context) async {
    final userName = _accountTextController.text;
    final pwd = _pwdTextController.text;
    if (userName.isEmpty) {
      FlutterToast.toastCenter('用户名不能为空!');
      return;
    } else if (pwd.isEmpty) {
      FlutterToast.toastCenter('密码不能为空!');
      return;
    }
    setState(() {
      isAnimating = true;
    });
    final params = {'userName': '$userName', 'password': '$pwd'};
    getHome(params);
  }

  getVerson(context, vers, params) async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String version = packageInfo.version;
    if (haveNewVersion(vers, version)) {
      showUpdate(context);
    } else {
      await getHome(params);
    }
  }

  bool haveNewVersion(String newVersion, String old) {
    if (newVersion == null || newVersion.isEmpty || old == null || old.isEmpty) {
      return false;
    }
    int newVersionInt, oldVersion;
    var newList = newVersion.split('.');
    var oldList = old.split('.');
    if (newList.isEmpty || oldList.isEmpty) {
      return false;
    }
    for (int i = 0; i < newList.length; i++) {
      newVersionInt = int.parse(newList[i]);
      oldVersion = int.parse(oldList[i]);
      if (newVersionInt > oldVersion) {
        return true;
      } else if (newVersionInt < oldVersion) {
        return false;
      }
    }
    return false;
  }

  getHome(params) async {
    HttpRequest.login(params: params).then((res) {
      if (res['status'] == 200) {
        // 保存用户登录返回信息
        final result = res['result'];
        UserInfoManager.saveLoginBaseInfo(result);
        UserInfoManager.clearUserName();
        UserInfoManager.clearUserPwd();
        SharedPreferences.getInstance().then((preferences) {
          preferences.setString('loginUser', params['userName']);
          preferences.setString('user_id', result['userId']);
          preferences.setString('user_name', params['userName']);
          preferences.setString('user_token', result['token']);
          preferences.setString('product', result['product']);
          preferences.setString('appKey', result['appKey']);
          preferences.setString('jpushUserKey', result['jpushUserKey']);
          preferences.setString('amos_userName', params['userName']);
          if (rememberPwd) {
            preferences.setString('amos_userPwd', params['password']);
          } else {
            preferences.setString('amos_userPwd', '');
          }
        });
        getData(context);
      }
    }).catchError((_) {
      setState(() {
        isAnimating = false;
      });
    });
  }

  // 获取数据
  Future<void> getData(context) async {
    HttpRequest.getSelectCompany().then((res) {
      setState(() {
        isAnimating = false;
      });
      if (res['status'] == 200) {
        var _result = res['result'];
        handleTurn(context, _result);
      }
    }).catchError((_) {
      setState(() {
        isAnimating = false;
      });
    });
  }

  // 处理跳转
  void handleTurn(context, _result) {
    if (_result == null) return;
    try {
      List companys = _result['companys'];
      Map companyDepartments = _result['companyDepartments'];
      Map orgRoles = _result['orgRoles'];
      if (companys.length == 1 &&
          companyDepartments.values.toList().length == 1 &&
          orgRoles.values.toList().length == 1) {
        var _company = companys[0];
        var _department =
            companyDepartments.values.toList()[0].toList().length == 1 ? companyDepartments.values.toList()[0][0] : {};
        var _role = orgRoles.values.toList()[0][0];
        confirm(context, _company, _department, _role);
      } else {
        Application.navigateToPath(context, Routes.selectCompanyRole, params: {'extension': json.encode(_result)})
            .then((value) {
          getBaseInfo();
        });
      }
    } catch (err) {
      Navigator.of(context).pop();
    }
  }

  // 完成
  void confirm(context, _company, _department, _role) {
    if (_company == null || _role == null) {
      FlutterToast.toastCenter('角色异常请联系管理员!');
      return;
    }
    showDialog(
        context: context,
        builder: (ctx) {
          return LoadingDialog(
            barrierDismissible: true,
          );
        });
    // 处理数据
    // 后台解析数据有问题，需前端处理
    _company['children'] = [];
    if (_department != null) {
      _department['children'] = [];
    }
    _role['children'] = [];

    final params = {'companyModel': _company, 'departmentModel': _department, 'roleModel': _role};
    HttpRequest.saveCurCompany(params: params).then((res) async {
      Navigator.of(context).pop();
      if (res['status'] == 200) {
        try {
          final result = res['result'];
          final companyModel = result['companyModel'];
          final departmentModel = result['departmentModel'];
          final roleModel = result['roleModel'];
          SharedPreferences prefer = await SharedPreferences.getInstance();
          if (result['userPower'] != null && result['userPower'] != '') {
            List<String> plist = [];
            print(result['userPower'].toString());
            List userList = result['userPower'];
            if (userList != null) {
              userList.forEach((element) {
                for (final parme in element['children']) {
                  plist.add(parme['path']);
                }
              });
              prefer.setString('permissionList', plist.join(','));
            } else {
              prefer.setString('permissionList', '');
            }
          }
          prefer.setString('real_name', result['realName'] ?? '');
          prefer.setString('user_name', result['userName'] ?? '');
          prefer.setString('email', result['email'] ?? '');
          List<ConfigurationItemModel> data = [];
          for (final json in result['userPower']) {
            data.add(ConfigurationItemModel.fromJson(json));
          }
          prefer.setString('companyList', json.encode(data));
          prefer.setString(SharePrefersKey.companyModelKey, json.encode(companyModel));
          prefer.setString('sel_dept', json.encode(departmentModel));
          prefer.setString('sel_role', json.encode(roleModel));
          // 权限跳转
          final userPower = result['userPower'];
          if (userPower != null) {
            final params = {'params': json.encode(userPower)};
            Application.navigateToPath(context, Routes.main, params: params, clearStack: true);
          } else {
            FlutterToast.toastCenter('服务器未返回权限信息!');
          }
        } catch (e) {
          print(e);
          FlutterToast.toastCenter('数据解析失败!');
        }
      } else {
        shortMessage('接口请求失败!');
      }
    }).catchError((_) {
      Navigator.of(context).pop();
    });
  }
}

// 登录输入框
class LoginInput extends StatefulWidget {
  final TextEditingController controller;
  final String hintText;
  final Image icon;
  final FocusNode focusNode;
  final bool security;
  final String theme;

  const LoginInput({this.controller, this.hintText, this.theme, this.icon, this.focusNode, this.security = false});

  @override
  _LoginInputState createState() => _LoginInputState();
}

class _LoginInputState extends State<LoginInput> {
  bool showSecurity = false;

  @override
  Widget build(BuildContext context) {
    final widget2 = widget;
    return Container(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          SizedBox(
            width: 12.px,
          ),
          widget.icon,
          SizedBox(
            width: 12.px,
          ),
          Expanded(
            child: TextField(
              obscureText: widget2.security ? !showSecurity : false,
              focusNode: widget.focusNode,
              controller: widget.controller,
              decoration:
                  InputDecoration(contentPadding: EdgeInsets.zero, hintText: widget.hintText, border: InputBorder.none),
            ),
          ),
          !widget.security
              ? Container()
              : InkWell(
                  highlightColor: Colors.transparent,
                  splashColor: Colors.transparent,
                  onTap: () {
                    setState(() {
                      showSecurity = !showSecurity;
                    });
                  },
                  child: Container(
                    width: 60,
                    height: 40,
                    padding: EdgeInsets.symmetric(horizontal: 8.px),
                    alignment: Alignment.centerRight,
                    child: showSecurity
                        ? Image.asset('assets/images/icon_security_show.png',
                            width: 10.px, color: GetConfig.getColor(widget.theme))
                        : Image.asset('assets/images/icon_security_hide.png', width: 10.px),
                  ))
        ],
      ),
      decoration: BoxDecoration(
          border: Border.all(color: const Color(0xffdae1e6), width: 1.px), borderRadius: BorderRadius.circular(3.px)),
    );
  }
}
