import 'dart:async';
import 'dart:io';

import 'package:amap_location_flutter_plugin/amap_location_flutter_plugin.dart';
import 'package:amap_location_flutter_plugin/amap_location_option.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'package:liftmanager/internal/bbs/model/mix_model.dart';
import 'package:liftmanager/internal/bbs/presenter/position_list_presenter.dart';
import 'package:liftmanager/internal/search/presenter/base_list_provider.dart';
import 'package:liftmanager/internal/wode/model/table_dicts_model.dart';
import 'package:liftmanager/mvp/base_page_state.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_search_bar.dart';
import 'package:liftmanager/widgets/bbs_content.dart';
import 'package:liftmanager/widgets/my_refresh_list.dart';
import 'package:liftmanager/widgets/state_layout.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

class PositionList extends StatefulWidget {
  String city;
  String provinceName;
  PositionList({this.city, this.provinceName});
  @override
  PositionListState createState() => PositionListState();
}

class PositionListState
    extends BasePageState<PositionList, PositionListPresenterSeconds> {
  // Map<String, Object> _locationResult;
  // StreamSubscription<Map<String, Object>> _locationListener;
  // AmapLocationFlutterPlugin _locationPlugin = new AmapLocationFlutterPlugin();

  BaseListProvider<Records> provider = BaseListProvider<Records>();
  int _page = 1;

  List<dynamic> categoryList = [
    {"title": "地址", "label": "地点"},
    {"title": "所属职位", "label": "所属职位"},
    {"title": "薪资范围", "label": "薪资范围"}
  ];

  ScrollController _scrollController = new ScrollController();

  @override
  void initState() {
    provider.setStateTypeNotNotify(StateType.loading);
    super.initState();

    cityName = widget.city;
    provinceName = widget.provinceName;
    categoryList[0]['label'] = widget.city;
    _onRefresh();

    ///移除定位监听
    // if (null != _locationListener) {
    //   _locationListener.cancel();
    // }

    // ///销毁定位
    // if (null != _locationPlugin) {
    //   _locationPlugin.destroy();
    // }

//     _locationListener = _locationPlugin
//         .onLocationChanged()
//         .listen((Map<String, Object> result) {
//       setState(() {
//         _locationPlugin.stopLocation();
//         _locationResult = result;
//         print(_locationResult["city"]);
//         print(_locationResult["province"]);
// //        address latitude longitude
//         provinceName = _locationResult["province"];
//         categoryList[0]['label'] = _locationResult["city"];
//         _onRefresh();
//         setState(() {});
//       });
//     });
//     getInitLocation();
    getJobClass();
  }

  // // 获取定位权限
  // Future<bool> requestPermission() async {
  //   final permissions = await PermissionHandler()
  //       .requestPermissions([PermissionGroup.location]);
  //   if (permissions[PermissionGroup.location] == PermissionStatus.granted) {
  //     return true;
  //   } else {
  //     toasts('需要定位权限!');
  //     _onRefresh();
  //     setState(() {});
  //     return false;
  //   }
  // }

  // getInitLocation() async {
  //   if (await requestPermission()) {
  //     if (null != _locationPlugin) {
  //       ///开始定位之前设置定位参数
  //       _setLocationOption();
  //       // _locationPlugin.getSystemAccuracyAuthorization();
  //       _locationPlugin.startLocation();
  //     }
  //   }
  // }

  // void _setLocationOption() {
  //   if (null != _locationPlugin) {
  //     AMapLocationOption locationOption = new AMapLocationOption();

  //     ///是否单次定位
  //     locationOption.onceLocation = true;

  //     ///是否需要返回逆地理信息
  //     locationOption.needAddress = true;

  //     ///逆地理信息的语言类型
  //     locationOption.geoLanguage = GeoLanguage.DEFAULT;

  //     ///设置Android端连续定位的定位间隔
  //     locationOption.locationInterval = 20000;

  //     locationOption.desiredLocationAccuracyAuthorizationMode =
  //         AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;

  //     ///设置Android端的定位模式<br>
  //     ///可选值：<br>
  //     ///<li>[AMapLocationMode.Battery_Saving]</li>
  //     ///<li>[AMapLocationMode.Device_Sensors]</li>
  //     ///<li>[AMapLocationMode.Hight_Accuracy]</li>
  //     locationOption.locationMode = AMapLocationMode.Hight_Accuracy;
  //     // locationOption.requestAccuracyAuthorization();

  //     ///设置iOS端的定位最小更新距离<br>
  //     locationOption.distanceFilter = -1;

  //     ///设置iOS端期望的定位精度
  //     /// 可选值：<br>
  //     /// <li>[DesiredAccuracy.Best] 最高精度</li>
  //     /// <li>[DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度 </li>
  //     /// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
  //     /// <li>[DesiredAccuracy.Kilometer] 1000米</li>
  //     /// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
  //     locationOption.desiredAccuracy = DesiredAccuracy.Best;

  //     ///设置iOS端是否允许系统暂停定位
  //     locationOption.pausesLocationUpdatesAutomatically = false;

  //     ///将定位参数设置给定位插件
  //     _locationPlugin.setLocationOption(locationOption);
  //   }
  // }

  @override
  void dispose() {
    _scrollController.dispose();

    // ///移除定位监听
    // if (null != _locationListener) {
    //   _locationListener.cancel();
    // }

    // ///销毁定位
    // if (null != _locationPlugin) {
    //   _locationPlugin.destroy();
    // }
    super.dispose();
  }

  List<TableDictsModel> jobClass = [];

  // 获取招聘职位分类
  Future getJobClass() async {
    NewApiService().queryConstant('recruitment_info', 'job', onSuccess: (res) {
      jobClass = res;
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Result addressResult = new Result();
  String provinceName;
  String cityName;

  // 选择地址
  void _clickEventFunc() async {
    Result tempResult = await CityPickers.showCityPicker(
      theme: ThemeData.light(),
      context: context,
      showType: ShowType.pc,
      cancelWidget: GestureDetector(
        onTap: () {
          provinceName = null;
          cityName = null;
          categoryList[0]['label'] = "不限地区";
          Navigator.pop(context);
          _onRefresh();
          setState(() {});
        },
        child: Text(
          "不限地区",
          style: TextStyle(
            color: Color(0xffff0000),
          ),
        ),
      ),
      locationCode: addressResult != null
          ? addressResult.areaId ??
              addressResult.cityId ??
              addressResult.provinceId
          : null, // 初始化地址信息
    );
    if (tempResult != null) {
      print(tempResult);
      addressResult = tempResult;

      if (tempResult.cityName == "市辖区") {
        cityName = "重庆城区";
      } else {
        cityName = tempResult.cityName;
      }
      provinceName = tempResult.provinceName;
      if (cityName == "县") {
        categoryList[0]['label'] = "重庆市-县";
      } else {
        categoryList[0]['label'] = cityName;
      }

      _onRefresh();

      setState(() {});
    }
  }

  changTypeClass(item, index) {
    if (index == 0) {
      // 选择地址
      _clickEventFunc();
    } else if (index == 1) {
      // 所属职位
      showPositionModal(context);
    } else if (index == 2) {
      // 薪资范围
      showSalaryModal(context);
    }

    setState(() {});
  }

  // 所属职位
  List jobClassData = [];
  String jobSelected;

  showPositionModal(BuildContext context) {
    jobClassData.clear();
    jobClassData.add("不限");
    for (var i = 0; i < jobClass.length; i++) {
      jobClassData.add(jobClass[i].value);
    }
    new Picker(
      // selecteds:[0],
      cancelText: "取消",
      confirmText: "确认",
      adapter: PickerDataAdapter<String>(
        pickerdata: jobClassData,
      ),
      changeToFirst: true,
      hideHeader: false,
      onConfirm: (Picker picker, List value) {
        if (value[0] == 0) {
          jobSelected = null;
        } else {
          jobSelected = picker.getSelectedValues()[0];
          print(jobSelected);
        }
        categoryList[1]['label'] = picker.getSelectedValues()[0];

        _onRefresh();
        setState(() {});
      },
    ).showModal(this.context);
  }

  List salaryRange = [
    {
      "title": "不限",
      "min": null,
      "max": null,
    },
    {
      "title": "3K以下",
      "min": 0,
      "max": 3000,
    },
    {
      "title": "3-5k",
      "min": 3000,
      "max": 5000,
    },
    {
      "title": "5-10k",
      "min": 5000,
      "max": 10000,
    },
    {
      "title": "10-20k",
      "min": 10000,
      "max": 20000,
    },
    {
      "title": "20-50k",
      "min": 20000,
      "max": 50000,
    },
    {
      "title": "50K以上",
      "min": 50000,
      "max": null,
    }
  ];

  // 薪资范围
  List moneyList;
  List salaryRangeData = [];
  int minSalary;
  int maxSalary;

  showSalaryModal(BuildContext context) {
    salaryRangeData.clear();
    for (var i = 0; i < salaryRange.length; i++) {
      salaryRangeData.add(salaryRange[i]["title"]);
    }
    new Picker(
      selectedTextStyle: TextStyle(color: Colors.black),
      selecteds: moneyList,
      cancelText: "取消",
      confirmText: "确认",
      adapter: PickerDataAdapter<String>(
        pickerdata: salaryRangeData,
      ),
      changeToFirst: true,
      hideHeader: false,
      onConfirm: (Picker picker, List value) {
        print(12389);
        print(value);
        moneyList = value;
        int index = value[0];
        minSalary = salaryRange[index]['min'];
        maxSalary = salaryRange[index]['max'];
        categoryList[2]['label'] = salaryRange[index]["title"];

        _onRefresh();
        setState(() {});
      },
    ).showModal(this.context);
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    return ChangeNotifierProvider<BaseListProvider<Records>>(
      create: (_) => provider,
      child: Scaffold(
        appBar: SearchAppBar2(
          onPressed: (text) {
            jobSelected = text;
            _onRefresh();
          },
        ),
        body: Container(
          child: Stack(
            children: <Widget>[
              Column(
                children: <Widget>[
                  Container(
                      width: width,
                      height: ScreenUtil().setWidth(50),
                      decoration: BoxDecoration(
                        border: Border(
                          bottom: BorderSide(
                            width: 5,
                            color: Color(0xffF9F9F9),
                          ),
                        ),
                      ),
                      child: TopTitle(
                        categoryList: categoryList,
                        fun: changTypeClass,
                      )),
                  SizedBox(
                    height: 10,
                  ),
                  Expanded(
                      flex: 1,
                      child: Consumer<BaseListProvider<Records>>(
                          builder: (_, provider, __) {
                        return MyListView(
                          key: Key('position_list'),
                          itemCount: provider.list.length,
                          stateType: provider.stateType,
                          onRefresh: _onRefresh,
                          loadMore: _loadMore,
                          hasMore: provider.hasMore,
                          showSeparator: false,
                          itemBuilder: (_, index) {
                            return GestureDetector(
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 10),
                                child: PositionCell(
                                  provider.list[index],
                                ),
                              ),
                              onTap: () {
                                NavigatorUtils.push(context,
                                    "${BbsRouter.positionDetail}?id=${provider.list[index].id.toString()}");
                              },
                            );
                          },
                        );
                      }))
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future _onRefresh() async {
    _page = 1;
    await presenter.getPositionList(
      _page,
      provinceName: provinceName,
      cityName: cityName,
      minSalary: minSalary,
      maxSalary: maxSalary,
      job: jobSelected,
    );
  }

  Future _loadMore() async {
    _page++;
    await presenter.getPositionList(
      _page,
      provinceName: provinceName,
      cityName: cityName,
      minSalary: minSalary,
      maxSalary: maxSalary,
      job: jobSelected,
    );
  }

  @override
  PositionListPresenterSeconds createPresenter() {
    return PositionListPresenterSeconds();
  }
}

class TopTitle extends StatelessWidget {
  TopTitle({Key key, this.categoryList, this.fun}) : super(key: key);
  List<dynamic> categoryList;
  Function fun;

  List<Widget> listWidget(context) => categoryList.asMap().keys.map((index) {
        return index != 1
            ? GestureDetector(
                onTap: () {
                  fun(categoryList[index], index);
                },
                child: Container(
                  child: Row(children: <Widget>[
                    Row(
                      children: <Widget>[
                        Text(
                          categoryList[index]['label'] ?? '',
                          style: TextStyle(
                            fontSize: 14,
                            color: Color(0xff333333),
                          ),
                          textAlign: TextAlign.start,
                        ),
                        Container(
                          padding: EdgeInsets.only(top: 3),
                          child: Icon(
                            Icons.keyboard_arrow_down,
                            size: 20.0,
                          ),
                        )
                      ],
                    ),
                    SizedBox(width: ScreenUtil().setWidth(15)),
                  ]),
                ),
              )
            : Container(child: null);
      }).toList();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: listWidget(context),
      ),
    );
  }
}
