import 'package:flutter/material.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/common/user_db.dart';
import 'package:liftmanager/internal/heavy/heavy_router.dart';
import 'package:liftmanager/internal/heavy/model/heavy_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/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 'package:oktoast/oktoast.dart';

class HeavyList extends StatefulWidget {
  const HeavyList({Key key, @required this.index}) : super(key: key);

  final int index;

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

class _HeavyListState extends State<HeavyList>
    with
        AutomaticKeepAliveClientMixin<HeavyList>,
        SingleTickerProviderStateMixin {
  List<HeavyListItem> _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(() {

      });
    }

  }

  Future _onRefresh() async {
    _stateType = StateType.loading;
    _page = 1;
    _maxPage = 999;
    ApiService(context: context).searchHeavyProject(_page, 10, widget.index,
        onSuccess: (HeavyListEntity 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++;
    ApiService(context: context).searchHeavyProject(_page, 10, widget.index,
        onSuccess: (HeavyListEntity data) {
      _stateType = StateType.empty;
      if (data.rows.length < 10) {
        _maxPage = _page;
      }
      _list.addAll(data.rows);
      _page++;
      setState(() {});
    }, onError: (code, msg) {
      showToast(msg);
    });
  }

    ///电梯列表
  void _liftList(id) {
    NavigatorUtils.push(context, HeavyRouter.heavyLiftListPage + "?id=${id}");
  }

    ///项目详情
  void _projectDetail(id,projectStatus) {
    NavigatorUtils.push(context, "${HeavyRouter.heavyDetailPage}?id=${id}&status=${projectStatus}");
  }

  void _startProject(id) {
    showAlert(context, "提示", "现在开工？", "确定", (){
      NavigatorUtils.goBack(context);
      showLoading(context, "正在加载");
      ApiService(context: context).capitalBegin(id,onSuccess: (res){
        dismissLoading(context);
        _onRefresh();
      },onError: (code,msg){
        dismissLoading(context);
        toasts(msg);
      });
    },txt2: "取消",onPre2: (){
      NavigatorUtils.goBack(context);
    });

  }

  void _endProject(id) {
    showAlert(context, "提示", "现在开工？", "确定", (){
      ApiService(context: context).capitalBegin(id,onSuccess: (res){
        if(res !=null){
          _onRefresh();
        }
      },onError: (code,msg){
        toasts(msg);
      });
    },txt2: "取消",onPre2: (){
      NavigatorUtils.goBack(context);
    });

  }

  @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 InkWell(
              onTap: () {
                _projectDetail(_list[index].projectId,_list[index].projectStatus);
              },
              child: Container(
                margin: EdgeInsets.fromLTRB(15, 5, 15, 5),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(6.0),
                ),
                padding: const EdgeInsets.only(bottom: 10),
                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: TextStyles.text15,
                                overflow: TextOverflow.ellipsis,
                                softWrap: false, //单行显示
                              )),
                          Offstage(
                              offstage: noRole || !(_list[index].projectStatus=="1" && _list[index].isMonitor=="1"),
                              child: MyButton(
                                key: const Key('lift_list'),
                                onPressed: () {
                                  _startProject(_list[index].projectId);
                                },
                                height: 25,
                                fontSize: 11,
                                colors: [Colours.app_main, Colours.app_main],
                                borderWidth: 0.5,
                                borderColor: Colours.app_main,
                                text: "开工",
                              )
                          ),
//                          Offstage(
//                              offstage: !(widget.projectStatus=="2"&&item.isMonitor=="1"),
//                              child: FlatButton(
//                                child: Text("竣工"),
//                                textColor: Colours.dark_text,
//                                highlightColor: Colors.transparent,
//                                onPressed: () {
//                                  NavigatorUtils.push(context, "${HeavyRouter.heavyEndPage}?id="+widget.projectId);
//                                },
//                              )
//                          ),
                          Offstage(
                              offstage:noRole || !(_list[index].projectStatus=="2"&&_list[index].isMonitor=="1"),
                              child: MyButton(
                                key: const Key('lift_list'),
                                onPressed: () {
                                  NavigatorUtils.push(context, "${HeavyRouter.heavyEndPage}?id="+_list[index].projectId);
                                },
                                height: 25,
                                fontSize: 11,
                                colors: [Colours.app_main, Colours.app_main],
                                borderWidth: 0.5,
                                borderColor: Colours.app_main,
                                text: "竣工",
                              )
                          ),
                          MyButton(
                            key: const Key('lift_list'),
                            onPressed: () {
                              _liftList(_list[index].projectId);
                            },
                            height: 25,
                            fontSize: 11,
                            colors: [Colours.app_main, Colours.app_main],
                            borderWidth: 0.5,
                            borderColor: Colours.app_main,
                            text: "查看电梯",
                          )
                        ],
                      ),
                    ),
                    lineTxt("大修单编号", "${_list[index].projectCode}"),
                    lineTxt(
                      "项目用途",
                      "${Constant.projectUsageText[_list[index].projectUsage]}",
                    ),
                    lineTxt("台量", "${_list[index].actualNum}")
                  ],
                ),
              ));
        });
  }

  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;


}
