// ignore_for_file: unnecessary_set_literal

/*
 * @Author: WuWei
 * @Date: 2020-06-29 11:03:14
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2023-02-15 16:03:43
 * @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:service_center_package/src/models/inner_sort_list.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:service_center_package/src/service/impl/report_service_impl.dart';
import 'package:service_center_package/src/service/report_service.dart';
import 'package:service_center_package/src/models/report_list_model.dart';
import 'package:service_center_package/src/models/status.dart';

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

  /// tab 控制器
  late TabController tabController;

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

  final OverdueReportService _reportService = OverdueReportServiceImpl();

  //当前员工的信息
  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>();

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

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

  /// 滚动位置
  double scrollHeight = 0;

  var statusList = [].obs;
  var dealPersonList = [].obs;

  var tabIndex = 0.obs;
  var allList = <ReportListModel>[].obs;
  var copyList = <ReportListModel>[].obs;
  var communityList = [].obs;

  var typeList = [].obs;
  var sortList = [].obs;
  var innerSortList = [].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 = ''.obs;
  var communityIds = [].obs;
  var communityNameString = ''.obs;
  var backTrackingAtDayStart;
  var backTrackingAtDayEnd;

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

  onInitData() async {
    onInitList();
    getStatusEnum();
    getCommunityList();
    getInnerSortList();
    getTypeList();
    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;
    allList.value = [];
    // allList.refresh();
    await getReportList(isLoad: false);
    scrollToTop();
  }

  /// 滚动到tab位置
  scrollToTop() {
    if (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();
      }
    }
  }

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

  onResetInner() async {
    businessTypeId.value = '';
    checkSortIds.value = [];
    communityIds.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 _reportService.getTypeList();
    typeList.value = jsonDecode(jsonEncode(res.data)) ?? [];
    typeList.refresh();
  }

  /// 分类类型
  Future getSortList() async {
    var res = await _reportService.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 _reportService.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();
  }

  /// ==========================================  状态
  filterStatus(String code) {
    statusCode.value = code;
    onInitFreshList();
  }

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

  Future getStatusEnum() async {
    final res = await _reportService.getStatusEnum();
    final item =
        StatusModel.fromJson({'code': '', 'name': '全部', 'disabled': false});
    final list =
        (res.data ?? []).where((e) => !['process'].contains(e.code)).toList();
    list.insert(0, item);
    statusList.value = list;
  }

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

  onLoadMore() async {
    await getReportList(isLoad: true);
  }

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

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

  submit() async {
    onInitFreshList();
    Get.back();
  }

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

  onSearch(String word) {
    // FocusScope.of(context).requestFocus(FocusNode());
    switch (tabIndex.value) {
      case 0:
        searchKeyWord.value = word;
        onInitFreshList();
        break;
      default:
        break;
    }
  }

  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['nameFuzzy'] = '';
    } else {
      params['mobile'] = '';
      params['nameFuzzy'] = searchKeyWord.value;
    }
    var res = await _reportService.getReportList({
      'status': statusCode.value,
      '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();
  }

  /// 跳转报事详情
  route2RepairDetail(ReportListModel item) async {
    await Get.toNamed('report/detail',
        arguments: {'id': item.id, 'type': 'report'});
    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('service_center/filter/report');
  }

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