/*
 * @Author: WuWei
 * @Date: 2020-06-29 11:03:14
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2023-02-15 16:12:17
 * @Description:
 */
import 'dart:convert';

import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:app_package/app_package.dart';
import 'package:app_package/src/api/employee.dart';
import 'package:flutter/material.dart';
import 'package:overdue_package/src/models/inner_sort_list.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:overdue_package/src/service/impl/repair_service_impl.dart';
import 'package:overdue_package/src/service/repair_service.dart';
import 'package:overdue_package/src/models/repair_list.dart';
import 'package:overdue_package/src/models/status.dart';

class OverdueRepairStore extends GetxController {
  final scrollKey = GlobalKey();

  /// tab 控制器
  TabController? tabController;

  /// NestedScrollView 控制器
  ScrollController outerController = new ScrollController();

  final OverdueRepairService _repairService = OverdueRepairServiceImpl();

  //当前员工的信息
  final authGlobalStore = GetIt.I.get<AuthGlobalStore>();
  //当前员工的信息
  EmployeesInfoModel? get userInfo => authGlobalStore.info;

  final scorllViewKeyAll = GlobalKey<WisScrollViewState>();
  final scorllViewKeyCopy = GlobalKey<WisScrollViewState>();

  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

  ///从储存中取出的当前小区 拿出来可能是空
  CommunityModel get currentCommunity => communityGlobalStore.data;

  ///缓存的小区列表
  // List<CommunityModel> get communityList =>
  //     jsonDecode(jsonEncode(communityGlobalStore.communityList)) ?? [];

  var isLast = false.obs;
  var isLoading = false.obs;
  var isEmpty = false.obs;

  Map<String, dynamic> params = {
    'pageNum': 1,
    'pageSize': 20,
  };

  /// 滚动位置
  double? scrollHeight;

  var statusList = [].obs;
  var dealPersonList = [].obs;
  var typeList = [].obs;
  var sortList = [].obs;
  var innerSortList = [].obs;

  var tabIndex = 0.obs;
  var status = StatusModel().obs;
  var innerSort = InnerSortListModel().obs;
  var businessTypeId = ''.obs;
  var checkSortIds = [].obs;
  var sortNamesString = ''.obs;
  var searchKeyWord = ''.obs;
  var selectDate = ''.obs;
  var statusCode = '0'.obs;
  var filterStatusCode = ''.obs;
  var communityIds = [].obs;
  var communityNameString = ''.obs;
  var backTrackingAtDayStart;
  var backTrackingAtDayEnd;

  var allList = [].obs;
  var copyList = [].obs;
  var communityList = [].obs;

  ///获取用户管辖的小区列表
  Future getCommunityList() async {
    if (communityList.length != 0) {
      return;
    }
    var res = await EmployeeApi.getDomainCommunitysList();
    communityList.value = jsonDecode(jsonEncode(res.data)) ?? [];
    communityList.refresh();
  }

  onInitData() async {
    onInitList();
    getCommunityList();
    getInnerSortList();
    getTypeList();
    // getStatusEnum();
    outerController.addListener(() {
      scrollHeight = outerController.offset;
    });
  }

  onChooseCommunityIds(ids) {
    communityIds.value = ids;
    communityNameString.value = '';
    var names = [];
    communityList.forEach((item) {
          if (ids.contains(item['id'])) {names.add(item['name']);};
        });
    communityNameString.value = names.join('、');
    onInitList();
  }

  onInitList() async {
    params['pageNum'] = 1;
    copyList.value = [];
    copyList.refresh();
    await getRepairList(isLoad: false);
    scrollToTop();
  }

  /// 滚动到tab位置
  scrollToTop() {
    if (scrollHeight != null && scrollHeight! > 110) {
      outerController.animateTo(106.pt,
          duration: Duration(milliseconds: 200), curve: Curves.ease);
    }
  }

  /// 滚动通知时间
  handleScrollEvent(ScrollNotification scroll) {
    if ((scroll.metrics.pixels / scroll.metrics.maxScrollExtent) > 0.8) {
      if (!isLast.value && !isLoading.value) {
        isLoading.value = true;
        onLoadMore();
      }
    }
  }

  onChooseStatus(value) async {
    status.value = value;
    onInitFreshList();
  }

  onReset() async {
    searchKeyWord.value = '';
    innerSort.value = InnerSortListModel();
    selectDate.value = '';
    status.value = StatusModel();
    communityIds.value = [];
    communityNameString.value = '';
    onInitFreshList();
  }

  onResetInner() async {
    businessTypeId.value = '';
    checkSortIds.value = [];
    onInitFreshList();
    Get.back();
  }

  /// ========================================== 提报类型 / 分类

  onChooseType(id) async {
    if (businessTypeId.value != id) {
      checkSortIds.value = [];
      checkSortIds.refresh();
    }
    businessTypeId.value = id;
    getSortList();
  }

  Future getTypeList() async {
    var res = await _repairService.getTypeList();
    typeList.value = jsonDecode(jsonEncode(res.data)) ?? [];
    typeList.refresh();
  }

  /// 分类类型
  Future getSortList() async {
    var res = await _repairService.getSortList({
      'businessTypeId': businessTypeId.value,
    });
    sortList.value = jsonDecode(jsonEncode(res.data)) ?? [];
    sortList.refresh();
  }

  /// 选择分类
  onChooseSort(id) async {
    if (checkSortIds.contains(id)) {
      checkSortIds.remove(id);
      return;
    }
    checkSortIds.add(id);
  }

  onResetSort() {
    checkSortIds.value = [];
    checkSortIds.refresh();
  }

  Future<List<InnerSortListModel>> getInnerSortList() async {
    var res = await _repairService.getInnerSortList();
    innerSortList.value = jsonDecode(jsonEncode(res.data)) ?? [];
    innerSortList.refresh();
    return res.data ?? [];
  }

  /// 选择分类
  onChooseInnerSort(value) async {
    innerSort.value = value;
    onInitFreshList();
  }

  /// ==========================================  日期

  setDate(time) async {
    selectDate.value = DateFormat('yyyy-MM-dd').format(time);
    onInitFreshList();
  }

  /// ==========================================  状态
  var statisticStatus = [
    {'name': '全部', 'code': '0', 'show': false, 'quantity': 0},
    {'name': '24小时内', 'code': '1', 'show': false, 'quantity': 24},
    {'name': '超24小时', 'code': '2', 'show': false, 'quantity': 24},
    {'name': '超48小时', 'code': '3', 'show': false, 'quantity': 48},
  ].obs;

  filterStatus(item) {
    statusCode.value = item['code'];
    var now = new DateTime.now();
    var target = now.add(new Duration(hours: -item['quantity']));
    switch (item['code']) {
      case '0':
        backTrackingAtDayStart = null;
        backTrackingAtDayEnd = null;
        break;
      case '1':
        backTrackingAtDayStart =
            DateFormat('yyyy-MM-dd HH:mm:ss').format(target);
        backTrackingAtDayEnd = null;
        break;
      default:
        backTrackingAtDayStart = null;
        backTrackingAtDayEnd = DateFormat('yyyy-MM-dd HH:mm:ss').format(target);
    }
    onInitFreshList();
  }

  changeStateValue(String code) {
    filterStatusCode.value = code;
  }

  getTimeConsuming(String createAt) {
    var useTime = '';
    if (createAt.isNotEmpty) {
      final now = new DateTime.now();
      final target = DateTime.parse(createAt);
      final duration = now.difference(target);
      if (duration.inHours > 72) {
        useTime = '${duration.inHours ~/ 24}' '天';
      } else {
        useTime = '${duration.inHours}' '小时';
      }
    }
    return createAt.isNotEmpty ? useTime : '-';
  }

  Future<List<StatusModel>> getStatusEnum() async {
    final res = await _repairService.getStatusEnum();
    final list = (res.data ?? [])
        .where((e) => ['waitAccept', 'hangUp', 'accept'].contains(e.code))
        .toList();
    return list;
  }

  onSearchName(v) async {
    searchKeyWord.value = v;
    onInitFreshList();
  }

  onLoadMore() async {
    switch (tabIndex.value) {
      case 0:
        await getReportList(isLoad: true);
        break;
      case 1:
        await getRepairList(isLoad: true);
        break;
    }
  }

  onSetTabIndex(index) {
    // FocusScope.of(context).requestFocus(FocusNode());
    tabIndex.value = index;
    // 避免切换tab时，已有数据情况下，重复发起请求
    if (copyList.isEmpty) {
      onInitFreshList();
    }
  }

  bool get isFilterStatus =>
      businessTypeId.value.isNotEmpty ||
      checkSortIds.length > 0 ||
      communityIds.length > 0;

  submit() async {
    statusCode.value =
        (filterStatusCode.value.isNotEmpty ? null : statusCode.value)!;
    onInitFreshList();
    Get.back();
  }

  onInitFreshList() async {
    isLast.value = false;
    isEmpty.value = false;
    isLoading.value = false;
    scrollToTop();
    switch (tabIndex.value) {
      case 1:
        params['pageNum'] = 1;
        copyList.value = [];
        copyList.refresh();
        await getRepairList(isLoad: true);
        break;
      default:
        break;
    }
  }

  onSearch(String word) {
    // FocusScope.of(context).requestFocus(FocusNode());
    searchKeyWord.value = word;
    onInitFreshList();
  }

  bool isMoblieMatch(value) {
    RegExp regExp = new RegExp(r'^[0-9]+$');
    return regExp.hasMatch(value);
  }

  /// 全部报修列表
  Future getReportList({bool isLoad = true}) async {
    if (!isLoad) params['pageNum'] = 1;
    if (isMoblieMatch(searchKeyWord.value)) {
      params['mobile'] = searchKeyWord.value;
      params['name'] = '';
    } else {
      params['mobile'] = '';
      params['name'] = searchKeyWord.value;
    }
    var res = await _repairService.getRepairList({
      'statuss': status.value.code ?? 'waitAccept,hangUp,accept',
      'backTrackingAtDayStart': backTrackingAtDayStart ?? null,
      'backTrackingAtDayEnd': backTrackingAtDayEnd ?? null,
      'communityIdList':
          communityIds.length > 0 ? communityIds.join(',') : null,
      'businessTypeId':
          businessTypeId.value.isNotEmpty ? businessTypeId.value : null,
      'sortIds': checkSortIds.length > 0 ? checkSortIds.join(',') : null,
      'internalSortId': innerSort.value.id ?? null,
      'startDate': selectDate.value.isNotEmpty ? selectDate.value : null,
      'endDate': selectDate.value.isNotEmpty ? selectDate.value : null,
      ...params,
    });

    final _data = res.data;
    final _list = _data?.list ?? [];
    isLoading.value = false;
    if ((_data?.total ?? 0) == 0) {
      isEmpty.value = true;
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      isLast.value = true;
    } else {
      params['pageNum']++;
    }
    isLoad ? allList.addAll(_list) : allList.value = _list;
    allList.refresh();
  }

  /// 已解决报修列表
  Future getRepairList({bool isLoad = true}) async {
    if (!isLoad) params['pageNum'] = 1;
    if (isMoblieMatch(searchKeyWord.value)) {
      params['mobile'] = searchKeyWord.value;
      params['nameFuzzy'] = '';
    } else {
      params['mobile'] = '';
      params['nameFuzzy'] = searchKeyWord.value;
    }
    var res = await _repairService.getRepairList({
      'statuss': status.value.code ?? 'waitAccept,hangUp,accept',
      'backTrackingAtDayStart': backTrackingAtDayStart ?? null,
      'backTrackingAtDayEnd': backTrackingAtDayEnd ?? null,
      'communityIdList':
          communityIds.length > 0 ? communityIds.join(',') : null,
      'businessTypeId':
          businessTypeId.value.isNotEmpty ? businessTypeId.value : null,
      'sortIds': checkSortIds.length > 0 ? checkSortIds.join(',') : null,
      'internalSortId': innerSort.value.id ?? null,
      'startDate': selectDate.value.isNotEmpty ? selectDate.value : null,
      'endDate': selectDate.value.isNotEmpty ? selectDate.value : null,
      ...params,
    });

    final _data = res.data;
    final _list = _data?.list ?? [];
    isLoading.value = false;
    if ((_data?.total ?? 0) == 0) {
      isEmpty.value = true;
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      isLast.value = true;
    } else {
      params['pageNum']++;
    }
    isLoad ? copyList.addAll(_list) : copyList.value = _list;
    copyList.refresh();
  }

  /// 跳转报事详情
  route2RepairDetail(RepairListModel item) async {
    await Get.toNamed('repair/detail',
        arguments: {'id': item.id, 'type': 'repair'});
    final bool refresh = WisStorageUtil.get(key: 'report_list_refresh');
    if (refresh == true) {
      WisStorageUtil.set(key: 'report_list_refresh', data: false);
      onInitFreshList();
    }
  }

  toFilterPage() async {
    await Get.toNamed('overdue/filter/repair');
  }

  back() {
    Get.back();
  }
}
