import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_iot_login_tpl/amos_iot_login_tpl.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/cupertino.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 'package:get/get.dart';

import '../../model/Hidden_Danger/hidden_danger_model.dart';
import '../../services/HiddenDanger.dart';
import '../../view/hidedanger_manage/hidden_danger_check.dart';
import '../../view/hidedanger_manage/hidden_danger_company_review.dart';
import '../../view/hidedanger_manage/hidden_danger_department_review.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_rectification.dart';
import '../../view/hidedanger_manage/hidden_danger_review.dart';
import '../../view/hidedanger_manage/hidden_danger_search.dart';

class PendingHideDanger extends StatefulWidget {
  static String getDangerStateIcon(int state) {
    switch (state) {
      case 1:
        return 'assets/images/jiaoda/pendToreview.png';
        break;
      case 2:
        return 'assets/images/jiaoda/pendToreform.png';
        break;
      case 3:
        return 'assets/images/jiaoda/waitPlan.png';
        break;
      case 4:
        return 'assets/images/jiaoda/pendTocheck.png';
        break;
      case 5:
        return 'assets/images/jiaoda/hasCheck.png';
        break;
      case 6:
        return 'assets/images/jiaoda/hasRecinded.png';
        break;
      case 7:
        return 'assets/images/jiaoda/delay.png';
        break;
      case 8:
        return 'assets/images/jiaoda/pendToreview.png';
        break;
      case 9:
        return 'assets/images/jiaoda/pendToreview.png';
        break;
    }
  }

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

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

  bool isAnimating = false;
  int page = 0;
  List<HiddenDangerModel> initData = [];
  HiddenDangerFilter modelfilter = HiddenDangerFilter();
  String theme = '';
  bool hasNext = false;
  ScrollController scorController = ScrollController();
  final EasyRefreshController _controllers = EasyRefreshController();

  String titleMy = '我的';
  String titleAll = '全部';
  String titleGrade = '全部';

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

  List<Map<String, dynamic>> TITLE_ALL_CONTENT = [
    {'title': '全部', 'id': 0},
    {'title': '待评审', 'id': 1},
    {'title': '待治理', 'id': 2},
    {'title': '待验证', 'id': 4},
    {'title': '延期治理中', 'id': 7},
    {'title': '延期待车间部门审核', 'id': 8},
    {'title': '延期待公司审核', 'id': 9},
    {'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},
  ];

  @override
  void initState() {
    super.initState();
    scorController.addListener(() {
      print(scorController.offset);
    });
    dynamic map = Get.arguments;
    if (map is Map && map.isNotEmpty) {
      modelfilter.dangerId = map['id'];
    } else if (map != null && map is PlatformMenu && map.frontComponent == 'currentPatrolDangerWaitHandle') {
      setState(() {
        peopleIndex = 0;
        titleMy = '全部';
      });
    }
    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 (final DangerLevelModel item in ls) {
          TITLE_GRADE_CONTENT.add({'title': item.dictDataDesc, 'id': int.parse(item.dictDataKey ?? 0)});
        }
      });
    }
  }

  @override
  void dispose() {
    scorController.dispose();
    super.dispose();
  }

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

  Future<void> loadData({double i = 0.0}) 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 (final 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'],
                  overtimeState: p['overtimeState'],
                  state: int.parse(p['state'] ?? '0'),
                  taskId: p['taskId'],
                  levelDesc: p['levelDesc']));
            }
            hasNext = !data.last;
            _controllers.finishLoad(noMore: data.last);
          }
          isAnimating = false;
          modelfilter.pageIndex = page;
          modelfilter.pageSize = 10;
        });
        if (i > 0) {
          scorController.jumpTo(i);
        }
      }
    }).catchError((onError){
      print(onError);
      setState((){
        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;
    page = 0;
    modelfilter.pageSize = filter.pageSize;
    modelfilter.isHandle = false;
    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(false);
              }));
            },
          )
        ],
      ),
      body: ModalProgressHUD(
        child: _getWidget(),
        inAsyncCall: isAnimating,
        opacity: 0.7,
        progressIndicator: const CircularProgressIndicator(),
      ),
      resizeToAvoidBottomPadding: false,
    );
  }

  Color getLevelTextBgColor(int level) {
    if (level == 0) return const Color.fromRGBO(183, 28, 28, 1);
    if (level == 1) return const Color.fromRGBO(251, 140, 0, 1);
    if (level == 2) return const Color.fromRGBO(229, 57, 53, 1);
    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(
                            controller: scorController,
                            itemCount: initData.length,
                            shrinkWrap: true,
                            itemExtent: 130.0,
                            itemBuilder: (BuildContext context, int index) {
                              return GestureDetector(
                                onTap: () {
                                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                                    switch (initData[index].state) {
                                      case 1: //待评审
                                        return HiddenDangerReview(
                                          initData[index].dangerId,
                                          initData[index].taskId,
                                          state: initData[index].state,
                                        );
                                        break;
                                      case 2: //待治理
                                        return HiddenDangerRectification(initData[index].dangerId, initData[index].taskId,
                                            state: initData[index].state);
                                        break;
                                      case 3: //安措计划中
                                        return HiddenDangerProcessedDetailsRescinded(
                                            initData[index].dangerId, initData[index].taskId, false,
                                            state: initData[index].state);
                                        break;
                                      case 4:
                                        //待验证
                                        return HiddenDangerProcessedDetailsChecked(
                                            initData[index].dangerId, initData[index].taskId,
                                            state: initData[index].state);
                                        break;
                                      case 5: //治理完毕
                                        return HiddenDangerProcessedCheckedDetail(
                                            initData[index].dangerId, initData[index].taskId, false);
                                        break;
                                      case 6: //已撤销
                                        return HiddenDangerProcessedDetailsRescinded(
                                            initData[index].dangerId, initData[index].taskId, false);
                                        break;
                                      case 7: //延期待治理
                                        return HiddenDangerRectification(initData[index].dangerId, initData[index].taskId,
                                            state: initData[index].state);
                                        break;
                                      case 8: //延期治理中
                                        return HiddenDangerDepartReview(initData[index].dangerId, initData[index].taskId,
                                            state: initData[index].state);
                                        break;
                                      case 9:
                                        return HiddenDangerCompanyReview(initData[index].dangerId, initData[index].taskId,
                                            state: initData[index].state);
                                        break;
                                      default:
                                        return HiddenDangerProcessedDetailsRescinded(
                                            initData[index].dangerId, initData[index].taskId, false);
                                        break;
                                    }
                                  })).then((v) {
                                    final double e = scorController.offset;
                                    modelfilter.pageSize = (page + 1) * 10;
                                    modelfilter.pageIndex = 0;
                                    initData = [];

                                    loadData(i: e);
                                  });
                                },
                                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,
                                                          color: initData[index].overtimeState == 1 ||
                                                                  (initData[index].state >= 7 && initData[index].state <= 9)
                                                              ? Colors.red
                                                              : const Color.fromRGBO(50, 89, 206, 1))),
                                                ),
                                                Expanded(
                                                  child: Container(
                                                      alignment: Alignment.topCenter,
                                                      padding: const EdgeInsets.only(left: 5),
                                                      child: Text(
                                                        initData[index].stateDesc ?? '',
                                                        textAlign: TextAlign.center,
                                                        style: TextStyle(
                                                            fontSize: initData[index].stateDesc.length >= 5 ? 12 : 15,
                                                            color: const Color.fromRGBO(154, 154, 154, 1)),
                                                      )),
                                                ),
                                              ],
                                            ),
                                            flex: 2,
                                          ),
                                          Expanded(
                                            child: SingleChildScrollView(
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: <Widget>[
                                                  //  隐患信息
                                                  Container(
                                                    padding: const EdgeInsets.only(
                                                      left: 10,
                                                      top: 8,
                                                    ),
                                                    width: MediaQuery.of(context).size.width - 60,
                                                    child: Text(
                                                      initData[index].dangerName ?? '',
                                                      overflow: TextOverflow.ellipsis,
                                                      maxLines: 1,
                                                      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: const Text('治理期限：',
                                                              style: TextStyle(color: Colors.grey, fontSize: 14))),
                                                      Container(
                                                          padding: const EdgeInsets.only(left: 0, top: 5),
                                                          child: Text(initData[index].limitDesc ?? '',
                                                              style: TextStyle(
                                                                  color: initData[index].overtimeState == 1
                                                                      ? Colors.red
                                                                      : Colors.grey,
                                                                  fontSize: 14))),
                                                    ],
                                                  ),
                                                ],
                                              ),
                                            ),
                                            flex: 5,
                                          ),

                                          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;
                                page = 0;
                                initData = [];
                              });
                              _controllers.resetLoadState();
                              loadData();
                            });
                          },
                          onLoad: () async {
                            await Future.delayed(const Duration(seconds: 1), () {
                              if (hasNext) {
                                setState(() {
                                  modelfilter.pageIndex = modelfilter.pageIndex + 1;
                                  page = page + 1;
                                });
                                loadData();
                              } else {
                                setState(() {
                                  isAnimating = false;
                                });
                              }
                            });
                          },
                        ),
                        buildDropdownMenu()
                      ],
                    ))
                  ],
                )),
          ],
        ));
  }

  void _onTapHead(int index) {
    RenderObject renderObject = globalKey2.currentContext.findRenderObject();
    DropdownMenuController controller = DefaultDropdownMenuController.of(globalKey2.currentContext);
    scrollController
        .animateTo(scrollController.offset + renderObject.semanticBounds.height,
            duration: const Duration(milliseconds: 150), curve: Curves.ease)
        .whenComplete(() {
      controller.show(index);
    });
  }

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

  DropdownMenu buildDropdownMenu() {
    return DropdownMenu(maxMenuHeight: kDropdownMenuItemHeight * 10, blur: 0.0, menus: [
      DropdownMenuBuilder(
          builder: (BuildContext context) {
            return DropdownListMenu(
              selectedIndex: peopleIndex,
              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: stateIndex,
              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: typeIndex,
              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),
    ]);
  }
}
