import 'dart:ui';

import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:base/consts/color.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:date_utils/date_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../model/plan_list_input.dart';
import '../../model/plan_list_output.dart';
import '../../services/plan_inspection_services.dart';
import '../../view/plan_inspection/filter_page.dart';
import '../../view/plan_inspection/global_search.dart';
import '../../view/plan_inspection/plan_list_content.dart';

class PlanListScreen extends StatefulWidget {
  @override
  _PlanListScreenState createState() => _PlanListScreenState();
}

class _PlanListScreenState extends State<PlanListScreen> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  bool isAnimating = false;
  int myUserId;
  List<PlanListOutput> initData = [];
  PlanListInput planListInput = PlanListInput();
  String theme = '';

  // 当前页码
  int pageIndex = 0;

  // 是否有下一页
  bool hasNext = false;
  final EasyRefreshController _controllers = EasyRefreshController();

  @override
  void initState() {
    super.initState();
    getInitInfo();
  }

  Future<void> getInitInfo() async {
    await SharedPreferences.getInstance().then((data) {
      if (data != null) {
        setState(() {
          myUserId = num.tryParse(data.get('user_id'));
          planListInput.userId = myUserId;
          planListInput.finishStatus = -1;
          planListInput.departmentId = 0;
          planListInput.routeId = -1;
          planListInput.orderBy = 'beginTime asc';
          DateTime now = DateTime.now();
          planListInput.startTime = now.toString().substring(0, 10) + ' 00:00:00';
          planListInput.endTime = now.toString().substring(0, 10) + ' 23:59:59';
          theme = data.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
        });
      }
    }).then((data) {
      loadData();
    });
  }

  Future<void> loadData() async {
    setState(() {
      if (pageIndex == 0) {
        isAnimating = true;
      } else {
        isAnimating = false;
      }
    });
    await getPlanListOutputList(planListInput, pageIndex).then((data) {
      setState(() {
        if (data != null && data.content.isNotEmpty) {
          for (final dynamic p in data.content) {
            initData.add(PlanListOutput.fromJson(p));
          }
          hasNext = !data.last;
          _controllers.finishLoad(noMore: data.last);
        }
        isAnimating = false;
      });
    }).then((value) {});
  }

  void searchData() {
    initData = [];
    loadData();
  }

  void _searchData(PlanListInput filter) {
    if (filter.startTime != '') {
      planListInput.startTime = filter.startTime;
    }
    if (filter.endTime != '') {
      planListInput.endTime = filter.endTime;
    }
    planListInput.departmentId = filter.departmentId;
    planListInput.routeId = filter.routeId;
    planListInput.bumen = filter.bumen;
    planListInput.luxian = filter.luxian;
    if (filter.userId != -1) {
      planListInput.userId = filter.userId;
      planListInput.renyuan = filter.renyuan;
    }
    searchData();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    if (theme.isEmpty) {
      return const Scaffold(body: Text(''));
    }
    return Scaffold(
      backgroundColor: const Color.fromRGBO(242, 246, 249, 1),
      appBar: AppBar(
        title: const Text(
          '计划巡检',
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
        actions: <Widget>[
          GestureDetector(
            child: Container(
              child: const Icon(Icons.search),
              padding: const EdgeInsets.only(right: 20),
            ),
            onTap: () {
              Navigator.push(context, MaterialPageRoute(builder: (context) {
                return GlobalSearch(0, planListInput);
              }));
            },
          )
        ],
      ),
      body: ModalProgressHUD(
        child: _getWidget(),
        inAsyncCall: isAnimating,
        opacity: 0.7,
        progressIndicator: const CircularProgressIndicator(),
      ),
      resizeToAvoidBottomPadding: false,
    );
  }

  Color getBgColor(int finishStatus) {
    if (finishStatus == 0) {
      // 未开始
      return Colors.grey;
    } else if (finishStatus == 1) {
      // 进行中
      return Colors.orange;
    } else if (finishStatus == 2) {
      // 已结束
      return Colors.red[800];
    } else if (finishStatus == 3) {
      // 已超时
      return Colors.redAccent;
    } else {
      return Colors.white;
    }
  }

  String getStatus(int finishStatus) {
    if (finishStatus == 0) {
      return '未开始';
    } else if (finishStatus == 1) {
      return '进行中';
    } else if (finishStatus == 2) {
      return '已结束';
    } else if (finishStatus == 3) {
      return '已超时';
    } else {
      return '';
    }
  }

  Widget _getWidget() {
    return buildInnerListHeaderDropdownMenu();
  }

  ScrollController scrollController = ScrollController();
  GlobalKey globalKey2 = GlobalKey();

  Widget buildInnerListHeaderDropdownMenu() {
    return DefaultDropdownMenuController(
        onSelected: ({int menuIndex, int index, int subIndex, dynamic data}) {
          if (menuIndex == 0) {
            setState(() {
              var id = data['id'] as int;
              if (id == -1) {
                planListInput.userId = id;
              } else {
                planListInput.userId = myUserId;
              }
            });
            searchData();
          }
          if (menuIndex == 1) {
            setState(() {
              var id = data['id'] as int;
              if (id == 0) {
                // 今天
                DateTime now = DateTime.now();
                planListInput.startTime = now.toString().substring(0, 10) + ' 00:00:00';
                planListInput.endTime = now.toString().substring(0, 10) + ' 23:59:59';
              } else if (id == 1) {
                // 昨天
                DateTime now = DateTime.now();
                planListInput.startTime = (now.add(const Duration(days: -1))).toString().substring(0, 10) + ' 00:00:00';
                planListInput.endTime = (now.add(const Duration(days: -1))).toString().substring(0, 10) + ' 23:59:59';
              } else if (id == 2) {
                // 本周
                DateTime now = DateTime.now();
                DateTime firstDayOfWeek = Utils.firstDayOfWeek(now);
                firstDayOfWeek = DateTime(firstDayOfWeek.year, firstDayOfWeek.month, firstDayOfWeek.day + 1, firstDayOfWeek.hour,
                    firstDayOfWeek.second);
                planListInput.startTime = firstDayOfWeek.toString().substring(0, 10) + ' 00:00:00';
                planListInput.endTime = now.toString().substring(0, 10) + ' 23:59:59';
              } else if (id == 3) {
                // 上周
                DateTime now = DateTime.now();
                DateTime firstDayOfWeek = Utils.firstDayOfWeek(now);
                firstDayOfWeek = DateTime(firstDayOfWeek.year, firstDayOfWeek.month, firstDayOfWeek.day + 1, firstDayOfWeek.hour,
                    firstDayOfWeek.second);
                planListInput.startTime =
                    (firstDayOfWeek.add(const Duration(days: -7))).toString().substring(0, 10) + ' 00:00:00';
                planListInput.endTime = (firstDayOfWeek.add(const Duration(days: -1))).toString().substring(0, 10) + ' 23:59:59';
              } else if (id == 4) {
                // 本月
                DateTime now = DateTime.now();
                DateTime firstDayOfMonth = Utils.firstDayOfMonth(now);
                DateTime lastDayOfMonth = Utils.lastDayOfMonth(now);
                planListInput.startTime = firstDayOfMonth.toString().substring(0, 10) + ' 00:00:00';
                planListInput.endTime = lastDayOfMonth.toString().substring(0, 10) + ' 23:59:59';
              } else if (id == 5) {
                // 上月
                DateTime now = DateTime.now();
                // 当前月第一天
                DateTime firstDayOfMonth = Utils.firstDayOfMonth(now);
                // 当前月第一天，减一天，是上个月最后一天
                DateTime preLastDayOfMonth = firstDayOfMonth.add(const Duration(days: -1));
                // 用上个月最后一天，获取上个月第一天
                DateTime preFirstDayOfMonth = Utils.firstDayOfMonth(preLastDayOfMonth);
                planListInput.startTime = preFirstDayOfMonth.toString().substring(0, 10) + ' 00:00:00';
                planListInput.endTime = preLastDayOfMonth.toString().substring(0, 10) + ' 23:59:59';
              }
              //              pageIndex = 0;
            });
            searchData();
          }
          if (menuIndex == 2) {
            setState(() {
              planListInput.finishStatus = data['id'] as int;
            });
            searchData();
          }
          if (menuIndex == 3) {
            setState(() {
              var id = data['id'] as int;
              if (id == 0) {
                planListInput.orderBy = 'beginTime asc';
              } else if (id == 1) {
                planListInput.orderBy = 'beginTime desc';
              } else if (id == 2) {
                planListInput.orderBy = 'taskPlanNum asc';
              } else if (id == 3) {
                planListInput.orderBy = 'taskPlanNum desc';
              } else if (id == 4) {
                planListInput.orderBy = 'finshNum asc';
              } else if (id == 5) {
                planListInput.orderBy = 'finshNum desc';
              }
            });
            searchData();
          }
        },
        child: Stack(
          children: <Widget>[
            CustomScrollView(controller: scrollController, slivers: <Widget>[
              SliverList(
                  key: globalKey2,
                  delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
                    return Container(
                      color: Colors.black26,
                    );
                  }, childCount: 1)),
              SliverPersistentHeader(
                delegate: DropdownSliverChildBuilderDelegate(builder: (BuildContext context) {
                  return Container(color: Colors.white, child: buildDropdownHeader(onTap: _onTapHead));
                }),
                pinned: true,
                floating: true,
              ),
              SliverList(delegate: SliverChildBuilderDelegate((BuildContext context, int index) {}, childCount: 10)),
            ]),
            Padding(
                padding: const EdgeInsets.only(top: 50.0),
                child: Column(
                  children: <Widget>[
                    Expanded(
                        child: Stack(
                      fit: StackFit.expand,
                      children: <Widget>[
                        EasyRefresh(
                          enableControlFinishRefresh: false,
                          enableControlFinishLoad: true,
                          controller: _controllers,
                          footer: MaterialFooter(),
                          header: MaterialHeader(),
                          child: ListView.builder(
                            itemCount: initData.length,
                            itemBuilder: (BuildContext context, int index) {
                              return GestureDetector(
                                onTap: () {
                                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                                    return PlanListContent(initData[index].planTaskId);
                                  })).then((v) {
                                    pageIndex = 0;
                                    initData = [];
                                    loadData();
                                  });
                                },
                                child: Container(
                                  height: 130.0,
                                  margin: const EdgeInsets.only(left: 10, right: 10),
                                  child: Card(
                                      elevation: 0.2,
                                      child: Row(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: <Widget>[
                                          Container(
                                            width: 8,
                                            height: 130,
                                            decoration: BoxDecoration(
                                                borderRadius: const BorderRadius.only(
                                                    topLeft: Radius.circular(4), bottomLeft: Radius.circular(4)),
                                                color: getBgColor(initData[index].finishStatus)),
                                          ),
                                          Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: <Widget>[
                                              const Padding(
                                                padding: EdgeInsets.only(top: 3),
                                              ),
                                              Container(
                                                width: MediaQuery.of(context).size.width - 40,
                                                padding: const EdgeInsets.only(left: 10),
                                                child: Text(
                                                  initData[index].taskName ?? '',
                                                  maxLines: 1,
                                                  overflow: TextOverflow.ellipsis,
                                                  style: const TextStyle(fontSize: 16.0, fontWeight: FontWeight.w500),
                                                ),
                                              ),
                                              const Padding(
                                                padding: EdgeInsets.only(top: 5),
                                              ),
                                              Container(
                                                  padding: const EdgeInsets.only(left: 10),
                                                  child: Row(
                                                    children: <Widget>[
                                                      Column(
                                                        children: <Widget>[
                                                          Row(
                                                            children: <Widget>[
                                                              Container(
                                                                width: 140,
                                                                child: Text(
                                                                  '计划批号:' + initData[index].batchNo.toString(),
                                                                  style: const TextStyle(color: Colors.grey, fontSize: 12),
                                                                ),
                                                              ),
                                                              Container(
                                                                width: 100,
                                                                child: Text(
                                                                  getStatus(initData[index].finishStatus),
                                                                  style: TextStyle(
                                                                      color: getBgColor(initData[index].finishStatus),
                                                                      fontSize: 12),
                                                                ),
                                                              )
                                                            ],
                                                          ),
                                                          Row(
                                                            children: <Widget>[
                                                              Container(
                                                                width: 140,
                                                                child: Text('计划巡检:' + initData[index].taskPlanNum.toString(),
                                                                    style: const TextStyle(color: Colors.grey, fontSize: 12)),
                                                              ),
                                                              Container(
                                                                width: 100,
                                                                child: Text(
                                                                    '剩余:' +
                                                                        (initData[index].taskPlanNum - initData[index].finshNum)
                                                                            .toString(),
                                                                    style: const TextStyle(color: Colors.grey, fontSize: 12)),
                                                              )
                                                            ],
                                                          ),
                                                          Row(
                                                            children: <Widget>[
                                                              Container(
                                                                width: 240,
                                                                child: initData[index].executiveName == null
                                                                    ? const Text('执行人:',
                                                                        style: TextStyle(color: Colors.grey, fontSize: 12))
                                                                    : Text('执行人:' + initData[index].executiveName,
                                                                        style: const TextStyle(color: Colors.grey, fontSize: 12)),
                                                              ),
                                                            ],
                                                          ),
                                                        ],
                                                      ),
                                                      Container(
                                                          margin: const EdgeInsets.only(left: 30, right: 10),
                                                          child: Icon(
                                                            Icons.keyboard_arrow_right,
                                                            color: GetConfig.getColor(theme),
                                                          ),
                                                          alignment: Alignment.centerRight),
                                                    ],
                                                  )),
                                              const Padding(
                                                padding: EdgeInsets.only(top: 10),
                                              ),
                                              Container(
                                                height: 25,
                                                width: MediaQuery.of(context).size.width - 46,
                                                color: Colors.grey[50],
                                                padding: const EdgeInsets.only(left: 10),
                                                alignment: Alignment.centerLeft,
                                                child: Text(
                                                  initData[index].beginTime + ' - ' + initData[index].endTime,
                                                  style: TextStyle(color: Colors.grey[500], fontSize: 12),
                                                ),
                                              )
                                            ],
                                          ),
                                        ],
                                      )),
                                ),
                              );
                            },
                          ),
                          onRefresh: () async {
                            await Future.delayed(const Duration(seconds: 1), () {
                              setState(() {
                                pageIndex = 0;
                                initData = [];
                              });
                              _controllers.resetLoadState();
                              loadData();
                            });
                          },
                          onLoad: () async {
                            await Future.delayed(const Duration(seconds: 1), () {
                              if (hasNext) {
                                pageIndex = pageIndex + 1;
                                loadData();
                              } else {
                                setState(() {
                                  isAnimating = false;
                                });
                              }
                            });
                          },
                        ),
                        buildDropdownMenu()
                      ],
                    ))
                  ],
                )),
          ],
        ));
  }

  void _onTapHead(int index) {
    RenderObject renderObject = globalKey2.currentContext.findRenderObject();
    DropdownMenuController controller = DefaultDropdownMenuController.of(globalKey2.currentContext);
    if (index == 4) {
      scrollController
          .animateTo(scrollController.offset + renderObject.semanticBounds.height,
              duration: const Duration(milliseconds: 150), curve: Curves.ease)
          .whenComplete(() {
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return FilterPage(inputFilter: planListInput, callback: (val) => _searchData(val));
        }));
      });
    } else {
      scrollController
          .animateTo(scrollController.offset + renderObject.semanticBounds.height,
              duration: const Duration(milliseconds: 150), curve: Curves.ease)
          .whenComplete(() {
        controller.show(index);
      });
    }
  }

  String titleMy = '我的';
  String titleToday = '今天';
  String titleAll = '所有';
  String titleTime = '时间正序';
  String titleFilter = '筛选';

  DropdownHeader buildDropdownHeader({DropdownMenuHeadTapCallback onTap}) {
    return DropdownHeader(
      onTap: onTap,
      fontSize: 13,
      titles: [titleMy, titleToday, titleAll, titleTime, titleFilter],
    );
  }

  static const int TYPE_INDEX = 0;
  static const List<Map<String, dynamic>> TITLE_MY_CONTENT = [
    {'title': '我的', 'id': 0},
    {'title': '全部', 'id': -1},
  ];

  static const List<Map<String, dynamic>> TITLE_TODAY_CONTENT = [
    {'title': '今天', 'id': 0},
    {'title': '昨天', 'id': 1},
    {'title': '本周', 'id': 2},
    {'title': '上周', 'id': 3},
    {'title': '本月', 'id': 4},
    {'title': '上月', 'id': 5},
  ];

  static const List<Map<String, dynamic>> TITLE_ALL_CONTENT = [
    {'title': '所有', 'id': -1},
    {'title': '未开始', 'id': 0},
    {'title': '进行中', 'id': 1},
    {'title': '已结束', 'id': 2},
    {'title': '已超时', 'id': 3},
  ];

  static const List<Map<String, dynamic>> TITLE_TIME_CONTENT = [
    {'title': '按时间正序', 'id': 0},
    {'title': '按时间倒序', 'id': 1},
    {'title': '计划数正序', 'id': 2},
    {'title': '计划数倒序', 'id': 3},
    {'title': '完成数正序', 'id': 4},
    {'title': '完成数倒序', 'id': 5},
  ];

  DropdownMenu buildDropdownMenu() {
    return DropdownMenu(
      maxMenuHeight: kDropdownMenuItemHeight * 10,
      blur: 0.0,
      menus: [
        DropdownMenuBuilder(
            builder: (BuildContext context) {
              return DropdownListMenu(
                selectedIndex: TYPE_INDEX,
                data: TITLE_MY_CONTENT,
                itemBuilder: (BuildContext context, dynamic data, bool selected) {
                  return Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: Text(
                              defaultGetItemLabel(data),
                              textAlign: TextAlign.center,
                              style: selected
                                  ? TextStyle(fontSize: 14.0, color: GetConfig.getColor(theme), fontWeight: FontWeight.w400)
                                  : const TextStyle(fontSize: 14.0),
                            ),
                          ),
                        ],
                      ));
                },
              );
            },
            height: kDropdownMenuItemHeight * TITLE_MY_CONTENT.length),
        DropdownMenuBuilder(
            builder: (BuildContext context) {
              return DropdownListMenu(
                selectedIndex: TYPE_INDEX,
                data: TITLE_TODAY_CONTENT,
                itemBuilder: (BuildContext context, dynamic data, bool selected) {
                  return Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: Text(
                              defaultGetItemLabel(data),
                              textAlign: TextAlign.center,
                              style: selected
                                  ? TextStyle(fontSize: 14.0, color: GetConfig.getColor(theme), fontWeight: FontWeight.w400)
                                  : const TextStyle(fontSize: 14.0),
                            ),
                          ),
                        ],
                      ));
                },
              );
            },
            height: kDropdownMenuItemHeight * TITLE_TODAY_CONTENT.length),
        DropdownMenuBuilder(
            builder: (BuildContext context) {
              return DropdownListMenu(
                selectedIndex: TYPE_INDEX,
                data: TITLE_ALL_CONTENT,
                itemBuilder: (BuildContext context, dynamic data, bool selected) {
                  return Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: Text(
                              defaultGetItemLabel(data),
                              textAlign: TextAlign.center,
                              style: selected
                                  ? TextStyle(fontSize: 14.0, color: GetConfig.getColor(theme), fontWeight: FontWeight.w400)
                                  : const TextStyle(fontSize: 14.0),
                            ),
                          ),
                        ],
                      ));
                },
              );
            },
            height: kDropdownMenuItemHeight * TITLE_ALL_CONTENT.length),
        DropdownMenuBuilder(
            builder: (BuildContext context) {
              return DropdownListMenu(
                selectedIndex: TYPE_INDEX,
                data: TITLE_TIME_CONTENT,
                itemBuilder: (BuildContext context, dynamic data, bool selected) {
                  return Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: Text(
                              defaultGetItemLabel(data),
                              textAlign: TextAlign.center,
                              style: selected
                                  ? TextStyle(fontSize: 14.0, color: GetConfig.getColor(theme), fontWeight: FontWeight.w400)
                                  : const TextStyle(fontSize: 14.0),
                            ),
                          ),
                        ],
                      ));
                },
              );
            },
            height: kDropdownMenuItemHeight * TITLE_TIME_CONTENT.length),
      ],
    );
  }
}
