import 'dart:convert' as convert;

import 'package:flutter/material.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/common/user_db.dart';
import 'package:liftmanager/internal/yearly/model/yearly_list_entity.dart';
import 'package:liftmanager/internal/yearly/yearly_router.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/widgets/my_button.dart';
import 'package:liftmanager/widgets/my_refresh_list.dart';
import 'package:liftmanager/widgets/state_layout.dart';
import 'package:oktoast/oktoast.dart';

class YearlyList extends StatefulWidget {
  YearlyList({Key key, @required this.index, this.callback}) : super(key: key);
  Function callback;
  final int index;

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

class _YearlyListState extends State<YearlyList>
    with
        AutomaticKeepAliveClientMixin<YearlyList>,
        SingleTickerProviderStateMixin {
  List<YearlyListItem> _list = [];
  int _page = 1;
  int _maxPage = 999;
  StateType _stateType = StateType.loading;

  @override
  void initState() {
    super.initState();
    //Item数量
    _onRefresh();
    getHasRole();
  }

  bool noRole = true;

  getHasRole() async {
    var role = await User().getCompanyRole();
    if (role == Constant.RoleAdmin ||
        role == Constant.RoleRegion ||
        role == Constant.RoleWork) {
      noRole = false;
      setState(() {});
    }
  }

  goToPage(pagePath) {
    NavigatorUtils.pushResult(context, pagePath, (res) {
      _onRefresh();
      widget.callback();
    });
  }

  Future _onRefresh() async {
    _stateType = StateType.loading;
    _page = 1;
    _maxPage = 999;
    if (widget.index == 0) {
      ApiService(context: context).yearlyNoConfirmList(_page, 10, widget.index,
          onSuccess: (YearlyListEntity data) {
        _stateType = StateType.empty;
        if (_page == 1) {
          _list.clear();
        }
        if (data.rows.length < 10) {
          _maxPage = _page;
        }
        _list.addAll(data.rows);
        setState(() {});
      }, onError: (code, msg) {
        showToast(msg);
      });
    } else {
      ApiService(context: context).yearlyList(_page, 10, widget.index - 1,
          onSuccess: (YearlyListEntity data) {
        _stateType = StateType.empty;
        if (_page == 1) {
          _list.clear();
        }
        if (data.rows.length < 10) {
          _maxPage = _page;
        }
        _list.addAll(data.rows);
        setState(() {});
      }, onError: (code, msg) {
        showToast(msg);
      });
    }
  }

  Future _loadMore() async {
    _stateType = StateType.loading;
    _page += 1;
    if (widget.index == 0) {
      ApiService(context: context).yearlyNoConfirmList(_page, 10, widget.index,
          onSuccess: (YearlyListEntity data) {
        _stateType = StateType.empty;
        if (data.rows.length < 10) {
          _maxPage = _page;
        }
        _list.addAll(data.rows);
        _page++;
        setState(() {});
      }, onError: (code, msg) {
        showToast(msg);
      });
    } else {
      ApiService(context: context).yearlyList(_page, 10, widget.index - 1,
          onSuccess: (YearlyListEntity data) {
        _stateType = StateType.empty;
        if (data.rows.length < 10) {
          _maxPage = _page;
        }
        _list.addAll(data.rows);
        _page++;
        setState(() {});
      }, onError: (code, msg) {
        showToast(msg);
      });
    }
  }

  ///确认年检计划
  _yearlyConfirm(index) {
    String jsonString = convert.jsonEncode(_list[index]);
    print(jsonString);
    goToPage(
        "${YearlyRouter.yearlyDetailPage}?item=${Uri.encodeComponent(jsonString)}");
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return MyListView(
        itemCount: _list.length,
        stateType: _stateType,
        onRefresh: _onRefresh,
        loadMore: _loadMore,
        hasMore: _page < _maxPage,
        itemBuilder: (_, index) {
          return Container(
            margin: EdgeInsets.fromLTRB(15, 5, 15, 5),
            decoration: BoxDecoration(
              color: ThemeUtils.getTabsBg(context),
              borderRadius: BorderRadius.circular(6.0),
            ),
            child: Column(
              children: <Widget>[
                Container(
                  decoration: BoxDecoration(
                      border: Border(
                    bottom: BorderSide(width: 0.5, color: Colours.line),
                  )),
                  padding: EdgeInsets.only(left: 12),
                  child: Row(
                    children: <Widget>[
                      Text(
                        "${_list[index].projectName}",
                        style: TextStyle(
                            fontSize: 15,
                            color: ThemeUtils.isDark(context)
                                ? Colours.dark_text
                                : Colours.text),
                        overflow: TextOverflow.ellipsis,
                        softWrap: false, //单行显示
                      ),
                      Expanded(
                          flex: 1,
                          child: Container(
                            padding: EdgeInsets.all(12),
                            child: Text(
                              getStepName(_list[index].stepName),
                              style: TextStyle(
                                  fontSize: 13, color: Colours.app_main),
                              textAlign: TextAlign.right,
                              overflow: TextOverflow.ellipsis,
                              softWrap: false, //单行显示
                            ),
                          )),
                    ],
                  ),
                ),
                lineTxt("注册代码", "${_list[index].registrationCode}"),
                lineTxt("区域", "${_list[index].areaName}"),
                lineTxt("设备内部编号", "${_list[index].useCompanyCode}"),
                lineTxt("电梯地址", "${_list[index].devicePosition}"),
                lineTxt("区域主管", "${_list[index].directorName}"),
                lineTxt("计划时间", "${_list[index].planDate}"),
                lineTxt("是否检查限速器",
                    "${_list[index].isCheckGoverner == 1 ? "是" : "否"}"),
                lineTxt("荷载年检设置",
                    "${_list[index].loadInspectionSetting == 1 ? "是" : "否"}"),
                SizedBox(
                  height: 10,
                ),
                Container(
                    decoration: BoxDecoration(
                        border: Border(
                      top: BorderSide(width: 0.5, color: Colours.line),
                    )),
                    child: Row(children: <Widget>[
                      Expanded(
                          flex: 1,
                          child: Container(
                            padding: EdgeInsets.all(12),
                            child: Text(
                              getStepTitle(_list[index].stepStatus),
//                              "${_list[index].status == 0 ? "待完成" : _list[index].status == 1 ? "已完成" : "超期"}",
                              style: TextStyle(
                                  fontSize: 13,
                                  color: _list[index].status == 0
                                      ? Colors.amber
                                      : _list[index].status == 1
                                          ? Colours.app_main
                                          : Colours.red),
                              overflow: TextOverflow.ellipsis,
                              softWrap: false, //单行显示
                            ),
                          )),
                      Offstage(
                          offstage: noRole && _list[index].status != 1,
                          child: MyButton(
                            onPressed: () {
                              _yearlyConfirm(index);
                            },
                            height: 25,
                            fontSize: 11,
                            colors: [Colours.app_main, Colours.app_main],
                            borderWidth: 0.5,
                            borderColor: Colours.app_main,
                            text: _list[index].status == 1 ? "年检详情" : "提交年检进度",
                          ))
                    ]))
              ],
            ),
          );
        });
  }

  String getStepName(int i) {
    String str = "";
    switch (i) {
      case 0:
        str = "未开始";
        break;
      case 1:
        str = "自检";
        break;
      case 2:
        str = "报检";
        break;
      case 3:
        str = "场检";
        break;
      case 4:
        str = "确认";
        break;
    }
    return str;
  }

  String getStepTitle(int i) {
    String str = "";
    switch (i) {
      case 0:
        str = "开启年检";
        break;
      case 1:
        str = "请上传自检报告";
        break;
      case 2:
        str = "请等待自检审核";
        break;
      case 3:
        str = "请等待报检结果";
        break;
      case 4:
        str = "请上传检验结果";
        break;
      case 5:
        str = "请等待场检审核";
        break;
      case 6:
      case 7:
        str = "请上传年检报告和合格证";
        break;
      case 8:
      case 9:
      case 10:
        str = "请等待确认审核";
        break;
    }
//    switch(i){
//      case 0:
//        str = "请开启年检";
//        break;
//      case 1:
//        str = "请上传自检报告";
//        break;
//      case 2:
//        str = "请等待自检审核";
//        break;
//      case 3:
//        str = "请等待报检结果";
//        break;
//      case 4:
//        str = "请等待";
//        break;
//    }
    return str;
  }

  Widget lineTxt(title, value) {
    return Container(
      padding: EdgeInsets.only(left: 12, top: 5, right: 12),
      child: Row(
        children: <Widget>[
          Text("${title}",
              style: TextStyle(fontSize: 13, color: Colours.dark_text_gray)),
          Expanded(
            flex: 1,
            child: Text(
              "${value}",
              textAlign: TextAlign.right,
              style: TextStyle(fontSize: 13, color: Colours.dark_text_gray),
            ),
          )
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
