import 'dart:async';

import 'package:amap_location_flutter_plugin/amap_location_flutter_plugin.dart';
import 'package:amap_location_flutter_plugin/amap_location_option.dart';
import 'package:flutter/material.dart';
import 'package:liftmanager/widgets/app_search_bar.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/mvp/base_page_state.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/bbs/model/mix_model.dart';
import 'package:liftmanager/widgets/state_layout.dart';
import 'package:liftmanager/widgets/my_refresh_list.dart';
import 'package:liftmanager/utils/time_format.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:provider/provider.dart';
import 'package:liftmanager/internal/search/search_router.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:liftmanager/internal/wode/model/table_dicts_model.dart';
import 'package:permission_handler/permission_handler.dart';


class PositionList extends StatefulWidget {
  @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();

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

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

    _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(() {});
        _locationResult.forEach((key, value) {                
          print(111);
          print('key:$key :');
          print('value:$value :');
        });
      });
    });

    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()) {
//      final location = await AmapLocation.fetchLocation();
//      provinceName = location.province;
//      cityName = location.city;
//      categoryList[0]['label'] = location.city;
//      _onRefresh();
//      setState(() {});
//    }else {
//      _onRefresh();
//    }
    if (await requestPermission()) {
      if (null != _locationPlugin) {
        ///开始定位之前设置定位参数
        _setLocationOption();
        _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;
      ///设置Android端的定位模式<br>
      ///可选值：<br>
      ///<li>[AMapLocationMode.Battery_Saving]</li>
      ///<li>[AMapLocationMode.Device_Sensors]</li>
      ///<li>[AMapLocationMode.Hight_Accuracy]</li>
      locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

      ///设置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.NearestTenMeters;
      ///设置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;
      provinceName = tempResult.provinceName;
      cityName = tempResult.cityName;
      categoryList[0]['label'] = addressResult.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;
    double height = MediaQuery.of(context).size.height;
    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: 0.5, color: Colours.line),
                        ),
                      ),
                      child: ListView(
                        scrollDirection: Axis.horizontal,
                        children: <Widget>[
                          SizedBox(width: ScreenUtil().setWidth(15)),
                          TopTitle(
                            categoryList: categoryList,
                            fun: changTypeClass,
                          )
                        ],
                      )),
                  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,
                          itemBuilder: (_, index) {
                            return GestureDetector(
                              child: Container(
                                padding: EdgeInsets.only(
                                    left: ScreenUtil().setWidth(15),
                                    right: ScreenUtil().setWidth(15),
                                    top: ScreenUtil().setHeight(10),
                                    bottom: ScreenUtil().setHeight(10)),
                                decoration: BoxDecoration(
                                  border: Border(
                                    bottom: BorderSide(
                                        width: 0.5, color: Colours.line),
                                  ),
                                ),
                                child: Column(
                                    // crossAxisAlignment: CrossAxisAlignment.start,

                                    children: <Widget>[
                                      Container(
                                        padding: EdgeInsets.only(
                                            bottom: ScreenUtil().setHeight(5)),
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          children: <Widget>[
                                            Container(
                                              width: width*0.4,
                                              child: Text(
                                              provider.list[index].job ?? '',
                                              textAlign: TextAlign.left,
                                              style: TextStyle(
                                                fontSize:
                                                    ScreenUtil().setSp(17),
                                              ),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                            ),
                                            Container(
                                              width:width*0.4,
                                              child:Text(
                                              // 'jiage',
                                              "￥" +
                                                  provider
                                                      .list[index].lowerSalary
                                                      .toString() +
                                                  "-" +
                                                  provider
                                                      .list[index].upperSalary
                                                      .toString(),
                                              textAlign: TextAlign.right,
                                              style: TextStyle(
                                                fontSize:
                                                    ScreenUtil().setSp(17),
                                                color: Color(0xffff0000),
                                              ),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                            )
                                          ],
                                        ),
                                      ),
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: <Widget>[
                                          Container(
                                            width: width*0.5,
                                            child: Text(
                                              provider.list[index].company
                                                      .name ??
                                                  '',
                                              textAlign: TextAlign.left,
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                fontSize:
                                                    ScreenUtil().setSp(14),
                                                color: Color(0xff999999),
                                              ),
                                            ),
                                          ),
                                          provider.list[index]
                                                          .provinceName !=
                                                      null?Container(
                                            width: width*0.35,
                                            child: Text(
                                              (provider.list[index]
                                                          .provinceName !=
                                                      null
                                                  ? provider
                                                      .list[index].provinceName
                                                  : '') +
                                                      "-" +
                                                      (provider.list[index]
                                                          .cityName !=
                                                      null
                                                  ? provider
                                                      .list[index].cityName
                                                  : ''),
                                              textAlign: TextAlign.right,
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                fontSize:
                                                    ScreenUtil().setSp(14),
                                                color: Color(0xff999999),
                                              ),
                                            ),
                                          ):Container(child:null),
                                        ],
                                      ),
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: <Widget>[
                                          Container(
                                            width: width * 0.65,
                                            child: Text(
                                              provider.list[index].info ?? '',
                                              textAlign: TextAlign.left,
                                              style: TextStyle(
                                                fontSize:
                                                    ScreenUtil().setSp(14),
                                                color: Color(0xff999999),
                                              ),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                          Text(
                                            DateUtils.instance.getFormartData(
                                                timeSamp: provider
                                                    .list[index].createTime,
                                                format: "yyyy-MM-dd"),
                                            textAlign: TextAlign.left,
                                            style: TextStyle(
                                              fontSize: ScreenUtil().setSp(14),
                                              color: Color(0xff999999),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ]),
                              ),
                              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: ScreenUtil().setSp(16)),
                    textAlign: TextAlign.start,
                  ),
                  Container(
                    padding: EdgeInsets.only(top: 3),
                    child: Icon(
                      Icons.keyboard_arrow_down,
                      size: 26.0,
                    ),
                  )
                ],
              ),
              SizedBox(width: ScreenUtil().setWidth(15)),
            ]),
          ),
        ):Container(child:null);
      }).toList();

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