import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/home/AddProgram.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/MessageBox.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:flutter/material.dart';
import 'package:chat/utils/PopUpMenu.dart' as myPop;

import 'package:oktoast/oktoast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../utils/HttpUtil.dart';
import 'package:dio/dio.dart';
import "../data/UserData.dart";
import '../utils/TokenMgr.dart';

class MyProgramPage extends StatefulWidget {
  @required
  final bool isProgram;
  @required
  final bool isMan;
  final userId;
  MyProgramPage(
      {Key key, this.isProgram = true, this.userId, this.isMan = false})
      : super(key: key);

  @override
  _MyProgramPageState createState() => new _MyProgramPageState();
}

class _MyProgramPageState extends State<MyProgramPage> {
  List list = new List(); //列表要展示的数据
  RefreshController _refreshController =
      RefreshController(initialRefresh: true);
  int _page = 1; //加载的页数
  int rows = 20;

  bool isMyself = false;

  addProgramCallback(data) {
    list.insert(0, data);
  }

  @override
  void initState() {
    isMyself = widget.userId == UserData().basicInfo.userId;
    super.initState();
    MessageMgr().on('delete_program', msgListDelete);
    MessageMgr().on('Add_program', addProgramCallback);
    MessageMgr().on('refresh_list', msgRefreshList);
    MessageMgr().on('join_program', msgJoinList);
  }

  msgJoinList(data) {
    for (int i = 0; i < list.length; i++) {
      if (list[i]['Id'] == data) {
        list[i]['EnrollNum']++;
        list[i]['IsEnroll']++;
        setState(() {});
        break;
      }
    }
  }

  msgRefreshList(data) {
    _onRefresh();
  }

  msgListLove(data) {
    for (int i = 0; i < list.length; i++) {
      if (list[i]['Id'] == data) {
        list[i]['FabulousNum']++;
        list[i]['IsFabulous']++;
        setState(() {});
        break;
      }
    }
  }

  msgListDelete(data) {
    for (int i = 0; i < list.length; i++) {
      if (list[i]['Id'] == data) {
        list.removeAt(i);
        setState(() {});
        break;
      }
    }
  }

  Future getData(callback) async {
    var data = {
      "userId": UserData().basicInfo.userId,
      "visitUserId": widget.userId,
      //"type": widget.isProgram == true ? 1 : 2,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['page'] = _page;
    data['rows'] = rows;
    Response res = await HttpUtil().post('station/gain/program',
        data: data, failback: () => Navigator.of(context).pop());
    _refreshController.refreshCompleted();
    var resData = res.data;
    if (resData['code'] == 0) {
      callback(resData['data']);
    } else {
      showToast(resData['msg']);
    }
  }

  void addProgram(str) async {
    if (str == 'program') {
      //自己是女性，且未认证,提示去认证
      if (!UserData().isMan() && !UserData().basicInfo.isAttestation) {
        CustomUI.buildNotTrue(context);
        return;
      }
      if (!UserData().isCanProgram) {
        showToast(I18n.of(context).stop_program);
      } else {
        Navigator.of(context).push(
          new MaterialPageRoute(
            builder: (context) {
              return AddProgram(
                isProgram: true,
              );
            },
          ),
        );
      }
    } else if (str == 'dynamic') {
      //自己是女性，且未认证,提示去认证
      if (!UserData().isMan() && !UserData().basicInfo.isAttestation) {
        CustomUI.buildNotTrue(context);
        return;
      }
      Navigator.of(context).push(
        new MaterialPageRoute(
          builder: (context) {
            return AddProgram(
              isProgram: false,
            );
          },
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget appBar = new AppBar(
      backgroundColor: AppColors.NewAppbarBgColor,
      title: new Text(
        // widget.isProgram
        //     ? (isMyself
        //         ? I18n.of(context).my_show
        //         : (widget.isMan
        //             ? I18n.of(context).his_dynamics
        //             : I18n.of(context).her_dynamics))
        //     : (isMyself
        //         ? I18n.of(context).my_dynamic
        //         : (widget.isMan
        //             ? I18n.of(context).his_dynamics
        //             : I18n.of(context).her_dynamics)),
        isMyself
            ? I18n.of(context).my_dynamic
            : (widget.isMan
                ? I18n.of(context).his_dynamics
                : I18n.of(context).her_dynamics),
        textScaleFactor: 1.0,
        style: TextStyle(color: AppColors.NewAppbarTextColor),
      ),
      centerTitle: true,
      leading: CustomUI.buildCustomLeading(context),

          elevation: 1,
      actions: <Widget>[
        isMyself
            ? myPop.PopupMenuButton<String>(
                padding: EdgeInsets.zero,
                offset: Offset(0, 45),
                child: Container(
                  alignment: Alignment.center,
                  child: new Padding(
                    padding: EdgeInsets.only(
                        right: 15, left: 15, top: 10, bottom: 10),
                    child: new Text(
                      I18n.of(context).release,
                      textScaleFactor: 1.0,
                      style: Constants.AppBarActionTextStyle,
                    ),
                  ),
                ),
                onSelected: (str) {
                  addProgram(str);
                },
                itemBuilder: (BuildContext context) =>
                    <myPop.PopupMenuEntry<String>>[
                  myPop.PopupMenuItem<String>(
                      value: 'program',
                      child: Container(
                        margin: EdgeInsets.only(top: 15, bottom: 15),
                        child: Text(
                          I18n.of(context).release_program,
                          textScaleFactor: 1.0,
                          textAlign: TextAlign.center,
                        ),
                      )),
                  myPop.PopupMenuDivider(
                    height: 1,
                  ),
                  myPop.PopupMenuItem<String>(
                    value: 'dynamic',
                    child: Container(
                        margin: EdgeInsets.only(top: 15, bottom: 15),
                        child: Text(
                          I18n.of(context).release_dynamics,
                          textScaleFactor: 1.0,
                          textAlign: TextAlign.center,
                        )),
                  ),
                ],
              )
            : Container()
      ],
    );
    Widget content = Scaffold(
      appBar: appBar,
      body: SafeArea(
          child: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: MaterialClassicHeader(),
        footer: CustomUI.buildLoadingFooter(),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: (_refreshController.headerStatus == RefreshStatus.completed &&
                list.length == 0)
            ? CustomUI.buildNoData(context)
            : ListView.builder(
                itemBuilder: _renderRow,
                itemCount: list.length,
              ),
      )),
    );
    return content;
  }

  Widget _renderRow(BuildContext context, int index) {
    // if (list.length == 0) {
    //   return CustomUI.buildNoData(
    //     context,
    //     str: isMyself
    //         ? (widget.isProgram
    //             ? I18n.of(context).no_program
    //             : I18n.of(context).on_dynamic)
    //         : (widget.isMan
    //             ? I18n.of(context).low_key2
    //             : I18n.of(context).low_key),
    //   );
    // }
    if (index < list.length) {
      var userInfo = list[index];
      print('--------------------------------------------');
      print(userInfo);
      return MessageBox(
        programInfo: userInfo,
      );
    }
    return Container();
  }

  Future<Null> _onRefresh() async {
    _page = 1;
    getData((data) {
      list.clear();
      if (data != null) {
        list.addAll(data);
      }
      setState(() {});
    });
  }

  Future _onLoading() async {
    _page++;
    getData((data) {
      if (data == null || data.length == 0) {
        _page--;
        _refreshController.loadNoData();
      } else {
        list.addAll(data);
        _refreshController.loadComplete();
      }
      setState(() {});
    });
  }

  @override
  void dispose() {
    _refreshController.dispose();
    MessageMgr().off('delete_program', msgListDelete);
    MessageMgr().off('Add_program', addProgramCallback);
    MessageMgr().off('refresh_list', msgRefreshList);
    MessageMgr().off('join_program', msgJoinList);
    super.dispose();
  }
}
