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/repair/model/repair_list_entity.dart';
import 'package:liftmanager/internal/repair/repair_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 RepairList extends StatefulWidget {
  RepairList({Key key, @required this.index, this.callback}) : super(key: key);

  int index;
  RepairListState mState;
  Function callback;

  @override
  RepairListState createState() {
    mState = RepairListState();
    return mState;
  }
}

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

  @override
  void initState() {
    super.initState();
    //Item数量
//    _maxPage = widget.index == 0 ? 1 : (widget.index == 1 ? 2 : 3);
    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;
    ApiService(context: context).repairList(_page, 10, widget.index,
        onSuccess: (RepairListEntity 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;
    ApiService(context: context).repairList(_page, 10, widget.index,
        onSuccess: (RepairListEntity data) {
      _stateType = StateType.empty;
      if (data.rows.length < 10) {
        _maxPage = _page;
      }
      _list.addAll(data.rows);
      _page++;
      setState(() {});
    }, onError: (code, msg) {
      showToast(msg);
    });
  }

  _repairDetail(int index) {
    RepairItem item = _list[index];
    String jsonString = convert.jsonEncode(item);
    goToPage(
        "${RepairRouter.repairDetailPage}?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, //单行显示
                      ),
                      Offstage(
                          offstage: _list[index].isCritical != 1,
                          child: Container(
                            margin: EdgeInsets.only(left: 12),
                            width: 32,
                            height: 18,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4),
                                color: Color(0xFFFF3B30)),
                            child: Center(
                                child: Text("紧急",
                                    style: TextStyle(
                                        color: Colors.white, fontSize: 11))),
                          )),
                      Expanded(
                          flex: 1,
                          child: Container(
                              padding: EdgeInsets.all(12),
                              child: Row(
                                // crossAxisAlignment: CrossAxisAlignment.end,
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  Text(
                                    '来自：',
                                    style: TextStyle(
                                        fontSize: 13, color: Colours.text_gray),
                                  ),
                                  Text(
                                    _list[index].source == 1
                                        ? "物业端"
                                        : _list[index].source == 2
                                            ? "维保端"
                                            : "物联端",
                                    style: TextStyle(
                                        fontSize: 13,
                                        color: Colours.blue_app_main),
                                    textAlign: TextAlign.right,
                                    overflow: TextOverflow.ellipsis,
                                    softWrap: false, //单行显示
                                  ),
                                ],
                              ))),
                    ],
                  ),
                ),
                lineTxt("发起时间", "${_list[index].createDate}"),
                lineTxt("电梯注册代码", "${_list[index].registrationCode}"),
                lineTxt("电梯类型", "${_list[index].getLiftCategory()}"),
                lineTxt("设备内部编号", "${_list[index].useCompanyCode}"),
                lineTxt("维保负责人", "${_list[index].workerName}"),
                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(
                              "${_list[index].status == -1 ? "暂停中" : _list[index].status == 0 ? "待修理" : _list[index].status == 1 ? "修理中" : _list[index].status == 2 ? _list[index].hasEvaluate == 0 ? '未评价' : "已完成" : "已关闭"}",
                              style: TextStyle(
                                  fontSize: 13, color: Colours.dark_text_gray),
                              overflow: TextOverflow.ellipsis,
                              softWrap: false, //单行显示
                            ),
                          )),
                      Offstage(
                          offstage: noRole && _list[index].status < 2,
                          child: MyButton(
                            onPressed: () {
                              _repairDetail(index);
                            },
                            height: 25,
                            fontSize: 11,
                            colors: [Colours.app_main, Colours.app_main],
                            borderWidth: 0.5,
                            borderColor: Colours.app_main,
                            text:
                                "${_list[index].status == -1 ? "开始修理" : _list[index].status == 0 ? "确认修理" : _list[index].status == 1 ? "继续修理" : _list[index].hasEvaluate == 0 ? "查看" : "查看详情"}",
                          ))
                    ]))
              ],
            ),
          );
        });
  }

  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;
}
