import 'package:flutter/material.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/common/user_db.dart';
import 'package:liftmanager/internal/lift/lift_router.dart';
import 'package:liftmanager/internal/maintenance/maintenance_router.dart';
import 'package:liftmanager/internal/maintenance/model/maintenance_list_entity.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/utils/toast.dart';
import 'package:liftmanager/widgets/my_button.dart';
import 'package:liftmanager/widgets/my_refresh_list.dart';
import 'package:liftmanager/widgets/state_layout.dart';
import 'dart:convert' as convert;

import 'package:oktoast/oktoast.dart';

class MaintenanceList extends StatefulWidget {

  MaintenanceList({Key key, @required this.index, this.date,this.callback})
      : super(key: key);

  final int index;
  DateTime date;
  Function callback;

  MaintenanceListState mState;

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

class MaintenanceListState extends State<MaintenanceList>
    with
        AutomaticKeepAliveClientMixin<MaintenanceList>,
        SingleTickerProviderStateMixin {
  List<MaintenanceListItem> _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(() {

      });
    }
  }

  static String _twoDigits(int n) {
    if (n >= 10) return "${n}";
    return "0${n}";
  }

  Future onRefresh() async {
    _stateType = StateType.loading;
    _page = 1;
    _maxPage = 999;
    ApiService(context: context).maintenanceList(_page, 10, widget.index,
        "${widget.date.year}-${_twoDigits(widget.date.month)}-${_twoDigits(
            widget.date.day)}",
        onSuccess: (MaintenanceListEntity data) {
          _stateType = StateType.empty;
          if (data != null) {
            if (_page == 1) {
              _list.clear();
            }
            if (data.rows.length < 10) {
              _maxPage = _page;
            }
            if (data != null) {
              _list.addAll(data.rows);
            }
          }
          setState(() {});
        }, onError: (code, msg) {
          showToast(msg);
        });
  }

  Future _loadMore() async {
    _stateType = StateType.loading;
    _page += 1;
    ApiService(context: context).maintenanceList(_page, 10, widget.index,
        "${widget.date.year}-${_twoDigits(widget.date.month)}-${_twoDigits(
            widget.date.day)}",
        onSuccess: (MaintenanceListEntity data) {
          _stateType = StateType.empty;
          if (data.rows.length < 10) {
            _maxPage = _page;
          }
          _list.addAll(data.rows);
          _page++;
          setState(() {});
        }, onError: (code, msg) {
          showToast(msg);
        });
  }

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

  ///保养详情
  startMaintenance(int index) {
    String jsonString = convert.jsonEncode(_list[index]);
    if (_list[index].recordId.length > 0) {
      if (_list[index].status == "2") {
        if (_list[index].hasEvaluate == "0") {
          goToPage("${MaintenanceRouter.maintenanceEvaluate}?id=${_list[index]
                  .recordId}&category=${_list[index]
                  .category}&type=${_list[index].maintenanceType}");
        } else {
          goToPage("${MaintenanceRouter.maintenanceDetail}?item=${Uri
                  .encodeComponent(jsonString)}");
        }
      } else {
          goToPage(
            "${MaintenanceRouter.maintenanceSubmit}?item=${Uri.encodeComponent(
                jsonString)}");
      }
    } else {
      if (_list[index].coordinate.length == 0) {
        showAlert(context, "提示", "电梯未定位,是否立即定位", "去定位", () {
          goToPage(
              "${LiftRouter.liftDetailPage}?project_id=" +
                  _list[index].projectId + "&id=" + _list[index].liftId);
        }, txt2: "取消", onPre2: () {
          NavigatorUtils.goBack(context);
        });
      } else {
        goToPage(
            "${MaintenanceRouter.maintenanceRecordInfo}?item=${Uri
                .encodeComponent(jsonString)}");
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    bool isDark = ThemeUtils.isDark(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, 5, 5),
            padding: EdgeInsets.only(bottom: 10),
            decoration: BoxDecoration(
              color: isDark ? Colors.black : Colors.white,
              borderRadius: BorderRadius.circular(6.0),
            ),
            child: Column(
              children: <Widget>[
                Container(
                  decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                            width: 0.5, color: Colours.text_gray_c),
                      )),
                  padding: EdgeInsets.only(left: 12),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                          flex: 1,
                          child: Text(
                            _list[index].projectName,
                            style: TextStyle(fontSize: 15, color: isDark
                                ? Colours.dark_text
                                : Colours.text,),
                            overflow: TextOverflow.ellipsis,
                            softWrap: false, //单行显示
                          )),
                      MyButton(
                        key: const Key('lift_list'),
                        onPressed: () {
                          if (noRole && _list[index].status != "2") {
                            toasts("保养未开始或未完成，暂不可查看");
                            return;
                          }else if(noRole && _list[index].status == "2"){
                            String jsonString = convert.jsonEncode(_list[index]);
                            goToPage(
                                "${MaintenanceRouter.maintenanceDetail}?item=${Uri
                                    .encodeComponent(jsonString)}");
                          }else{
                            startMaintenance(index);
                          }

                        },
                        height: 25,
                        fontSize: 11,
                        colors: noRole && _list[index].status != "2"?[
                          Colours.text_gray,
                          Colours.text_gray
                        ]:null,
                        borderWidth: 0.5,
                        text: _list[index].status == "-1" ? "补录" : _list[index]
                            .status == "0" ? (DateTime.parse(_list[index]
                            .planDate).isAfter(DateTime.now())
                            ? '提前保养'
                            : '开始保养') : _list[index].status == "1"
                            ? "继续保养"
                            : _list[index].status == "2" ? _list[index]
                            .hasEvaluate == "0" ? "待评价" : "保养详情" : "保养详情",
                      )

                    ],
                  ),
                ),
                lineTxt("电梯注册代码", "${_list[index].registrationCode}"),
                lineTxt("设备内部编号", "${_list[index].useCompanyCode}"),
                lineTxt("电梯类型", "${_list[index].liftTypeName}"),
                lineTxt("维保负责人", "${_list[index].workerName}"),
                lineTxt("计划日期", "${_list[index].planDate}"),
                lineTxt("保养类型", "${_list[index].maintenanceTypeName}"),
              ],
            ),
          );
        });
  }

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


