import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_iot_login_tpl/const/const.dart';
import 'package:amos_iot_ui/listItem/list_view_item.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/consts/colors.dart';
import 'package:jcs_airport/entity/page.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/utils/convert_date.dart';
import 'package:jcs_airport/view/common/no_data.dart';
import 'package:jcs_airport/view/workBench/maintenance/maintenanceTask/task.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'record_detail.dart';

///维保任务
class Record extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('维保记录'),
      ),
      body: RecordContent(),
    );
  }
}

class RecordContent extends StatefulWidget {
  bool showFilter;
  String fireFacilityCode;
  RecordContent({this.showFilter = true,this.fireFacilityCode=''});

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

class _RecordContentState extends State<RecordContent> {
  final scope = [
    {'title': '全部', 'value': ''},
  ];
  final date = [
    {'title': '全部时间'},
    {'title': '今天'},
    {'title': '昨天'},
    {'title': '本周'},
    {'title': '上周'},
    {'title': '本月'},
    {'title': '上月'},
  ];
  final status = [
    {'title': '所有状态', 'value': ''},
  ];
  final orderType = [
    {'title': '默认排序', 'value': ''},
  ];
  int _scopeSelectIndex = 0;
  int _dateSelectIndex = 0;
  int _statusSelectIndex = 0;
  int _orderTypeSelectIndex = 0;
  Map<String, Object> filterData = {};
  final Map chooseDepartment = {};
  final Map choosePerson = {};
  final RefreshController _refreshController = RefreshController(initialRefresh: false);
  final AmosPage _page = AmosPage(current: 0);
  final List<Map<String, Object>> _data = [];

  @override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((value) => scope.add(
          {'title': '我的', 'value': value.getString(GlobalConst.USER_ID)},
        ));
    _getData();
    Future.wait([_getOderBy(), _getStatus()]).whenComplete(() => setState(() {}));
  }

  @override
  Widget build(BuildContext context) {
    return DefaultDropdownMenuController(
      onSelected: ({int menuIndex, int index, int subIndex, dynamic data}) {
        print('menuIndex:$menuIndex index:$index subIndex:$subIndex data:$data');
        switch (menuIndex) {
          case 0:
            if (data['value'] != '') {
              filterData['userId'] = data['value'];
            } else {
              filterData.remove('userId');
              setState(() {
                choosePerson.clear();
              });
            }
            setState(() {
              _scopeSelectIndex = index;
            });
            break;
          case 1:
            if (data['title'] != '全部时间') {
              DateRange dateRange = ConvertDate.convertDateTextToRealValue(data['title']);
              filterData['startDate'] = dateRange.startTime;
              filterData['endDate'] = dateRange.endTime;
            } else {
              filterData.remove('startDate');
              filterData.remove('endDate');
            }
            setState(() {
              _dateSelectIndex = index;
            });
            break;
          case 2:
            if (data['value'] != '') {
              filterData['result'] = data['value'];
            } else {
              filterData.remove('result');
            }
            setState(() {
              _statusSelectIndex = index;
            });
            break;
          case 3:
            if (data['value'] != '') {
              filterData['orderRule'] = data['value'];
            } else {
              filterData.remove('orderRule');
            }
            setState(() {
              _orderTypeSelectIndex = index;
            });
            break;
        }
        _data.clear();
        _page.current = 0;
        _getData();
      },
      child: Stack(
        children: [
          Padding(
            padding: EdgeInsets.only(top: widget.showFilter ? 46 : 0),
            child: Column(
              children: [
                _data.isNotEmpty
                    ? Expanded(
                        child: SmartRefresher(
                          enablePullDown: true,
                          enablePullUp: true,
                          controller: _refreshController,
                          header: const WaterDropMaterialHeader(),
                          footer: const ClassicFooter(),
                          onRefresh: _onRefresh,
                          onLoading: _onLoading,
                          child: ListView.builder(
                            itemCount: _data.length,
                            shrinkWrap: true,
                            itemBuilder: (BuildContext context, int index) {
                              Map<String, Object> item = _data[index];
                              ListViewItemModel listViewItemModel = ListViewItemModel(
                                  hasTitle: false,
                                  hasState: true,
                                  stateColor:
                                      AMOSColors.maintenanceRecordStatusColor(int.parse(_data[index]['isOk']) ?? 0),
                                  hasFooter: true,
                                  footer: '维保时间：' + item['checkDate'],
                                  onclick: () async {
                                    Get.to(
                                        RecordDetail((item['checkId'] ?? '').toString(), item['equipmentName'] ?? ''));
                                  });
                              return ListViewItem(
                                listViewItemModel: listViewItemModel,
                                contentWidget: Padding(
                                  padding: const EdgeInsets.all(5.0),
                                  child: Column(
                                    children: [
                                      Row(
                                        children: [
                                          Expanded(
                                              child: Text(
                                            _data[index]['equipmentDetailName'] ?? '',
                                            style: const TextStyle(fontSize: 15),
                                          )),
                                          Text(
                                            _data[index]['status'] ?? '',
                                            style: TextStyle(
                                                color: AMOSColors.maintenanceRecordStatusColor(
                                                    int.parse(_data[index]['isOk']) ?? 0)),
                                          )
                                        ],
                                      ),
                                      const SizedBox(
                                        height: 5,
                                      ),
                                      Row(
                                        children: [
                                          Expanded(
                                            child: Row(
                                              children: [
                                                const Text('系统：'),
                                                const SizedBox(
                                                  width: 5,
                                                ),
                                                Text(_data[index]['systemName'] ?? ''),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                      const SizedBox(
                                        height: 5,
                                      ),
                                      Row(
                                        children: [
                                          Expanded(
                                            child: Row(
                                              children: [
                                                const Text('位置：'),
                                                const SizedBox(
                                                  width: 5,
                                                ),
                                                Text(_data[index]['buildingName'] ?? ''),
                                              ],
                                            ),
                                          ),
                                        ],
                                      )
                                    ],
                                  ),
                                ),
                              );
                            },
                          ),
                        ),
                      )
                    : const NoData()
              ],
            ),
          ),
          widget.showFilter
              ? Row(
                  children: [
                    Expanded(
                      child: DropdownHeader(
                        onTap: null,
                        fontSize: 13,
                        titles: [
                          choosePerson != null && choosePerson['name'] != null
                              ? choosePerson['name']
                              : scope[_scopeSelectIndex], //如果选择了维保执行人员则重置人员下拉列表，并将维保执行人员的名字放置于下拉列表处
                          date[_dateSelectIndex < 0 ? 0 : _dateSelectIndex],
                          status[_statusSelectIndex],
                          orderType[_orderTypeSelectIndex]
                        ],
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 8),
                      child: InkWell(
                        onTap: () async {
                          //暂存一下起始时间
                          String startDate = filterData['startDate'];
                          String endDate = filterData['endDate'];
                          await Get.to(TaskFilter(filterData, chooseDepartment, choosePerson));
                          //如果起始时间被修改，重置日期下拉列表的选择状态
                          if (startDate != filterData['startDate'] || endDate != filterData['endDate']) {
                            setState(() {
                              _dateSelectIndex = -1;
                            });
                          }
                          if (choosePerson != null && choosePerson['name'] != null) {
                            setState(() {
                              _scopeSelectIndex = -1;
                            });
                          }
                          print(filterData);
                          setState(() {
                            _page.current = 0;
                            _data.clear();
                          });
                          _getData();
                        },
                        child: Row(
                          children: const [
                            Text(
                              '筛选',
                              style: TextStyle(color: Colors.black54),
                            ),
                            Icon(
                              Icons.filter_alt_outlined,
                              size: 14,
                              color: Colors.black54,
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                )
              : Container(),
          Padding(
            padding: const EdgeInsets.only(top: 46.0),
            child: DropdownMenu(menus: [
              DropdownMenuBuilder(
                  builder: (BuildContext context) {
                    return DropdownListMenu(selectedIndex: 0, data: scope, itemBuilder: buildCheckItem);
                  },
                  height: (scope.length * 46).toDouble()),
              DropdownMenuBuilder(
                  builder: (BuildContext context) {
                    return DropdownListMenu(selectedIndex: 0, data: date, itemBuilder: buildCheckItem);
                  },
                  height: (date.length * 46).toDouble()),
              DropdownMenuBuilder(
                  builder: (BuildContext context) {
                    return DropdownListMenu(selectedIndex: 0, data: status, itemBuilder: buildCheckItem);
                  },
                  height: (status.length * 46).toDouble()),
              DropdownMenuBuilder(
                  builder: (BuildContext context) {
                    return DropdownListMenu(selectedIndex: 0, data: orderType, itemBuilder: buildCheckItem);
                  },
                  height: (orderType.length * 46).toDouble())
            ]),
          ),
        ],
      ),
    );
  }

  void _onRefresh() {
    setState(() {
      _data.clear();
    });
    _page.current = 0;
    _getData();
    _refreshController.refreshCompleted();
  }

  void _onLoading() {
    _page.current++;
    _getData();
    _refreshController.loadComplete();
  }

  Future<void> _getData() async {
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      //公用筛选页面，接口参数不一致，转化
      if(filterData['startDate']!= null){
        filterData['startDate'] = '${filterData['startDate']} 00:00:00';
      };
      if( filterData['endDate']!= null){
        filterData['endDate'] = '${filterData['endDate']} 23:59:59';
      };
      Map<String, Object> query ={
        'pageNumber': _page.current,
        'pageSize': _page.size,
        'qrCode':widget.fireFacilityCode,
        'beginTime':filterData['startDate'],
        'endTime':filterData['endDate'],
      };
      var data = await API.maintenanceRecord(query);
      if(filterData['startDate']!= null){
        List<String> l1 = filterData['startDate'].toString().split(' ');
        filterData['startDate'] = l1[0];
      };
      if(filterData['endDate']!= null){
        List<String> l2 = filterData['endDate'].toString().split(' ');
        filterData['endDate'] = l2[0];
      };
      Get.back();
      if (data != null) {
        if ((data['content'] ?? []).length == 0) {
          _refreshController.loadNoData();
          return;
        }
        setState(() {
          _data.addAll(data['content'].cast<Map<String, Object>>());
        });
        _refreshController.refreshCompleted();
        _refreshController.loadComplete();
      }
    });
  }

  Future<void> _getOderBy() async {
    var data = await API.maintenanceRecordSort();
    if (data != null) {
      setState(() {
        data.forEach((element) {
          orderType.add({'title': element.values.first, 'value': element.keys.first});
        });
      });
    }
  }

  Future<void> _getStatus() async {
    var data = await API.maintenanceRecordStatus();
    if (data != null) {
      setState(() {
        data.forEach((element) {
          status.add({'title': element['name'], 'value': element['code']});
        });
      });
    }
  }
}
