import 'dart:convert';
import 'dart:io';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';
import 'package:path/path.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';

import '../../consts/color.dart';
import '../../consts/share_prefers_key_const.dart';
import '../../model/CompanyInfo.dart';
import '../../model/configuration_item_model.dart';
import '../../services/myinfo_services.dart';
import '../../utils/GetConfig.dart';
import '../../utils/user_info_manager.dart';
import '../../view/login/login.dart';
import '../../widgets/My_scteen_item.dart';
import 'myinfo_page.dart';

///我的页面
///qi 2019.03.03

class MyScreen extends StatefulWidget {
  final List userPowers;

  const MyScreen(this.userPowers);

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

class _MyScreenState extends State<MyScreen> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  String version;
  bool isOffline = false;
  String theme = '';
  num catchSize = 0.0;
  String userId;
  String userName;
  CompanyInfos company;
  String permissionList;
  List<ConfigurationItemModel> data = [];

  @override
  void didUpdateWidget(MyScreen oldWidget) {
    super.didUpdateWidget(oldWidget);
    getData();
  }

  @override
  void initState() {
    super.initState();
    final usePowers = widget.userPowers;
    for (var json in usePowers) {
      data.add(ConfigurationItemModel.fromJson(json));
    }
    getData();

    getPermissionData();
  }

  getData() {
    SharedPreferences.getInstance().then((sp) {
      setState(() {
        userId = sp.getString('user_id');
        userName = sp.getString('real_name');
        theme = sp.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
        company = CompanyInfos.fromJson(json.decode(sp.get(SharePrefersKey.companyModelKey)));
      });

      if (sp.getBool('offline') != null) {
        setState(() {
          isOffline = sp.getBool('offline');
        });
      }
    });

    PackageInfo.fromPlatform().then((packageInfo) {
      setState(() {
        version = packageInfo.version;
      });
    });

    getDatabasesPath().then((dbPath) {
      SharedPreferences.getInstance().then((sp) {
        String str = sp.get('LoginResult');
        String myDbPath = join(dbPath, '${sp.getString("user_id")}', 'my.db');
        File(myDbPath).exists().then((exists) {
          if (exists) {
            print("DB Path exists:${myDbPath}");
            File(myDbPath).length().then((size) {
              print("${myDbPath}:${size}");
              setState(() {
                catchSize = size;
              });
            });
          } else {
            print("DB Path not exists:${myDbPath}");
            catchSize = 0;
          }
        });
      });
    });
  }

  clearCatch() {
    setState(() {
      catchSize = 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (theme.isEmpty) {
      return const Scaffold(
        body: Text(""),
      );
    }
    return Scaffold(
        backgroundColor: const Color.fromRGBO(242, 246, 249, 1),
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0.2,
          //backgroundColor: KColorConstant.floorTitleColor,
          title: const Text(
            '我的',
            style: TextStyle(
              color: Colors.black,
              //              fontWeight: FontWeight.bold,
            ),
          ),
          centerTitle: true,
        ),
        body: SingleChildScrollView(
            child: Container(
                child: Column(
          children: <Widget>[
            //头像部分
            Container(
              //margin: const EdgeInsets.only(top: 0.0),
              color: Colors.white,
              height: 80.0,
              child: TouchCallBack(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      padding: const EdgeInsets.only(left: 20, right: 20),
                      child: CircleAvatar(
                        backgroundColor: GetConfig.getColor(theme),
                        child: Text(
                          userName.isEmpty ? '' : userName[0] /*loginResult.user.name[0]*/,
                          style: const TextStyle(color: Colors.white),
                        ),
                      ),
                    ),
                    Expanded(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            //myInfo.username,
                            userName.isEmpty ? "" : userName, //loginResult.user.name,
                            style: const TextStyle(
                              fontSize: 18.0,
                              color: Color(0xff353535),
                            ),
                          ),
                          Text(
                            company == null ? "" : company.companyName, //loginResult.user.company.companyName,
                            style: const TextStyle(
                              fontSize: 14.0,
                              color: Color(0xffa9a9a9),
                            ),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
                onPressed: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => MyInfoPage(),
                      )
                      //点击进入个人信息详细页面
                      );
                },
              ),
            ),
            // 列表项，使用自定义ImItem
            Container(
                margin: const EdgeInsets.only(top: 10.0),
                color: Colors.white,
                height: data.length * 50.5,
                child: ListView.builder(
                    itemCount: data.length,
                    physics: const NeverScrollableScrollPhysics(),
                    itemBuilder: (context, index) {
                      String type = '';
                      String subText = '';
                      String righticonPath = 'assets/images/icons/righticon.png';
                      ConfigurationItemModel element = data[index];
                      if (element.path == 'AppNFC') {
                        return Container(
                          color: const Color.fromRGBO(242, 246, 249, 1),
                          height: 50,
                        );
                      }
                      if (data[index].path == '/ChangPwd') {
                        type = 'assets/images/my/modify_password_blue.png';
                      } else if (data[index].path == '/MailList') {
                        type = 'assets/images/my/contact_blue.png';
                      } else if (data[index].path == '/MessageSubscription') {
                        type = 'assets/images/my/message_blue.png';
                      } else if (data[index].path == '/OfflineMode') {
                        subText = isOffline ? '已开启' : '未开启';
                        type = 'assets/images/my/offline_blue.png';
                      } else if (data[index].path == '/CurrentVersion') {
                        righticonPath = '';
                        subText = version ?? '';
                        type = 'assets/images/my/version_blue.png';
                      } else if (data[index].path == '/ClearCache') {
                        righticonPath = '';
                        subText = (catchSize / 1000000).toStringAsFixed(2) + 'M';
                        type = 'assets/images/my/clean_blue.png';
                      }
                      return Container(
                        child: Column(
                          children: [
                            ImItem(
                              iconPath: type,
                              title: data[index].permissionName,
                              path: data[index].path,
                              righticonPath: righticonPath,
                              subtext: subText,
                              theme: theme,
                              isOffline: isOffline,
                              callback: clearCatch,
                              changed: () {
                                getData();
                              },
                            ),
                            //分割线
                            const Padding(
                              padding: EdgeInsets.only(left: 15.0, right: 15.0),
                              child: Divider(
                                height: 0.5,
                                color: Color(0xffd9d9d9),
                              ),
                            ),
                          ],
                        ),
                      );
                    })),
            Container(
              margin: const EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0),
              color: GetConfig.getColor(theme),
              width: 330,
              child: MaterialButton(
                onPressed: () {
                  Logout();
                  UserInfoManager.logoutClear();
                  Navigator.of(context)
                      .pushAndRemoveUntil(MaterialPageRoute(builder: (context) => Login()), (route) => route == null);
                },
                child: const Text(
                  '退出登录',
                  style: TextStyle(fontSize: 18, color: Colors.white),
                ),
              ),
            ),
          ],
        ))));
  }

  checkPermission(String permission) {
    if (permissionList == null || permissionList.isEmpty) return false;
    bool hasPermission = false;
    List permissions = permissionList.split(',');
    if (permissions.isEmpty) {
      hasPermission = false;
    } else {
      permissions.forEach((f) {
        print(f);
        if (f == permission) {
          hasPermission = true;
        }
      });
    }

    return hasPermission;
  }

  getPermissionData() async {
    await SharedPreferences.getInstance().then((sp) {
      String str = sp.get('permissionList');
      setState(() {
        permissionList = str;
//        this.theme = sp.getString("theme")??KColorConstant.DEFAULT_COLOR;
      });
    });
  }
}
