import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:base/consts/color.dart';
import 'package:base/consts/external_assets_package_key.dart';
import 'package:base/utils/GetConfig.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/Hidden_Danger/hidden_danger_model.dart';
import '../../services/HiddenDanger.dart';
import '../../view/hidedanger_manage/hidden_danger_procedded_hasChecked.dart';
import '../../view/hidedanger_manage/hidden_danger_processed_details_rescinded.dart';
import '../../view/hidedanger_manage/hidden_danger_search.dart';
import '../../view/hidedanger_manage/hidedanger_pending.dart';
import '../../view/plan_inspection/filter_page.dart';

class ProcessedHiddenDanger extends StatefulWidget {
  @override
  _ProcessedHiddenDanger createState() => _ProcessedHiddenDanger();
}

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

  bool isAnimating = false;
  String myUserId;
  List<HiddenDangerModel> initData = [];
  HiddenDangerFilter modelfilter = HiddenDangerFilter();
  String theme = '';
  bool hasNext = false;

  final EasyRefreshController _controllers = EasyRefreshController();

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

  Future<void> getAllDangerLevel() async {
    var ls = await GetAllDangerLevel();
    if (ls != null) {
      TITLE_GRADE_CONTENT.clear();
      setState(() {
        TITLE_GRADE_CONTENT.add({'title': '全部', 'id': -1});
        for (DangerLevelModel item in ls) {
          TITLE_GRADE_CONTENT.add({'title': item.dictDataDesc, 'id': int.parse(item.dictDataKey)});
        }
      });
    }
  }

  Future<void> getInitInfo() async {
    await SharedPreferences.getInstance().then((data) {
      if (data != null) {
        setState(() {
          myUserId = data.getString('loginUser');
          modelfilter.dangerName = '';
          modelfilter.pageSize = 10;
          modelfilter.pageIndex = 0;
          modelfilter.belongType = 1;
          modelfilter.dangerState = 0;
          modelfilter.dangerLevel = -1;
          modelfilter.isHandle = true;
          this.theme = data.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
        });
      }
    }).then((data) {
      loadData();
    });
  }

  Future<void> loadData() async {
    setState(() {
      if (modelfilter.pageIndex == 0) {
        isAnimating = true;
      } else {
        isAnimating = false;
      }
    });
    await getHiddenDangerList(modelfilter).then((data) {
      if (mounted) {
        setState(() {
          if (data.content != null && data.content.isNotEmpty) {
            for (dynamic p in data.content) {
              initData.add(HiddenDangerModel.fromParams(
                dangerId: p['dangerId'],
                level: int.parse(p['level'] ?? '0'),
                dangerName: p['dangerName'],
                discovererUserName: p['discovererUserName'],
                stateDesc: p['stateDesc'],
                limitDesc: p['limitDesc'],
                state: int.parse(p['state'] ?? '0'),
                levelDesc: p['levelDesc'],
                taskId: p['taskId'],
              ));
            }

            hasNext = !data.last;
          }
          isAnimating = false;
        });
      }
    });
  }

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

  void _searchData(HiddenDangerFilter filter) {
    if (filter.dangerLevel != -1) {
      modelfilter.dangerLevel = filter.dangerLevel;
    }
    if (filter.belongType != -1) {
      modelfilter.belongType = filter.belongType;
    }
    if (filter.dangerState != -1) {
      modelfilter.dangerState = filter.dangerState;
    }
    modelfilter.pageIndex = 0;
    modelfilter.pageSize = filter.pageSize;
    modelfilter.isHandle = true;
    searchData();
  }

  @override
  Widget build(BuildContext 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 HiddenDangerSearchPage(true);
              }));
            },
          )
        ],
      ),
      body: ModalProgressHUD(
        child: _getWidget(),
        inAsyncCall: isAnimating,
        opacity: 0.7,
        progressIndicator: const CircularProgressIndicator(),
      ),
      resizeToAvoidBottomPadding: false,
    );
  }

  Color getLevelTextBgColor(int level) {
    if (level == 1) return Colors.orange;
    if (level == 2) return Colors.red;
    return Colors.black;
  }

  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;
              modelfilter.belongType = id;
            });
            _searchData(modelfilter);
          }
          if (menuIndex == 1) {
            setState(() {
              var id = data['id'] as int;
              modelfilter.dangerState = id;
            });
            _searchData(modelfilter);
          }
          if (menuIndex == 2) {
            setState(() {
              var id = data['id'] as int;
              modelfilter.dangerLevel = id;
            });
            _searchData(modelfilter);
          }
        },
        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(
                      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) {
                                    switch (initData[index].state) {
                                      case 5: //治理完毕
                                        return HiddenDangerProcessedCheckedDetail(
                                            initData[index].dangerId, initData[index].taskId, true);
                                        break;
                                      case 6: //已撤销
                                        return HiddenDangerProcessedDetailsRescinded(
                                            initData[index].dangerId, initData[index].taskId, true);
                                        break;
                                      default:
                                        return HiddenDangerProcessedDetailsRescinded(
                                            initData[index].dangerId, initData[index].taskId, true);
                                        break;
                                    }
                                    // return  PlanListContent(initData[index].planTaskId);
                                  })).then((v) {
                                    modelfilter.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>[
                                          //任务类型
                                          Expanded(
                                            child: Column(
                                              children: <Widget>[
                                                Expanded(
                                                  child: Container(
                                                      alignment: Alignment.bottomCenter,
                                                      child: Image.asset(
                                                        PendingHideDanger.getDangerStateIcon(initData[index].state),
                                                        package: ExternalAssetsPackageKey.BASE,
                                                        height: 30,
                                                      )),
                                                ),
                                                Expanded(
                                                  child: Container(
                                                      alignment: Alignment.topCenter,
                                                      child: Text(
                                                        initData[index].stateDesc,
                                                        style: const TextStyle(color: Color.fromRGBO(154, 154, 154, 1)),
                                                      )),
                                                ),
                                              ],
                                            ),
                                            flex: 2,
                                          ),
                                          Expanded(
                                            child: SingleChildScrollView(
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: <Widget>[
                                                  //  隐患信息
                                                  Row(children: <Widget>[
                                                    Container(
                                                      padding: const EdgeInsets.only(left: 10, top: 8),
                                                      child: Text(
                                                        initData[index].dangerName ?? '',
                                                        style: const TextStyle(fontSize: 16.0, fontWeight: FontWeight.w500),
                                                      ),
                                                    ),
                                                  ]),
                                                  Row(
                                                    children: <Widget>[
                                                      Container(
                                                        padding: const EdgeInsets.only(left: 10, top: 6),
                                                        child: Text(
                                                          '发现人：${initData[index].discovererUserName ?? ' '}',
                                                          style: const TextStyle(color: Colors.grey, fontSize: 14),
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                  Row(
                                                    children: <Widget>[
                                                      Container(
                                                        padding: const EdgeInsets.only(left: 10, top: 5),
                                                        child: const Text('隐患等级：',
                                                            style: TextStyle(color: Colors.grey, fontSize: 14)),
                                                      ),
                                                      Container(
                                                        child: Text(initData[index].levelDesc,
                                                            style: TextStyle(
                                                                color: getLevelTextBgColor(initData[index].level), fontSize: 14)),
                                                      )
                                                    ],
                                                  ),
                                                  Row(
                                                    children: <Widget>[
                                                      Container(
                                                          padding: const EdgeInsets.only(left: 10, top: 5),
                                                          child: Text('治理期限：' + initData[index].limitDesc,
                                                              style: const TextStyle(color: Colors.grey, fontSize: 14))),
                                                    ],
                                                  ),
                                                ],
                                              ),
                                            ),
                                            flex: 7,
                                          ),
                                          Expanded(
                                            child: Container(
                                                child: Icon(
                                                  Icons.keyboard_arrow_right,
                                                  color: GetConfig.getColor(theme),
                                                ),
                                                alignment: Alignment.centerRight),
                                            flex: 1,
                                          ),
                                        ],
                                      )),
                                ),
                              );
                            },
                          ),
                          onRefresh: () async {
                            await Future.delayed(const Duration(seconds: 1), () {
                              setState(() {
                                modelfilter.pageIndex = 0;
                                initData = [];
                              });
                              loadData();
                            });
                          },
                          onLoad: () async {
                            await Future.delayed(const Duration(seconds: 1), () {
                              if (hasNext) {
                                setState(() {
                                  modelfilter.pageIndex = modelfilter.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: const Duration(milliseconds: 150), curve: Curves.ease)
          .whenComplete(() {
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return FilterPage(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 titleAll = '全部';
  String titleGrade = '全部';

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

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

  List<Map<String, dynamic>> TITLE_ALL_CONTENT = [
    {'title': '全部', 'id': 0},
    {'title': '治理完毕', 'id': 5},
    {'title': '已撤销', 'id': 6},
  ];

  List<Map<String, dynamic>> TITLE_GRADE_CONTENT = [
    {'title': '全部', 'id': -1},
    {'title': '安全隐患', 'id': 0},
    {'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>[
                        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_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_GRADE_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_GRADE_CONTENT.length),
    ]);
  }
}
