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 './filter_page.dart';
import '../../model/InspectionRecordModel.dart';
import '../../services/inspection_record.dart';
import '../../view/CheckExecute/checkexec_list_content.dart';

class RecordListScreen extends StatefulWidget {
  final DateTime currentDate;

  const RecordListScreen({this.currentDate});

  @override
  _RecordListScreenState createState() => _RecordListScreenState(currentDate);
}

class _RecordListScreenState extends State<RecordListScreen> with AutomaticKeepAliveClientMixin {
  // 页面接受参数
  DateTime currentDate;

  // 构造方法
  _RecordListScreenState(this.currentDate);

  @override
  bool get wantKeepAlive => true;

  // 当前页码
  int pageIndex = 0;

  // 是否有下一页
  bool hasNext = false;

  // 分页所需控件
  bool isAnimating = false;
  final EasyRefreshController _controllers = EasyRefreshController();

  List<InspectionRecord> initData = [];

  int myUserId;
  String theme = '';
  InspectionRecordFilter inspectionRecordFilter = InspectionRecordFilter();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color.fromRGBO(242, 246, 249, 1),
        appBar: AppBar(
          title: const Text(
            '巡检记录',
          ),
          centerTitle: true,
          elevation: 0.2,
          brightness: Brightness.light,
        ),
        body: ModalProgressHUD(
          child: _getWidget(),
          inAsyncCall: isAnimating,
          opacity: 0.7,
          progressIndicator: const CircularProgressIndicator(),
        ));
  }

  Widget _getWidget() {
    return buildInnerListHeaderDropdownMenu();
  }

  searchData() {
    initData = [];
    pageIndex = 0;
    loadData();
  }

  _searchData(InspectionRecordFilter filter) {
    if (filter.beginDate != "") {
      inspectionRecordFilter.beginDate = filter.beginDate;
    }
    if (filter.endDate != "") {
      inspectionRecordFilter.endDate = filter.endDate;
    }
    inspectionRecordFilter.departmentId = filter.departmentId;
    inspectionRecordFilter.planTaskId = filter.planTaskId;
    inspectionRecordFilter.pointId = filter.pointId;
    if (filter.userId != -1) {
      inspectionRecordFilter.userId = filter.userId;
    } else {
      inspectionRecordFilter.userId = myUserId;
    }
    if (filter.isOnlyMyInspection) {
      inspectionRecordFilter.userId = myUserId;
    }
    inspectionRecordFilter.bumen = filter.bumen;
    inspectionRecordFilter.jihua = filter.jihua;
    inspectionRecordFilter.renyuan = filter.renyuan;
    inspectionRecordFilter.dian = filter.dian;
    searchData();
  }

  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) {
                inspectionRecordFilter.userId = id;
              } else {
                inspectionRecordFilter.userId = myUserId;
              }
            });
            searchData();
          }
          if (menuIndex == 1) {
            setState(() {
              var id = data["id"] as int;
              if (id == 0) {
                // 今天
                DateTime now = DateTime.now();
                inspectionRecordFilter.beginDate = now.toString().substring(0, 10) + " 00:00:00";
                inspectionRecordFilter.endDate = now.toString().substring(0, 10) + " 23:59:59";
              } else if (id == 1) {
                // 昨天
                DateTime now = DateTime.now();
                inspectionRecordFilter.beginDate =
                    (now.add(const Duration(days: -1))).toString().substring(0, 10) + " 00:00:00";
                inspectionRecordFilter.endDate =
                    (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);
                inspectionRecordFilter.beginDate = firstDayOfWeek.toString().substring(0, 10) + " 00:00:00";
                inspectionRecordFilter.endDate = 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);
                inspectionRecordFilter.beginDate =
                    (firstDayOfWeek.add(const Duration(days: -7))).toString().substring(0, 10) + " 00:00:00";
                inspectionRecordFilter.endDate =
                    (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);
                inspectionRecordFilter.beginDate = firstDayOfMonth.toString().substring(0, 10) + " 00:00:00";
                inspectionRecordFilter.endDate = 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);
                inspectionRecordFilter.beginDate = preFirstDayOfMonth.toString().substring(0, 10) + " 00:00:00";
                inspectionRecordFilter.endDate = preLastDayOfMonth.toString().substring(0, 10) + " 23:59:59";
              }
            });
            searchData();
          }
          if (menuIndex == 2) {
            setState(() {
              inspectionRecordFilter.isOK = data["id"] as int;
            });
            searchData();
          }
          if (menuIndex == 3) {
            setState(() {
              var id = data["id"] as int;
              if (id == 0) {
                inspectionRecordFilter.orderBy = "checkDate asc";
              } else if (id == 1) {
                inspectionRecordFilter.orderBy = "checkDate desc";
              } else if (id == 2) {
                inspectionRecordFilter.orderBy = "pointNo asc";
              } else if (id == 3) {
                inspectionRecordFilter.orderBy = "pointNo 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: 46.0),
                child: Column(
                  children: <Widget>[
                    Expanded(
                        child: Stack(
                      children: <Widget>[
                        Center(
                            child: EasyRefresh(
                          controller: _controllers,
                          footer: MaterialFooter(),
                          header: MaterialHeader(),
                          child: ListView.builder(
                            //ListView的Item
                            itemCount: initData.length,
                            itemBuilder: (BuildContext context, int index) {
                              return GestureDetector(
                                  onTap: () {
                                    Navigator.push(context, MaterialPageRoute(builder: (context) {
                                      return CheckExecListContent(num.tryParse(initData[index].CheckId));
                                    }));
                                  },
                                  child: Container(
                                    child: Card(
                                      elevation: 0.2,
                                      margin: const EdgeInsets.only(top: 5, left: 10, right: 10),
                                      child: Container(
                                          height: 110.0,
                                          child: Row(
                                            children: <Widget>[
                                              Container(
                                                width: 8,
                                                height: 110,
                                                decoration: BoxDecoration(
                                                  borderRadius: const BorderRadius.only(
                                                      topLeft: Radius.circular(4), bottomLeft: Radius.circular(4)),
                                                  color: getPointColor(initData[index].IsQualified),
                                                ),
                                              ),
                                              Container(
                                                padding: const EdgeInsets.only(left: 10, top: 5),
                                                child: Column(
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                  children: <Widget>[
                                                    Container(
                                                        width: MediaQuery.of(context).size.width - 46,
                                                        child: Text(
                                                          (index + 1).toString() +
                                                                      "." +
                                                                      initData[index].InspectionPointName ==
                                                                  null
                                                              ? ""
                                                              : initData[index].InspectionPointName,
                                                          style: const TextStyle(
                                                              fontSize: 16.0, fontWeight: FontWeight.w500),
                                                          overflow: TextOverflow.ellipsis,
                                                        )),
                                                    const Padding(
                                                      padding: EdgeInsets.only(top: 5),
                                                    ),
                                                    Row(
                                                      children: <Widget>[
                                                        const Padding(
                                                          padding: EdgeInsets.only(left: 10),
                                                        ),
                                                        Text(
                                                          '编号:' + initData[index].Number ?? '',
                                                          style: const TextStyle(color: Colors.grey, fontSize: 12),
                                                        ),
                                                        const Padding(
                                                          padding: EdgeInsets.only(left: 36),
                                                        ),
                                                        Text(
                                                          getStatusName(initData[index].IsQualified),
                                                          style: TextStyle(
                                                              color: getPointColor(initData[index].IsQualified),
                                                              fontSize: 12),
                                                        ),
                                                      ],
                                                    ),
                                                    Row(
                                                      children: <Widget>[
                                                        const Padding(
                                                          padding: EdgeInsets.only(left: 10),
                                                        ),
                                                        Container(
                                                          width: MediaQuery.of(context).size.width - 80,
                                                          alignment: Alignment.centerLeft,
                                                          child: Text(
                                                            initData[index].InspectionPlanName == null
                                                                ? "计划:"
                                                                : "计划:" + initData[index].InspectionPlanName,
                                                            style: const TextStyle(color: Colors.grey, fontSize: 12),
                                                          ),
                                                        ),
                                                        Container(
                                                            padding: const EdgeInsets.only(right: 10),
                                                            alignment: Alignment.centerRight,
                                                            child: Icon(
                                                              Icons.keyboard_arrow_right,
                                                              color: GetConfig.getColor(theme),
                                                              size: 20,
                                                            )
                                                            //)
                                                            ),
                                                      ],
                                                    ),
                                                    Row(
                                                      children: <Widget>[
                                                        const Padding(
                                                          padding: EdgeInsets.only(left: 10),
                                                        ),
                                                        Container(
                                                          // width: 120,
                                                          child: Text(
                                                            initData[index].InspecterName == null
                                                                ? "巡检人:"
                                                                : "巡检人:" + initData[index].InspecterName ?? "",
                                                            maxLines: 1,
                                                            overflow: TextOverflow.ellipsis,
                                                            style: const TextStyle(color: Colors.grey, fontSize: 12),
                                                          ),
                                                        ),
                                                      ],
                                                    ),
                                                    Row(children: <Widget>[
                                                      const Padding(
                                                        padding: EdgeInsets.only(left: 10),
                                                      ),
                                                      //Expanded(child:
                                                      Container(
                                                        //width: 160,
                                                        alignment: Alignment.centerRight,
                                                        child: Text(
                                                          '时间:' + initData[index].InspectedTime ?? '',
                                                          style: const TextStyle(color: Colors.grey, 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) {
                                setState(() {
                                  pageIndex = pageIndex + 1;
                                });
                                loadData();
                              }
                            });
                          },
                        )),
                        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: Duration(milliseconds: 150), curve: Curves.ease)
          .whenComplete(() {
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return FilterPage(inspectionRecordFilter, 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": 1},
    {"title": "不合格", "id": 2},
    {"title": "漏检", "id": 3},
  ];

  static const List<Map<String, dynamic>> TITLE_TIME_CONTENT = [
    {"title": "时间倒序", "id": 1},
    {"title": "时间正序", "id": 0},
    {"title": "编号正序", "id": 2},
    {"title": "编号倒序", "id": 3},
  ];

  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: 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)
                                : 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: 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)
                                : 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),
    ]);
  }

  void getInitInfo() async {
    await SharedPreferences.getInstance().then((data) {
      if (data != null) {
        setState(() {
          myUserId = num.parse(data.getString("user_id")); //LoginResult(data.get('LoginResult')).user.id;
          inspectionRecordFilter.userId = myUserId;
          inspectionRecordFilter.isOK = -1;
          inspectionRecordFilter.departmentId = null;
          inspectionRecordFilter.planTaskId = -1;
          inspectionRecordFilter.pointId = -1;
          inspectionRecordFilter.orderBy = "checkDate desc";
          if (currentDate != null) {
            inspectionRecordFilter.beginDate = currentDate.toString().length > 10
                ? currentDate.toString().substring(0, 10) + " 00:00:00"
                : currentDate.toString() + " 00:00:00"; //.substring(0,19);
            inspectionRecordFilter.endDate = currentDate.toString().length > 10
                ? currentDate.toString().substring(0, 10) + " 23:59:59"
                : currentDate.toString() + " 23:59:59"; //.substring(0,19);
          } else {
            DateTime now = DateTime.now();
            inspectionRecordFilter.beginDate = now.toString().substring(0, 10) + " 00:00:00";
            inspectionRecordFilter.endDate = now.toString().substring(0, 10) + " 23:59:59";
          }
          this.theme = data.getString("theme") ?? KColorConstant.DEFAULT_COLOR;
        });
      }
    }).then((data) {
      loadData();
    });
  }

  loadData() async {
    setState(() {
      isAnimating = true;
    });
    await getInspectionRecordList(inspectionRecordFilter, pageIndex).then((data) {
      setState(() {
        if (data != null && data.content.length > 0) {
          for (dynamic p in data.content) {
            print(p);
            initData.add(InspectionRecord.fromParams(
                InspectionPointName: p["pointName"],
                Number: p["pointNo"],
                IsQualified: p["isOk"],
                InspectionPlanName: p["planName"],
                InspecterName: p["userName"],
                InspectedTime: p["checkTime"],
                PointId: p["pointId"],
                PlanTaskId: p["planTaskId"],
                CheckId: p["id"]));
          }
          hasNext = !data.last;
          _controllers.finishLoad(noMore: data.last);
        }
        isAnimating = false;
      });
    });
  }

  getPointColor(String statusName) {
    if (statusName == "合格") {
      return Colors.green;
    } else if (statusName == "不合格") {
      return Colors.red;
    } else if (statusName == "漏检") {
      return Colors.orange;
    } else {
      return Colors.black;
    }
  }

  getStatusName(String statusName) {
    if (statusName == "1") {
      return "合格";
    } else if (statusName == "2") {
      return "不合格";
    } else if (statusName == "3") {
      return "漏检";
    } else {
      return "";
    }
  }
}
