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

import '../../model/CheckExecute/check_point_record_list.dart';
import '../../model/plan_list_input.dart';
import '../../services/CheckRecordServices.dart';
import '../../view/CheckExecute/checkexec_list_content.dart';
import '../../view/CheckExecute/filter_page.dart';

class CheckExecListScreen extends StatefulWidget {
  final num pointId;
  final String pointName;

  CheckExecListScreen(this.pointId, this.pointName);

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

class _CheckExecListScreenState extends State<CheckExecListScreen> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  List<bool> offStageLst = [];
  List<String> dateKeyVisible = [];
  PlanListInput planListInput = PlanListInput();
  num myUserId;
  Map<String, List<CheckPointRecordDetail>> pageData = {};
  String theme = '';

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

    getInitInfo();
  }

  void getInitInfo() async {
    await SharedPreferences.getInstance().then((data) {
      if (data != null) {
        setState(() {
          myUserId = num.parse(data.get('user_id'));
          planListInput.userId = myUserId;
          planListInput.finishStatus = -1;
          planListInput.departmentId = -1;
          planListInput.routeId = -1;
          DateTime now = DateTime.now();
          planListInput.startTime = now.toString().substring(0, 10);
          planListInput.endTime = now.toString().substring(0, 10);
          theme = data.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
        });
      }
    }).then((data) {
      getData();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.pointName == null || widget.pointName.isEmpty ? '巡检点名称' : widget.pointName,
        ),
        centerTitle: true,
        elevation: 0.7,
        brightness: Brightness.light,
      ),
      body: _getWidget(),
    );
  }

  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(() {
              planListInput.finishStatus = data["id"] as int;
            });
            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: Theme.of(context).scaffoldBackgroundColor,
                      child: buildDropdownHeader(onTap: this._onTapHead));
                }),
                pinned: true,
                floating: true,
              ),
              SliverList(
                  delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
                return Container(
                  color: Theme.of(context).scaffoldBackgroundColor,
                );
              }, childCount: 10)),
            ]),
            Padding(
              padding: const EdgeInsets.only(top: 46.0),
              child: Stack(
                children: <Widget>[
                  Column(
                    children: <Widget>[
                      Expanded(
                        child: ListView.builder(
                            itemCount: 1,
                            itemBuilder: (context, index) {
                              return Column(
                                  children: pageData.keys.map((k) {
                                return Column(
                                  children: <Widget>[
                                    GestureDetector(
                                      child: Container(
                                        color: Theme.of(context).scaffoldBackgroundColor,
                                        child: Row(
                                          children: <Widget>[
                                            Text(k, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w500)),
                                            const Padding(
                                              padding: EdgeInsets.only(right: 200),
                                            ),
                                            Icon(
                                              !dateKeyVisible.contains(k)
                                                  ? Icons.keyboard_arrow_right
                                                  : Icons.keyboard_arrow_down,
                                              color: Colors.red,
                                            )
                                          ],
                                        ),
                                        height: 50,
                                        width: double.infinity,
                                        padding: const EdgeInsets.only(left: 20, right: 10, top: 5),
                                        alignment: Alignment.centerLeft,
                                      ),
                                      onTap: () {
                                        setState(() {
                                          !dateKeyVisible.contains(k)
                                              ? dateKeyVisible.add(k)
                                              : dateKeyVisible.remove(k);
                                        });
                                      },
                                    ),
                                    const Divider(
                                      height: 1,
                                    ),
                                    Offstage(
                                      offstage: dateKeyVisible.indexOf(k) == -1 ? true : false,
                                      child: Column(
                                        children: pageData[k].map((v) {
                                          return Column(
                                            children: <Widget>[
                                              Container(
                                                child: TimelineView.builder(
                                                    left: 30.0,
                                                    leftLine: 45.0,
                                                    itemCount: 1,
                                                    itemBuilder: (index) {
                                                      return GestureDetector(
                                                        child: TimelineTile(
                                                          height: 90,
                                                          title: Text(
                                                            getStatusName(v.is_ok),
                                                            style: TextStyle(color: getPointColor(v.is_ok)),
                                                          ),
                                                          subTitle: Column(
                                                            crossAxisAlignment: CrossAxisAlignment.start,
                                                            children: <Widget>[
                                                              Text(v.checkTime ?? "" + " 姓名TODO" /*+ " " + v.userName*/,
                                                                  style: const TextStyle(color: Colors.grey)),
                                                              Row(
                                                                children: <Widget>[
                                                                  const Text('计划名称:',
                                                                      style: TextStyle(color: Colors.grey)),
                                                                  Container(
                                                                      width: 150,
//                                                                            height: 30,
                                                                      child: Text(
                                                                        v.planName ?? '',
                                                                        style: const TextStyle(color: Colors.grey),
                                                                        overflow: TextOverflow.ellipsis,
                                                                      ))
                                                                ],
                                                              )
                                                            ],
                                                          ),
                                                          dotColor: getPointColor(v.is_ok),
                                                          gap: 0.0,
                                                          trailing: const Icon(
                                                            Icons.keyboard_arrow_right,
                                                            color: Colors.red,
                                                            size: 18,
                                                          ),
                                                        ),
                                                        onTap: () {
                                                          Navigator.push(context, MaterialPageRoute(builder: (context) {
                                                            return CheckExecListContent(v.id);
                                                          }));
                                                        },
                                                      );
                                                    }),
                                                height: 105.0,
                                              ),
                                              const Divider(
                                                height: 1,
                                              ),
                                            ],
                                          );
                                        }).toList(),
                                      ),
                                    )
                                  ],
                                );
                              }).toList());
                            }),
                      )
                    ],
                  ),
                  buildDropdownMenu()
                ],
              ),
            ),
          ],
        ));
  }

  void _onTapHead(int index) {
    RenderObject renderObject = globalKey2.currentContext.findRenderObject();
    DropdownMenuController controller = DefaultDropdownMenuController.of(globalKey2.currentContext);

    if (index == 2) {
      scrollController
          .animateTo(scrollController.offset + renderObject.semanticBounds.height,
              duration: const Duration(milliseconds: 150), curve: Curves.ease)
          .whenComplete(() {
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return FilterPage(planListInput, callback: (data) => callBack(data));
        }));
      });
    } else {
      scrollController
          .animateTo(scrollController.offset + renderObject.semanticBounds.height,
              duration: const Duration(milliseconds: 150), curve: Curves.ease)
          .whenComplete(() {
        controller.show(index);
      });
    }
  }

  String titleMy = '我的';
  String titleAll = '所有';
  String titleFilter = '筛选';

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

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

  static const List<Map<String, dynamic>> TITLE_ALL_CONTENT = [
    {"title": "所有", "id": -1},
    {"title": "合格", "id": 1},
    {"title": "不合格", "id": 2},
  ];

  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>[
                        Text(
                          defaultGetItemLabel(data),
                          style: selected
                              ? TextStyle(fontSize: 14.0, color: Theme.of(context).primaryColor, fontWeight: FontWeight.w400)
                              : const TextStyle(fontSize: 14.0),
                        ),
                        Expanded(
                            child: Align(
                          alignment: Alignment.center,
                          child: selected
                              ? Icon(
                                  Icons.check,
                                  color: Theme.of(context).primaryColor,
                                )
                              : null,
                        )),
                      ],
                    ));
              },
            );
          },
          height: kDropdownMenuItemHeight * TITLE_MY_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>[
                        Text(
                          defaultGetItemLabel(data),
                          style: selected
                              ? TextStyle(fontSize: 14.0, color: Theme.of(context).primaryColor, fontWeight: FontWeight.w400)
                              : const TextStyle(fontSize: 14.0),
                        ),
                        Expanded(
                            child: Align(
                          alignment: Alignment.center,
                          child: selected
                              ? Icon(
                                  Icons.check,
                                  color: Theme.of(context).primaryColor,
                                )
                              : null,
                        )),
                      ],
                    ));
              },
            );
          },
          height: kDropdownMenuItemHeight * TITLE_ALL_CONTENT.length),
    ]);
  }

  // 删选页面回调函数
  callBack(PlanListInput data) {
    // if(data.userId!=-1){
    //   data.userId = myUserId;
    // }
    setState(() {
      planListInput = data;
    });

    searchData();
  }

  searchData() {
    setState(() {
      this.pageData = Map();
    });
    getData();
  }

  getData() async {
    await getCheckPointRecordList(planListInput, this.widget.pointId).then((data) {
      setState(() {
        print(data);
        pageData = data;
        pageData.forEach((k, v) {
          dateKeyVisible.add(k);
        });
      });
    });
  }

  getPointColor(String statusName) {
    if (statusName == "1") {
      return Colors.green;
    } else if (statusName == "2") {
      return Colors.red;
    } else if (statusName == "3") {
      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 "";
    }
  }
}
