import 'package:amos_flutter_ui/amos_flutter_ui.dart' hide DropdownListMenu, DropdownHeader;
import 'package:amos_flutter_utils/date_utils.dart';
import 'package:amos_iot_login_tpl/amos_iot_login_tpl.dart';
import 'package:amos_iot_login_tpl/entity/platform_menu.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/dropdown_hander.dart';
import 'package:jcs_airport/view/common/dropdown_list_menu.dart';
import 'package:jcs_airport/view/common/no_data.dart';
import 'package:jcs_airport/view/workBench/maintenance/common/choose_maintenance_master_department.dart';
import 'package:jcs_airport/view/workBench/maintenance/common/choose_maintenance_person.dart';
import 'package:jcs_airport/view/workBench/maintenance/maintenanceTask/task_equipment.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';

///维保任务
class Task extends StatefulWidget {
  ///是否为业主单位角色
  static bool isMaster = false;

  ///userid
  static String userid = '';

  const Task({Key key}) : super(key: key);

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

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

  @override
  void initState() {
    super.initState();
    processFromHome();
    _getData();
    _getStatus();
    _getOrder();
    _userIdentify();
    SharedPreferences.getInstance().then((value) => scope.add(
          {'title': '我的', 'value': value.getString(GlobalConst.USER_ID)},
        ));
  }

  ///从首页跳转额外处理
  void processFromHome() {
    PlatformMenu platformMenu = Get.arguments;
    if (platformMenu != null) {
      switch (platformMenu.frontComponent) {
        case 'waitExecute':
          _statusSelectIndex = 2;
          filterData['finishStatus'] = 2;
          break;
        case 'timeout':
          _statusSelectIndex = 4;
          filterData['finishStatus'] = 4;
          break;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('维保任务'),
      ),
      body: 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['finishStatus'] = data['value'];
              } else {
                filterData.remove('finishStatus');
              }
              setState(() {
                _statusSelectIndex = index;
              });
              break;
            case 3:
              if (data['value'] != '') {
                filterData['orderBy'] = data['value'];
              } else {
                filterData.remove('orderBy');
              }
              setState(() {
                _orderTypeSelectIndex = index;
              });
              break;
          }
          setState(() {
            _data.clear();
            _page.current = 0;
          });
          _getData();
        },
        child: Stack(
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 46),
              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(
                                    hasState: true,
                                    stateColor: AMOSColors.maintenancePlanStatusColor(item['finishStatus']),
                                    hasFooter: true,
                                    footer: "${item['beginTime']} -- ${item['endTime']}",
                                    title: item['taskName'],
                                    onclick: () async {
                                      await Get.to(TaskEquipment(
                                          item['taskName'],
                                          (item['planTaskId'] ?? 0).toString(),
                                          (item['userId'] ?? 0).toString().contains(Task.userid), //是否为执行人
                                          (item['finishStatus'] ?? 0) == 1)); //是否为待执行
                                      setState(() {
                                        _data.clear();
                                        _page.current = 0;
                                      });
                                      _getData();
                                    });
                                return ListViewItem(
                                  listViewItemModel: listViewItemModel,
                                  contentWidget: Padding(
                                    padding: const EdgeInsets.all(5.0),
                                    child: Column(
                                      children: [
                                        Row(
                                          children: [
                                            Expanded(
                                              flex: 2,
                                              child: Row(
                                                children: [
                                                  const Text('任务批号：'),
                                                  const SizedBox(
                                                    width: 5,
                                                  ),
                                                  Text((item['batchNo'] ?? '').toString()),
                                                ],
                                              ),
                                            ),
                                            Expanded(
                                              child: Row(
                                                children: [
                                                  Text(
                                                    item['finishStatusDesc'].toString(),
                                                    style: TextStyle(
                                                        color: AMOSColors.maintenancePlanStatusColor(
                                                            item['finishStatus'])),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                        const SizedBox(
                                          height: 5,
                                        ),
                                        Row(
                                          children: [
                                            Expanded(
                                              child: Row(
                                                children: [
                                                  const Text('维保设施：'),
                                                  const SizedBox(
                                                    width: 5,
                                                  ),
                                                  Text((item['finishNum'] ?? '').toString()),
                                                ],
                                              ),
                                            ),
                                            Expanded(
                                              child: Row(
                                                children: [
                                                  const Text('剩余：'),
                                                  const SizedBox(
                                                    width: 5,
                                                  ),
                                                  Text((item['waitNum'] ?? 0).toString()),
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                        const SizedBox(
                                          height: 5,
                                        ),
                                        Row(
                                          children: [
                                            Expanded(
                                              child: Row(
                                                children: [
                                                  const Text('执行人：'),
                                                  const SizedBox(
                                                    width: 5,
                                                  ),
                                                  Text(item['userName']),
                                                ],
                                              ),
                                            ),
                                            Expanded(
                                              child: Row(
                                                children: [
                                                  const Text('单位：'),
                                                  const SizedBox(
                                                    width: 5,
                                                  ),
                                                  Text(item['ownerName']),
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              },
                            ),
                          ),
                        )
                      : const NoData()
                ],
              ),
            ),
            Row(
              children: [
                Expanded(
                  child: DropdownHeader(
                    fontSize: 13,
                    titles: [
                      choosePerson != null && choosePerson['name'] != null
                          ? choosePerson['name']
                          : scope[_scopeSelectIndex], //如果选择了维保执行人员则重置人员下拉列表，并将维保执行人员的名字放置于下拉列表处
                      date[_dateSelectIndex < 0 ? 0 : _dateSelectIndex],
                      status[_statusSelectIndex >= status.length ? 0 : _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,
                        )
                      ],
                    ),
                  ),
                ),
              ],
            ),
            Padding(
              padding: const EdgeInsets.only(top: 46.0),
              child: DropdownMenu(menus: [
                DropdownMenuBuilder(
                    builder: (BuildContext context) {
                      return DropdownListMenu(
                          selectedIndex: _scopeSelectIndex, data: scope, itemBuilder: buildCheckItem);
                    },
                    height: (scope.length * 46).toDouble()),
                DropdownMenuBuilder(
                    builder: (BuildContext context) {
                      return DropdownListMenu(selectedIndex: _dateSelectIndex, data: date, itemBuilder: buildCheckItem);
                    },
                    height: (date.length * 46).toDouble()),
                DropdownMenuBuilder(
                    builder: (BuildContext context) {
                      return DropdownListMenu(
                          selectedIndex: _statusSelectIndex, data: status, itemBuilder: buildCheckItem);
                    },
                    height: (status.length * 46).toDouble()),
                DropdownMenuBuilder(
                    builder: (BuildContext context) {
                      return DropdownListMenu(
                          selectedIndex: _orderTypeSelectIndex, data: orderType, itemBuilder: buildCheckItem);
                    },
                    height: (orderType.length * 46).toDouble())
              ]),
            ),
          ],
        ),
      ),
    );
  }

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

  void _onLoading() {
    _page.current += 1;
    _getData();
  }

  void _getData() {
    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';
      };
      var data = await API.queryPlanTask(filterData..addAll({'pageNumber': _page.current, 'pageSize': _page.size}));
      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();
      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];
      };

    });
  }

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

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

  Future<void> _userIdentify() async {
    var data = await API.userIdentify();
    if (data != null) {
      setState(() {
        if ((data['identityType'] ?? 2).toString() == '2') {
          Task.isMaster = true;
        }
        Task.userid = data['personSeq'];
      });
    }
  }
}

///筛选页面
class TaskFilter extends StatefulWidget {
  final Map<String, Object> filterData;
  final Map chooseDepartment;
  final Map choosePerson;

  const TaskFilter(this.filterData, this.chooseDepartment, this.choosePerson);

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

class _TaskFilterState extends State<TaskFilter> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('筛选'),
      ),
      body: Column(
        children: [
          Expanded(
            child: Form(
                child: Column(
              children: [
                const SizedBox(
                  height: 10,
                ),
                FormItem(
                    layout: FormLayout.vertical,
                    label: '开始日期',
                    formfield: InputDatePicker(
                      onChange: (val) {
                        setState(() {
                          widget.filterData['startDate'] = DateUtils.formatDate(val, format: 'yyyy-MM-dd');
                        });
                      },
                      value: widget.filterData['startDate'] ?? '',
                    )),
                const SizedBox(
                  height: 10,
                ),
                FormItem(
                    layout: FormLayout.vertical,
                    label: '结束日期',
                    formfield: InputDatePicker(
                      onChange: (val) {
                        setState(() {
                          widget.filterData['endDate'] = DateUtils.formatDate(val, format: 'yyyy-MM-dd');
                        });
                      },
                      value: widget.filterData['endDate'] ?? '',
                    )),
                const SizedBox(
                  height: 10,
                ),
                Task.isMaster
                    ? Container()
                    : Column(
                        children: [
                          FormItem(
                              layout: FormLayout.vertical,
                              label: '维保执行人员:',
                              formfield: SelectFormNewPage(
                                  value: widget.filterData['userName'] ?? '',
                                  selectPage: ChooseMaintenancePerson(
                                    person: widget.choosePerson,
                                  ),
                                  onChanged: (val) {
                                    if (val != null) {
                                      setState(() {
                                        widget.choosePerson.clear();
                                        widget.choosePerson.addAll(val);
                                        widget.filterData['userName'] = val['name'];
                                        widget.filterData['userId'] = val['sequenceNbr'];
                                      });
                                    }
                                  })),
                          const SizedBox(
                            height: 10,
                          ),
                          FormItem(
                              layout: FormLayout.vertical,
                              label: '业主单位:',
                              formfield: SelectFormNewPage(
                                  value: widget.filterData['companyName'] ?? '',
                                  selectPage: ChooseMaintenanceMasterDepartment(
                                    chooseDepartment: widget.chooseDepartment,
                                  ),
                                  onChanged: (val) {
                                    if (val != null) {
                                      setState(() {
                                        // widget.chooseDepartment.clear();
                                        // widget.chooseDepartment.addAll(val);
                                        widget.filterData['companyName'] = val['bizOrgName'];
                                        widget.filterData['companyId'] = val['sequenceNbr'];
                                      });
                                    }
                                  })),
                        ],
                      ),
              ],
            )),
          ),
          Padding(
            padding: const EdgeInsets.all(15.0),
            child: Row(
              children: [
                Expanded(
                    child: FlatButton(
                  color: const Color.fromRGBO(242, 246, 249, 1),
                  height: 40,
                  onPressed: () {
                    setState(() {
                      widget.filterData.clear();
                      widget.chooseDepartment.clear();
                    });
                  },
                  child: const Text(
                    '重置',
                    style: TextStyle(color: Colors.black87),
                  ),
                )),
                const SizedBox(
                  width: 5,
                ),
                Expanded(
                    child: FlatButton(
                  color: Theme.of(context).primaryColor,
                  height: 40,
                  onPressed: () {
                    Get.back(
                        result: {'choosePerson': widget.choosePerson, 'chooseDepartment': widget.chooseDepartment});
                  },
                  child: const Text(
                    '确定',
                    style: TextStyle(color: Colors.white),
                  ),
                )),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
