import 'dart:convert';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_svg_provider/flutter_svg_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../consts/color.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/app_theme.dart';
import '../../utils/flutter_toast.dart';
import '../../utils/request.dart';
import '../../utils/user_info_manager.dart';
import '../../widgets/back_button.dart';
import '../../widgets/loading_dialog.dart';

class SelectCompanyRole extends StatelessWidget {
  final String type;
  final Map<String, dynamic> result;
  String theme;

  SelectCompanyRole(this.result, {this.type});

  @override
  @override
  Widget build(BuildContext context) {
    return SelectCompanyRoleContent(result, type: type);
  }
}

class SelectCompanyRoleContent extends StatefulWidget {
  final String type;
  final Map<String, dynamic> result;

  const SelectCompanyRoleContent(this.result, {this.type});

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

class _SelectCompanyRoleContentState extends State<SelectCompanyRoleContent> {
  Map<String, dynamic> _company;
  Map<String, dynamic> _department;
  Map<String, dynamic> _role;
  Map<String, dynamic> _result;
  String theme;

  @override
  void initState() {
    super.initState();
    initConfig();
    _result = widget.result;
    if (widget.type == '1') {
      getDatas();
    }
  }

  initConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        theme = preferences.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }

  /// 获取数据
  Future<void> getData(context) async {
    Future.delayed(Duration.zero, () {
      showDialog(
          context: context,
          builder: (ctx) {
            return LoadingDialog(
              barrierDismissible: true,
            );
          });
      HttpRequest.getSelectCompany().then((res) {
        Navigator.of(context).pop();
        if (res['status'] == 200) {
          _result = res['result'];
          handleTurn(context);
        }
      }).catchError((_) {
        Navigator.of(context).pop();
      });
    });
  }

  /// 处理跳转
  void handleTurn(context) {
    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) {
        _company = companys[0];
        _department =
            companyDepartments.values.toList()[0].toList().length == 1 ? companyDepartments.values.toList()[0][0] : {};
        _role = orgRoles.values.toList()[0][0];
        if (widget.type != '1') {
          confirm(context);
        }
      }
    } catch (err) {
      Navigator.of(context).pop();
    }
  }

  void getDatas() {
    SharedPreferences.getInstance().then((sp) {
      setState(() {
        _company = json.decode(sp.get(SharePrefersKey.companyModelKey));
        _department = json.decode(sp.get('sel_dept'));
        _role = json.decode(sp.get('sel_role'));
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: AppTheme.backgroundColor,
        appBar: AppBar(
          title: const Text(
            '公司部门角色选择',
            style: TextStyle(color: Colors.black),
          ),
          centerTitle: true,
          leading: LeadingButton(
            theme: theme,
            onWillScope: true,
            onWillPop: () {
              UserInfoManager.clearBaseInfoMemoryCache();
              Navigator.of(context).pop();
            },
          ),
        ),
        body: Stack(
          children: <Widget>[buildContentList(context), buildBottomBarButton(context)],
        ));
  }

  // 选择选项卡
  Widget buildContentList(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 8.px, vertical: 5.px),
      child: Card(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6.px)),
        shadowColor: AppTheme.shadowColor,
        elevation: 4,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            CellItem(
              title: '公司',
              image: Image.asset(
                'assets/images/icon_company.png',
                width: 25,
                height: 25,
                fit: BoxFit.cover,
              ),
              select: _company == null ? '' : _company['companyName'],
              onTap: companySelect,
            ),
            CellItem(
              title: '部门',
              image: const Image(
                image: Svg('assets/images/icon_department.svg', size: Size(28, 28)),
              ),
              select: _department == null ? '' : _department['departmentName'],
              onTap: departmentSelect,
            ),
            CellItem(
              title: '角色',
              image: const Image(
                image: Svg('assets/images/icon_role.svg', size: Size(28, 28)),
              ),
              select: _role == null ? '' : _role['roleName'],
              onTap: roleSelect,
            )
          ],
        ),
      ),
    );
  }

  Widget buildBottomBarButton(BuildContext context) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Row(
        children: <Widget>[
          Expanded(
            child: Container(
              height: 50.px,
              child: RaisedButton(
                color: Colors.white,
                child: Text(
                  '重置',
                  style: Theme.of(context).textTheme.headline2.copyWith(color: const Color(0xFF333333)),
                ),
                onPressed: reset,
              ),
            ),
          ),
          Expanded(
            child: Container(
              height: 50.px,
              child: RaisedButton(
                color: GetConfig.getColor(theme),
                child: Text(
                  '确定',
                  style: Theme.of(context).textTheme.headline2,
                ),
                onPressed: () => confirm(context),
              ),
            ),
          )
        ],
      ),
    );
  }

  // 公司选择
  void companySelect() {
    if (_result == null) {
      FlutterToast.toastCenter('请求公司信息数据为空!');
      return;
    }
    final params = {'params': json.encode(_result['companys']), 'title': '公司'};
    Application.navigateToPath(context, Routes.selectRoleList, params: params).then((value) {
      if (value != null) {
        setState(() {
          _company = value;
          _department = null;
          _role = null;
        });
      }
    });
  }

  // 部门选择
  void departmentSelect() {
    if (_company == null) {
      FlutterToast.toastCenter('请先选择公司!');
      return;
    }
    List seq = _result['companyDepartments']['${_company['companySeq']}'];
    seq ?? seq.isEmpty;
    if (seq.isEmpty) {
      FlutterToast.toastCenter('请直接选择角色!');
      return;
    }
    try {
      final params = {'params': json.encode(_result['companyDepartments']['${_company['companySeq']}']), 'title': '部门'};

      Application.navigateToPath(context, Routes.selectRoleList, params: params).then((value) {
        if (value != null) {
          setState(() {
            _department = value;
            _role = null;
          });
        }
      });
    } catch (err) {
      FlutterToast.toastCenter('接口请求出错!');
    }
  }

  // 角色选择
  void roleSelect() {
    if (_company == null) {
      FlutterToast.toastCenter('请先选择公司!');
      return;
    }
    List seq = _result['companyDepartments']['${_company['companySeq']}'];
    seq ?? seq.isEmpty;
    try {
      final params = {
        'params': _department == null
            ? json.encode(_result['orgRoles'][_company['sequenceNbr']])
            : json.encode(_result['orgRoles'][_department['sequenceNbr']]),
        'title': '角色'
      };

      Application.navigateToPath(context, Routes.selectRoleList, params: params).then((value) {
        if (value != null) {
          setState(() {
            _role = value;
          });
        }
      });
    } catch (err) {
      FlutterToast.toastCenter('接口请求出错!');
    }
  }

  // 重置
  void reset() {
    setState(() {
      _company = null;
      _department = null;
      _role = null;
    });
  }

  // 完成
  void confirm(context) {
    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));

          ///直接返回，接续执行之前逻辑
          Navigator.of(context).pop(companyModel);
          // 权限跳转
          /* 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 CellItem extends StatelessWidget {
  final String title;
  final Image image;
  final VoidCallback onTap;
  final String select;

  const CellItem({this.title, this.image, this.onTap, this.select});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 15.px, vertical: 14.px),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Row(
              children: <Widget>[
                image,
                SizedBox(
                  width: 10.px,
                ),
                Text(
                  title,
                  style: Theme.of(context).textTheme.headline4,
                )
              ],
            ),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                select.isNotEmpty
                    ? Text(
                        '$select',
                        style: Theme.of(context).textTheme.headline4,
                      )
                    : Text(
                        '请选择',
                        style: Theme.of(context).textTheme.headline3.copyWith(color: const Color(0xFF999999)),
                      ),
                Icon(
                  Icons.keyboard_arrow_right,
                  size: 25.px,
                  color: const Color(0xFF999999),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
