import 'package:chat/data/UserData.dart';
import 'package:chat/data/WebData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/home/SearchPage.dart';
import 'package:chat/models/ref_name_provider.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/DropDownMemu.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/Toggle.dart';
import 'package:chat/utils/TokenMgr.dart';
import 'package:chat/utils/UserCard.dart';
import 'package:chat/utils/screen.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:location_permissions/location_permissions.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class DisCoverPage extends StatefulWidget {
  DisCoverPage({Key key}) : super(key: key);

  _DisCoverPageState createState() => _DisCoverPageState();
}

class _DisCoverPageState extends State<DisCoverPage>
    with TickerProviderStateMixin {
  TabController sameTabCtrl;
  TabController diffTabCtrl;

  RefreshController _scrollControllerNear =
      RefreshController(initialRefresh: true);

  RefreshController _scrollControllerNew =
      RefreshController(initialRefresh: true);

  RefreshController _scrollControllerApply =
      RefreshController(initialRefresh: true);

  RefreshController _scrollControllerVIP =
      RefreshController(initialRefresh: true);

  bool isPerformingRequest = false;

  Map listMap = {
    1: {'list': [], 'page': 1, 'control': null},
    2: {'list': [], 'page': 1, 'control': null},
    3: {'list': [], 'page': 1, 'control': null},
    4: {'list': [], 'page': 1, 'control': null},
  }; //不同类别的数据

  int type = 1;
  int rows = 20;

  bool isLoading = false; //是否正在加载数据

  static const SEPARATE_SIZE = 20.0;

  bool isOnline = false;

  bool isWomen = UserData().isMan();

  String search = '1';

  String titleStr = '';

  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();

  //获取新的数据
  void getNewData() {
    listMap[type]['page'] = 1;

    getData((data) {
      listMap[type]['list'].clear();
      if (data != null) {
        listMap[type]['list'].addAll(data);
      }
      if (mounted) {
        setState(() {});
      }
    });
  }

  void _onLoading() async {
    listMap[type]['page']++;
    getData((data) {
      if (data == null || data.length == 0) {
        listMap[type]['page']--;
        listMap[type]['control'].loadNoData();
      } else {
        listMap[type]['list'].addAll(data);
        listMap[type]['control'].loadComplete();
      }

      if (mounted) {
        setState(() {});
      }
    });
  }

  void getData(callback) async {
    var data = {
      "userId": UserData().basicInfo.userId,
      "type": type,
      "search": search,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['lng'] = UserData().longitude;
    data['lat'] = UserData().latitude;
    data['page'] = listMap[type]['page'];
    data['rows'] = rows;
    data['sex'] = isWomen ? 2 : 1;
    data['online'] = isOnline ? 1 : 0;
    Response res = await HttpUtil().post('user/main/interface', data: data);
    listMap[type]['control'].refreshCompleted();
    isLoading = false;
    if (res == null) {
      return;
    }
    var resData = res.data;
    print(resData);
    if (resData['code'] == 0) {
      callback(resData['data']);
    }
  }

  @override
  void initState() {
    super.initState();
    diffTabCtrl = TabController(length: 3, vsync: this);
    sameTabCtrl = TabController(length: 2, vsync: this);

    listMap[1]['control'] = _scrollControllerNear;
    listMap[2]['control'] = _scrollControllerNew;
    listMap[3]['control'] = _scrollControllerApply;
    listMap[4]['control'] = _scrollControllerVIP;

    //getNewData();

    sameTabCtrl.addListener(() {
      type = sameTabCtrl.index == 0 ? 1 : 4;
      if (listMap[type]['list'].length == 0) getNewData();
    });

    diffTabCtrl.addListener(() {
      type = diffTabCtrl.index + 1;
      if (listMap[type]['list'].length == 0) getNewData();
    });
    MessageMgr().on('test_Permission', msgTestPermission);
    MessageMgr().on('refresh_love_list', msgRefreshLoveList);
  }

  msgRefreshLoveList(data) {
    print('msgRefreshLoveList ${data['UserId'] is String}');
    for (int i = 0; i < listMap[type]['list'].length; i++) {
      var item = listMap[type]['list'][i];
      print(item['UserId'] == data['UserId']);
      if (item['UserId'] == data['UserId']) {
        item['Follow'] = data['flag'];
        print(listMap[type]['list'][i]);
        break;
      }
    }
    setState(() {});
  }

  msgTestPermission(data) async {
    PermissionStatus status =
        await LocationPermissions().checkPermissionStatus();
    if (status == PermissionStatus.granted) {
      UserData().hasLocationPermission = true;
      _onRefresh();
    }
  }

  @override
  void dispose() {
    _scrollControllerNear.dispose();
    _scrollControllerNew.dispose();
    _scrollControllerApply.dispose();
    _scrollControllerVIP.dispose();
    sameTabCtrl.dispose();
    diffTabCtrl.dispose();
    MessageMgr().off('test_Permission', msgTestPermission);
    MessageMgr().off('refresh_love_list', msgRefreshLoveList);
    super.dispose();
  }

  var _selectTempFirstLevelIndex = '1';
  var _selectFirstLevelIndex = '1';

  var _selectSecondLevelIndex = '-1';
  _buildAddressWidget(void itemOnTap(String key, String value)) {
    List firstLevels = [
      {'key': '1', 'value': I18n.of(context).nearby},
    ];

    if (WebData().provinces.length > 0) {
      if (UserData().isInChina) {
        firstLevels
            .add({'key': 'China', 'value': WebData().provinces['China']});
      } else {
        firstLevels
            .add({'key': 'VietNam', 'value': WebData().provinces['VietNam']});
      }
    }

    List secondLevels = [];
    if (WebData().cities.length > 0) {
      if (UserData().isInChina) {
        WebData()
            .cities['China']
            .forEach((k, v) => secondLevels.add({'key': k, 'value': v}));
      } else {
        WebData()
            .cities['VietNam']
            .forEach((k, v) => secondLevels.add({'key': k, 'value': v}));
      }
    }

    Widget _buildRow(item) {
      var index = item['key'];
      return GestureDetector(
        onTap: () {
          _selectSecondLevelIndex = index;
          _selectFirstLevelIndex = _selectTempFirstLevelIndex;
          itemOnTap(index, item['value']);
        },
        child: Container(
            height: 50,
            decoration: BoxDecoration(
              border: Border(top: Constants.GreyBorderSide),
            ),
            alignment: Alignment.center,
            child: Text(
              item['value'],
              textScaleFactor: 1.0,
              style: TextStyle(
                  decoration: TextDecoration.none,
                  color: _selectFirstLevelIndex == _selectTempFirstLevelIndex &&
                          _selectSecondLevelIndex == index
                      ? const Color(0xFF0368FF)
                      : Constants.BlackTextColor,
                  fontWeight: FontWeight.normal,
                  fontSize: 14),
            )),
      );
    }

    return Container(
        child: Row(
      children: <Widget>[
        Container(
            width: MediaQuery.of(context).size.width * 0.4,
            child: ListView(
              padding: EdgeInsets.zero,
              children: firstLevels.map((item) {
                var index = item['key'];
                return GestureDetector(
                    onTap: () {
                      _selectTempFirstLevelIndex = index;

                      if (index == '1' || index == '2') {
                        itemOnTap(index, item['value']);
                        return;
                      }
                      setState(() {});
                    },
                    child: Container(
                        height: 50,
                        decoration: BoxDecoration(
                          color: _selectTempFirstLevelIndex == index
                              ? const Color(0xFF0368FF)
                              : Colors.white,
                          border: Border(top: Constants.GreyBorderSide),
                        ),
                        alignment: Alignment.center,
                        child: Text(
                          item['value'],
                          textScaleFactor: 1.0,
                          style: TextStyle(
                              color: _selectTempFirstLevelIndex == index
                                  ? Colors.white
                                  : Constants.BlackTextColor,
                              fontWeight: FontWeight.normal,
                              decoration: TextDecoration.none,
                              fontSize: 14),
                        )));
              }).toList(),
            )),
        Expanded(
          child: Container(
            width: double.infinity,
            decoration:
                BoxDecoration(border: Border(left: Constants.GreyBorderSide)),
            child: ListView(
              padding: EdgeInsets.zero,
              children: _selectTempFirstLevelIndex == '1'
                  ? [
                      _buildRow({'key': '1', 'value': I18n.of(context).nearby})
                    ]
                  : (_selectTempFirstLevelIndex == '2'
                      ? [
                          _buildRow({
                            'key': '2',
                            'value': I18n.of(context).Resident_city
                          })
                        ]
                      : secondLevels.map((item) {
                          return _buildRow(item);
                        }).toList()),
            ),
          ),
        )
      ],
    ));
  }

  Widget _buildAppBar() {
    Widget title = InkWell(
        highlightColor: Colors.transparent,
        radius: 0,
        onTap: UserData().isInChina
            ? null
            : () {
                _dropdownMenuController.dropDownHearderHeight = 70;
                _dropdownMenuController.show(0);
              },
        child: Container(
            child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              titleStr == '' ? I18n.of(context).nearby : titleStr,
              textScaleFactor: 1.0,
              //style: Constants.MainTitleStyle,
            ),
            UserData().isInChina
                ? Container()
                : Icon(
                    Icons.arrow_drop_down,
                    color: Constants.BlackTextColor,
                  )
          ],
        )));
    Widget leading = Container(
      child: Row(
        children: <Widget>[
          CircleAvatar(
              backgroundColor: Constants.GreyBackgroundColor,
              radius: 13.75,
              child: Padding(
                  padding: EdgeInsets.only(bottom: 1.5),
                  child: ToggleButton(
                    activeIcon: IconData(
                      0xe61e,
                      fontFamily: 'iconfont',
                    ),
                    unActiveIcon: IconData(
                      0xe61f,
                      fontFamily: 'iconfont',
                    ),
                    active: isWomen,
                    activeColor: Constants.BlackTextColor,
                    unActiveColor: Colors.transparent,
                    onChange: (state) {
                      setState(() {
                        isWomen = !isWomen;
                        sameTabCtrl.index = 0;
                        diffTabCtrl.index = 0;
                        getNewData();
                      });
                    },
                  ))),
          Container(
            padding: EdgeInsets.only(left: 10),
            child: IconButton(
              icon: CircleAvatar(
                  backgroundColor: Constants.GreyBackgroundColor,
                  radius: 13.75,
                  child: Padding(
                      padding: EdgeInsets.only(bottom: 1),
                      child: Icon(
                        IconData(0xe619, fontFamily: Constants.IconFontFamily),
                        color: Constants.BlackTextColor,
                        size: 22,
                      ))),
              onPressed: () {
                Navigator.of(context).push(
                  new MaterialPageRoute(
                    builder: (context) {
                      return SearchPage();
                    },
                  ),
                );
              },
            ),
          ),
          // Container(
          //   child: IconButton(
          //     icon: CircleAvatar(
          //         backgroundColor: Constants.GreyBackgroundColor,
          //         radius: 13.75,
          //         child: Padding(
          //             padding: EdgeInsets.only(bottom: 1.5),
          //             child: Icon(
          //               IconData(0xe659, fontFamily: Constants.IconFontFamily),
          //               color: Constants.BlackTextColor,
          //               size: 21,
          //             ))),
          //     onPressed: () {
          //       goScanPage();
          //     },
          //   ),
          // )
        ],
      ),
    );

    Color borderColor =
        isOnline ? Constants.LightBlueButtonColor : Constants.GreyTextColor;
    Color textColor = isOnline ? Colors.white : Constants.GreyTextColor;
    Color bgColor = isOnline
        ? Constants.LightBlueButtonColor
        : Constants.LightGreyBackgroundColor;
    Widget actions = GestureDetector(
      child: Container(
        margin: EdgeInsets.only(right: 16, bottom: 0),
        alignment: Alignment.center,
        child: Text(
          I18n.of(context).first_online,
          textScaleFactor: 1.0,
          style: TextStyle(color: textColor, fontSize: 11.5),
        ),
        padding: EdgeInsets.only(left: 11, right: 11, bottom: 3, top: 2),
        decoration: BoxDecoration(
            color: bgColor,
            border: Border.all(color: borderColor, width: 1),
            borderRadius: BorderRadius.all(Radius.circular(5.0))),
      ),
      onTap: () {
        setState(() {
          isOnline = !isOnline;
          getNewData();
        });
      },
    );
    return AppBar(
      backgroundColor: Constants.LightGreyBackgroundColor,
      title: title,
      centerTitle: true,
      actions: <Widget>[leading],
      leading: CustomUI.buildCustomLeading(context),
      elevation: 0,
      bottom: PreferredSize(
          preferredSize:
              Size.fromHeight(UserData().hasLocationPermission ? 28 : 52),
          child: Column(
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(left: 2),
                width: Screen.width,
                decoration: BoxDecoration(
                    color: Constants.LightGreyBackgroundColor,
                    border: Border(
                        bottom: UserData().hasLocationPermission
                            ? BorderSide(color: Color(0xffeaeaea))
                            : BorderSide.none)),
                alignment: Alignment.centerLeft,
                child: Stack(
                  alignment: Alignment.centerLeft,
                  children: <Widget>[
                    tabBar(),
                    Positioned(right: 0, bottom: 4, child: actions)
                  ],
                ),
              ),
              // !UserData().hasLocationPermission
              //     ? InkWell(
              //         onTap: () {
              //           CustomUI.buildOneConfirm(
              //               context,
              //               I18n.of(context).get_location,
              //               I18n.of(context).determine, () async {
              //             Navigator.of(context).pop();
              //             LocationPermissions().openAppSettings();
              //           }, title: I18n.of(context).open_location);
              //         },
              //         child: Container(
              //           height: 25,
              //           alignment: Alignment.center,
              //           width: double.infinity,
              //           child: Row(
              //             crossAxisAlignment: CrossAxisAlignment.center,
              //             mainAxisAlignment: MainAxisAlignment.center,
              //             children: <Widget>[
              //               Text(
              //                 I18n.of(context).not_positioned,
              //                 textScaleFactor: 1,
              //                 style: TextStyle(
              //                     fontSize: 12.5,
              //                     color: const Color(0xffab8f60)),
              //               ),
              //               Icon(
              //                 Icons.chevron_right,
              //                 size: 18,
              //                 color: const Color(0xffab8f60),
              //               )
              //             ],
              //           ),
              //           color: const Color(0xfffaefcf),
              //         ))
              //     : Container()
            ],
          )),
    );
  }

  buildSexBar(bool isWomen) {
    List<Widget> feMaleTabs = [
      Text(I18n.of(context).nearby, textScaleFactor: 1.0),
      Text(I18n.of(context).new_registration, textScaleFactor: 1.0),
      Text(I18n.of(context).authenticate, textScaleFactor: 1.0),
    ];

    List<Widget> maleTabs = [
      Text(I18n.of(context).nearby, textScaleFactor: 1.0),
      Text(I18n.of(context).member, textScaleFactor: 1.0),
    ];

    return TabBar(
      isScrollable: true,
      indicatorPadding: EdgeInsets.only(left: 9, right: 9),
      tabs: isWomen ? feMaleTabs : maleTabs,
      controller: isWomen ? diffTabCtrl : sameTabCtrl,
    );
  }

  Widget tabBar() {
    return Container(
        alignment: Alignment.centerLeft,
        width: Screen.width,
        child: buildSexBar(isWomen));
  }

  @override
  Widget build(BuildContext context) {
    GZXDropDownMenu menu = GZXDropDownMenu(
      // controller用于控制menu的显示或隐藏
      controller: _dropdownMenuController,
      // 下拉菜单显示或隐藏动画时长
      animationMilliseconds: 150,
      // 下拉菜单，高度自定义，你想显示什么就显示什么，完全由你决定，你只需要在选择后调用_dropdownMenuController.hide();即可
      menus: [
        GZXDropdownMenuBuilder(
            dropDownHeight: 50 * 8.0,
            callback: () {
              setState(() {});
            },
            dropDownWidget: _buildAddressWidget((key, value) {
              setState(() {});
              isLoading = true;
              titleStr = value;
              _dropdownMenuController.hide();

              search = key;
              getNewData();
            })),
      ],
    );

    var footer = CustomUI.buildLoadingFooter();

    Widget diffView = TabBarView(
      children: <Widget>[
        SmartRefresher(
          enablePullDown: true,
          enablePullUp: true,
          header: MaterialClassicHeader(),
          footer: footer,
          controller: _scrollControllerNear,
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          child:
              (_scrollControllerNear.headerStatus == RefreshStatus.completed &&
                      listMap[1]['list'].length == 0)
                  ? CustomUI.buildNoData(context)
                  : ListView.builder(
                      itemBuilder: _renderRowNear,
                      itemCount: listMap[1]['list'].length,
                    ),
        ),
        SmartRefresher(
          enablePullDown: true,
          enablePullUp: true,
          header: MaterialClassicHeader(),
          footer: footer,
          controller: _scrollControllerNew,
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          child:
              (_scrollControllerNew.headerStatus == RefreshStatus.completed &&
                      listMap[2]['list'].length == 0)
                  ? CustomUI.buildNoData(context)
                  : ListView.builder(
                      itemBuilder: _renderRowNew,
                      itemCount: listMap[2]['list'].length,
                    ),
        ),
        SmartRefresher(
          enablePullDown: true,
          enablePullUp: true,
          header: MaterialClassicHeader(),
          footer: footer,
          controller: _scrollControllerApply,
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          child:
              (_scrollControllerApply.headerStatus == RefreshStatus.completed &&
                      listMap[3]['list'].length == 0)
                  ? CustomUI.buildNoData(context)
                  : ListView.builder(
                      itemBuilder: _renderRowApply,
                      itemCount: listMap[3]['list'].length,
                    ),
        ),
      ],
      controller: diffTabCtrl,
    );

    Widget sampView = TabBarView(
      children: <Widget>[
        SmartRefresher(
          enablePullDown: true,
          enablePullUp: true,
          header: MaterialClassicHeader(),
          footer: footer,
          controller: _scrollControllerNear,
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          child:
              (_scrollControllerNear.headerStatus == RefreshStatus.completed &&
                      listMap[1]['list'].length == 0)
                  ? CustomUI.buildNoData(context)
                  : ListView.builder(
                      itemBuilder: _renderRowNear,
                      itemCount: listMap[1]['list'].length,
                    ),
        ),
        SmartRefresher(
          enablePullDown: true,
          enablePullUp: true,
          header: MaterialClassicHeader(),
          footer: footer,
          controller: _scrollControllerVIP,
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          child:
              (_scrollControllerVIP.headerStatus == RefreshStatus.completed &&
                      listMap[4]['list'].length == 0)
                  ? CustomUI.buildNoData(context)
                  : ListView.builder(
                      itemBuilder: _renderRowVIP,
                      itemCount: listMap[4]['list'].length,
                    ),
        ),
      ],
      controller: sameTabCtrl,
    );
    return Stack(
      children: <Widget>[
        Scaffold(
            appBar: _buildAppBar(),
            body: SafeArea(
              child: Stack(
                children: <Widget>[
                  !isWomen ? sampView : diffView,
                  isLoading ? CustomUI.buildLoaingAnim(context) : Container(),
                ],
              ),
            )),
        menu
      ],
    );
  }

  Widget _renderRow(int index, list, page) {
    if (index < list.length) {
      var userInfo = list[index];
      print('----------------------------------------------------');
      print(userInfo);
      return UserCard(
        key: UniqueKey(),
        userName: Provider.of<RefNameProvider>(context)
            .getRefName(userInfo['UserId'], userInfo['NickName']),
        city: WebData().getCountry(
            userInfo['Country']), //WebData().getCity(userInfo['City']),
        headUrl: userInfo['Headimgurl'],
        isReal: userInfo['IsAttestation'] == 1,
        constellation:
            WebData().getConstellation(context, userInfo['Constellation']),
        distance: userInfo['Distance'].toDouble(),
        age: userInfo['Age'],
        professional: WebData().getProffesionName(userInfo['Occupation']),
        isOnline: userInfo['OnlineStatus'] == 1
            ? I18n.of(context).online
            : WebData().getLoginTime(context, userInfo['LoginDate']),
        hiddenDistince: userInfo['DistanceStatus'] == 1,
        sex: userInfo['Sex'],
        isLove: userInfo['Follow'] == 0,
        isBalck: userInfo['Follow'] == 1,
        userId: userInfo['UserId'],
        payImg: userInfo['PhotoAut'] == 1,
        isHidden: userInfo['InfoAut'] == 1,
        member: userInfo['IsMember'],
        imgNum: userInfo['PhotoNum'],
      );
    }
    return Container();
  }

  Widget _renderRowNear(BuildContext context, int index) {
    return _renderRow(index, listMap[1]['list'], listMap[1]['page']);
  }

  Widget _renderRowNew(BuildContext context, int index) {
    return _renderRow(index, listMap[2]['list'], listMap[2]['page']);
  }

  Widget _renderRowApply(BuildContext context, int index) {
    return _renderRow(index, listMap[3]['list'], listMap[3]['page']);
  }

  Widget _renderRowVIP(BuildContext context, int index) {
    return _renderRow(index, listMap[4]['list'], listMap[4]['page']);
  }

  Future<Null> _onRefresh() async {
    getNewData();
  }
}
