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/plan_list_input.dart';
import '../../model/plan_list_output.dart';
import '../../services/plan_inspection_services.dart';
import '../../view/plan_inspection/plan_list_content.dart';

class GlobalSearch extends StatefulWidget {
  final num type; // 0:计划巡检,1:移动巡检
  final PlanListInput planListInput;

  const GlobalSearch(this.type, this.planListInput);

  @override
  State<StatefulWidget> createState() => _GlobalSearch();
}

class _GlobalSearch extends State<GlobalSearch> with SingleTickerProviderStateMixin {
  TabController _tabController;
  int _selectedIndex = 0;

  var titles = ['全部', '线路', '计划', '检查点', '执行人'];
  Map<int, PageData> allData = {};

  bool isAnimating = false;

  final EasyRefreshController _controllers = 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);
      }
    });
    setState(() {
      allData[0] = PageData();
      allData[1] = PageData();
      allData[2] = PageData();
      allData[3] = PageData();
      allData[4] = PageData();
    });
  }

  // 检索数据
  void searchData() async {
    setState(() {
      isAnimating = true;
    });
    // '全部','线路', '计划',"检查项", "检查点"
    int pageindex = allData[_selectedIndex].pageindex ?? 0;
    if (_selectedIndex == 0) {
      await getPlanListForSelect('all', pageindex, 10, widget.planListInput, keywords: _controller.text).then((data) {
        setState(() {
          if (null == allData[_selectedIndex].content) {
            allData[_selectedIndex].content = [];
          }
          allData[_selectedIndex].content.addAll(data.content);
          allData[_selectedIndex].hasnext = !data.last;
          isAnimating = false;
          searchBtnPressed = false;
        });
      });
    } else if (_selectedIndex == 1) {
      await getPlanListForSelect('route', pageindex, 10, widget.planListInput, keywords: _controller.text).then((data) {
        setState(() {
          if (null == allData[_selectedIndex].content) {
            allData[_selectedIndex].content = [];
          }
          allData[_selectedIndex].content.addAll(data.content);
          allData[_selectedIndex].hasnext = !data.last;
          isAnimating = false;
          searchBtnPressed = false;
        });
      });
    } else if (_selectedIndex == 2) {
      await getPlanListForSelect('plan', pageindex, 10, widget.planListInput, keywords: _controller.text).then((data) {
        setState(() {
          if (null == allData[_selectedIndex].content) {
            allData[_selectedIndex].content = [];
          }
          allData[_selectedIndex].content.addAll(data.content);
          allData[_selectedIndex].hasnext = !data.last;
          isAnimating = false;
          searchBtnPressed = false;
        });
      });
    } else if (_selectedIndex == 3) {
      await getPlanListForSelect('point', pageindex, 10, widget.planListInput, keywords: _controller.text).then((data) {
        setState(() {
          if (null == allData[_selectedIndex].content) {
            allData[_selectedIndex].content = [];
          }
          allData[_selectedIndex].content.addAll(data.content);
          allData[_selectedIndex].hasnext = !data.last;
          isAnimating = false;
          searchBtnPressed = false;
        });
      });
    } else if (_selectedIndex == 4) {
      await getPlanListForSelect('executiveName', pageindex, 10, widget.planListInput, keywords: _controller.text)
          .then((data) {
        setState(() {
          if (null == allData[_selectedIndex].content) {
            allData[_selectedIndex].content = [];
          }
          allData[_selectedIndex].content.addAll(data.content);
          allData[_selectedIndex].hasnext = !data.last;
          isAnimating = false;
          searchBtnPressed = false;
        });
      });
    }
  }

  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: Icon(
                    Icons.search,
                    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(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(
                '搜索',
              ),
            ),
          ))
        ],
        bottom: TabBar(
          indicator: const BoxDecoration(),
          unselectedLabelColor: Colors.white60,
          unselectedLabelStyle: const TextStyle(fontSize: 16),
          labelColor: Colors.white,
          labelStyle: const TextStyle(fontSize: 16),
          isScrollable: true,
          tabs: titles.map((t) {
            return Tab(
              text: t,
            );
          }).toList(),
          controller: _tabController,
        ),
      ),
      body: ModalProgressHUD(
        child: Container(
          margin: const EdgeInsets.only(top: 4),
          child: Column(
            children: <Widget>[
              Expanded(
                child: EasyRefresh(
                  enableControlFinishRefresh: false,
                  enableControlFinishLoad: true,
                  controller: _controllers,
                  footer: MaterialFooter(),
                  header: MaterialHeader(),
                  child: ListView.builder(
                    //ListView的Item
                    itemCount: 1,
                    itemBuilder: (BuildContext context, int index) {
                      return Column(
                        children: allData[_selectedIndex].content.map((data) {
                          return buildListView(index, data);
                        }).toList(),
                      );
                    },
                  ),
                  onRefresh: () async {
                    await Future.delayed(const Duration(seconds: 1), () {
                      searchData();
                    });
                  },
                  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,
        // demo of some additional parameters
        opacity: 0.7,
        progressIndicator: const CircularProgressIndicator(),
      ),
    );
  }

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

  // 构造巡检点listview
  Widget buildPointList(int index, dynamic data) {
    PlanListOutput plan = PlanListOutput.fromJson(data);
    return Container(
      height: 130.0,
      margin: const EdgeInsets.only(left: 16, right: 16),
      child: GestureDetector(
        child: Card(
            elevation: 0.2,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  width: 8,
                  height: 130,
                  decoration: BoxDecoration(
                      borderRadius:
                          const BorderRadius.only(topLeft: Radius.circular(4), bottomLeft: Radius.circular(4)),
                      color: getBgColor(plan.finishStatus)),
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    const Padding(
                      padding: EdgeInsets.only(top: 3),
                    ),
                    Container(
                      width: 280,
                      padding: const EdgeInsets.only(left: 10),
                      child: Text(plan.taskName ?? '',
                          style: const TextStyle(fontSize: 16.0, fontWeight: FontWeight.w500),
                          overflow: TextOverflow.ellipsis),
                    ),
                    const Padding(
                      padding: EdgeInsets.only(top: 5),
                    ),
                    Container(
                        padding: const EdgeInsets.only(left: 10),
                        child: Row(
                          children: <Widget>[
                            Column(
                              children: <Widget>[
                                Row(
                                  children: <Widget>[
                                    Container(
                                      width: 140,
                                      child: Text(
                                        '计划批号:' + plan.batchNo.toString(),
                                        style: const TextStyle(color: Colors.grey, fontSize: 12),
                                      ),
                                    ),
                                    Container(
                                      width: 100,
                                      child: Text(
                                        getStatus(plan.finishStatus),
                                        style: TextStyle(color: getBgColor(plan.finishStatus), fontSize: 12),
                                      ),
                                    )
                                  ],
                                ),
                                Row(
                                  children: <Widget>[
                                    Container(
                                      width: 140,
                                      child: Text('计划巡检:' + plan.taskPlanNum.toString(),
                                          style: const TextStyle(color: Colors.grey, fontSize: 12)),
                                    ),
                                    Container(
                                      width: 100,
                                      child: Text('剩余:' + (plan.taskPlanNum - plan.finshNum).toString(),
                                          style: const TextStyle(color: Colors.grey, fontSize: 12)),
                                    )
                                  ],
                                ),
                                Row(
                                  children: <Widget>[
                                    Container(
                                      width: 240,
                                      child: plan.executiveName == null
                                          ? const Text('执行人:', style: TextStyle(color: Colors.grey, fontSize: 12))
                                          : Text('执行人:' + plan.executiveName,
                                              style: const TextStyle(color: Colors.grey, fontSize: 12)),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                            Container(
                                width: 50,
                                child: Icon(
                                  Icons.keyboard_arrow_right,
                                  color: GetConfig.getColor(theme),
                                ),
                                alignment: Alignment.centerRight),
                          ],
                        )),
                    const Padding(
                      padding: EdgeInsets.only(top: 10),
                    ),
                    Container(
                      height: 25,
                      width: 312,
                      color: Colors.grey[100],
                      padding: const EdgeInsets.only(left: 10),
                      alignment: Alignment.centerLeft,
                      child: Text(
                        plan.beginTime + ' - ' + plan.endTime,
                        style: TextStyle(color: Colors.grey[500], fontSize: 12),
                      ),
                    )
                  ],
                ),
              ],
            )),
        onTap: () {
          Navigator.push(context, MaterialPageRoute(builder: (context) {
            return PlanListContent(plan.planTaskId);
          }));
        },
      ),
    );
  }

  Color getBgColor(int finishStatus) {
    if (finishStatus == 0) {
      // 未开始
      return Colors.grey;
    } else if (finishStatus == 1) {
      // 进行中
      return Colors.orange;
    } else if (finishStatus == 2) {
      // 已结束
      return Colors.red[800];
    } else if (finishStatus == 3) {
      // 已超时
      return Colors.redAccent;
    } else {
      return Colors.white;
    }
  }

  String getStatus(int finishStatus) {
    if (finishStatus == 0) {
      // 未完成
      return '未开始';
    } else if (finishStatus == 1) {
      // 进行中
      return '进行中';
    } else if (finishStatus == 2) {
      // 未开始
      return '已结束';
    } else if (finishStatus == 3) {
      // 已超时
      return '已超时';
    } else {
      return '';
    }
  }
}

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