import 'package:base/consts/color.dart';
import 'package:base/consts/external_assets_package_key.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/CheckPoint.dart';
import '../../services/check_point_service.dart';
import '../../view/CheckExecute/navigation_checkexec.dart';

class MovePointSearch extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MovePointSearch();
}

class _MovePointSearch extends State<MovePointSearch> with SingleTickerProviderStateMixin {
  TabController _tabController;
  int _selectedIndex = 0;
  var titles = ['全部', '巡检点', '检查项'];
  Map<int, PageData> allData = {};
  bool isAnimating = false;
  EasyRefreshController _controllers = EasyRefreshController();
  final EasyRefreshController _controllers1 = EasyRefreshController();
  final EasyRefreshController _controllers2 = EasyRefreshController();
  final EasyRefreshController _controllers3 = EasyRefreshController();
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();

  String theme = '';
  bool searchBtnPressed = false;

  @override
  void initState() {
    super.initState();
    initConfig();
    _tabController = TabController(vsync: this, initialIndex: 0, length: titles.length);
    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        setState(() {
          _selectedIndex = _tabController.index;
          if (_selectedIndex == 0) {
            _controllers = _controllers1;
          } else if (_selectedIndex == 1) {
            _controllers = _controllers2;
          } else {
            _controllers = _controllers3;
          }
        });
      }
    });
    setState(() {
      allData[0] = PageData();
      allData[1] = PageData();
      allData[2] = PageData();
    });
  }

  // 检索数据
  Future<void> searchData() async {
    setState(() {
      isAnimating = true;
    });
    // '巡检点', "检查项",
    int pageindex = allData[_selectedIndex].pageindex ?? 0;
    if (_selectedIndex == 0) {
      await queryPointPageForSearch('all', pageindex, 10, keywords: _controller.text, isFix: false).then((data) {
        setState(() {
          if (null == allData[_selectedIndex].content) {
            allData[_selectedIndex].content = [];
          }
          allData[_selectedIndex].content.addAll(data.content);
          allData[_selectedIndex].hasnext = !data.last;
          _controllers1.finishLoad(noMore: data.last);
          isAnimating = false;
          searchBtnPressed = false;
        });
      });
    } else if (_selectedIndex == 1) {
      await queryPointPageForSearch('point', pageindex, 10, keywords: _controller.text, isFix: false).then((data) {
        setState(() {
          if (null == allData[_selectedIndex].content) {
            allData[_selectedIndex].content = [];
          }
          allData[_selectedIndex].content.addAll(data.content);
          allData[_selectedIndex].hasnext = !data.last;
          _controllers2.finishLoad(noMore: data.last);
          isAnimating = false;
          searchBtnPressed = false;
        });
      });
    } else if (_selectedIndex == 2) {
      await queryPointPageForSearch('inputItem', pageindex, 10, keywords: _controller.text, isFix: false).then((data) {
        setState(() {
          if (null == allData[_selectedIndex].content) {
            allData[_selectedIndex].content = [];
          }
          allData[_selectedIndex].content.addAll(data.content);
          allData[_selectedIndex].hasnext = !data.last;
          _controllers3.finishLoad(noMore: data.last);
          isAnimating = false;
          searchBtnPressed = false;
        });
      });
    }
  }

  Future<void> initConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        theme = preferences.getString(theme) ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (theme.isEmpty) {
      return const Scaffold(body: Text(''));
    }
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
        title: Container(
            height: 30,
            width: MediaQuery.of(context).size.width - 130,
            padding: const EdgeInsets.only(bottom: 5),
            decoration: BoxDecoration(
              color: Colors.grey[100],
              borderRadius: const BorderRadius.all(Radius.circular(25.0)),
            ),
            child: Row(
              children: <Widget>[
                Container(
                  padding: const EdgeInsets.only(left: 5, right: 5, top: 6),
                  child: Image.asset('assets/images/search_red.png',
                      package: ExternalAssetsPackageKey.BASE, width: 20, color: Theme.of(context).primaryColor),
                ),
                Container(
                  width: MediaQuery.of(context).size.width - 180,
                  child: TextField(
                      controller: _controller,
                      focusNode: _focusNode,
                      style: const TextStyle(fontSize: 16.0, color: Colors.black),
                      decoration: const InputDecoration(
                          border: InputBorder.none, contentPadding: EdgeInsets.only(bottom: 1, top: -15))),
                )
              ],
            )),
        actions: <Widget>[
          Align(
              child: Padding(
            padding: const EdgeInsets.only(right: 8),
            child: GestureDetector(
              onTap: () {
                if (searchBtnPressed) {
                } else {
                  setState(() {
                    allData[_selectedIndex].content = [];
                    allData[_selectedIndex].pageindex = 0;
                    allData[_selectedIndex].hasnext = false;
                    searchBtnPressed = true;
                  });
                  searchData();
                }
              },
              child: const Text(
                '搜索',
                style: TextStyle(color: Colors.white, fontSize: 16.0),
              ),
            ),
          ))
        ],
        bottom: TabBar(
          unselectedLabelColor: Colors.white54,
          labelColor: Colors.white,
          isScrollable: true,
          indicatorColor: Theme.of(context).primaryColor,
          tabs: titles.map((t) {
            return Tab(
              text: t,
            );
          }).toList(),
          controller: _tabController,
        ),
      ),
      body: ModalProgressHUD(
        child: Container(
          child: Column(
            children: <Widget>[
              Expanded(
                child: EasyRefresh(
                  enableControlFinishRefresh: false,
                  enableControlFinishLoad: true,
                  controller: _controllers,
                  footer: MaterialFooter(),
                  header: MaterialHeader(),
                  child: ListView.builder(
                    itemCount: 1,
                    itemBuilder: (BuildContext context, int index) {
                      return Column(
                        children: allData[_selectedIndex].content.map((data) {
                          return buildListView(index, data);
                        }).toList(),
                      );
                    },
                  ),
                  onLoad: () async {
                    await Future.delayed(const Duration(seconds: 1), () {
                      if (allData[_selectedIndex].hasnext) {
                        setState(() {
                          allData[_selectedIndex].pageindex = allData[_selectedIndex].pageindex + 1;
                        });
                        searchData();
                      }
                    });
                  },
                ),
                flex: 4,
              ),
            ],
          ),
        ),
        inAsyncCall: isAnimating,
        opacity: 0.7,
        progressIndicator: const CircularProgressIndicator(),
      ),
    );
  }

  //['巡检点', '计划', '线路', "记录", "任务", "检查项", "人员"];
  Widget buildListView(int index, dynamic data) {
    return buildPointList(index, data);
  }

  // 构造巡检点listview
  Widget buildPointList(int index, dynamic data) {
    CheckPoint point = CheckPoint.fromJson(data);
    return Card(
        elevation: 0.2,
        child: ListTile(
            isThreeLine: true,
            dense: false,
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  point.name,
                  style: const TextStyle(fontSize: 18.0, fontWeight: FontWeight.w600),
                ),
                const Padding(
                  padding: EdgeInsets.only(top: 5),
                ),
                Text(
                  '编号:' + point.pointNo,
                  style: const TextStyle(fontSize: 14.0, color: Colors.grey),
                ),
              ],
            ),
            trailing: const Padding(
              child: Icon(Icons.keyboard_arrow_right),
              padding: EdgeInsets.only(top: 15),
            ),
            onTap: () {
              Navigator.push(context, MaterialPageRoute(builder: (context) {
                return NavigationCheckExec(point.id, pointName: point.name);
              }));
            }));
  }
}

class PageData {
  int pageindex = 0;
  bool hasnext = false;
  List<dynamic> content = [];
}
