/*
 * @Author: WuWei
 * @Date: 2020-06-29 11:03:14
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2023-03-07 15:13:41
 * @Description:
 */

import 'dart:convert';

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

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

  /// tab 控制器
  TabController? tabController;

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

  final RepairService _repairService = RepairServiceImpl();

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

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

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

  /// 滚动位置
  double? scrollHeight;

  var statusList = [].obs;
  var dealPersonList = [].obs;
  var typeList = [].obs;
  var sortList = [].obs;
  var innerSortList = [].obs;
  var scoreList = [5, 4, 3, 2, 1].obs;

  var tabIndex = 0.obs;
  var status = StatusModel().obs;
  var innerSort = InnerSortListModel().obs;
  var businessTypeId = ''.obs;
  var checkSortIds = [].obs;
  var checkScoreIds = 0.obs;
  var sortNamesString = ''.obs;
  var searchKeyWord = ''.obs;
  var selectDate = ''.obs;
  var statusCode = 'process'.obs;
  var filterStatusCode = 'process'.obs;
  var community = CommunityPickerModel().obs;
  var communityId = ''.obs;
  var communityIName = ''.obs;

  var allList = <RepairListModel>[].obs;
  var copyList = <RepairListModel>[].obs;
  var communityList = <CommunityPickerModel>[].obs;

  ///去选择小区
  toCommunityPick() async {
    await Get.toNamed('community');
    onInitData();
  }

  init() async {
    if (currentCommunity!.id != null) {
      await onInitData();
    } else {
      await toCommunityPick();
    }
  }

  ///获取用户管辖的小区列表
  Future<List<CommunityPickerModel>> getCommunityList() async => communityList;

  getAsyncCommunityList({isInit: false}) async {
    if (communityList.length != 0) {
      return;
    }
    var res = await EmployeeApi.getDomainCommunityListToPicker();
    communityList.value = res.data ?? [];

    communityList.refresh();
    if (isInit) {
      communityId.value = currentCommunity!.id!;
      final match =
          (res.data ?? []).firstWhere((e) => e.id == communityId.value);
      community.value = match;
      communityIName.value = match.name!;
    }
  }

  onInitData() async {
    communityId.value = currentCommunity!.id!;
    getAsyncCommunityList(isInit: true);
    onInitList();
    getStatusEnum();
    getTypeList();
    outerController.addListener(() {
      scrollHeight = outerController.offset;
    });
  }

  ///筛选评分
  onChooseScore(score) async {
    checkScoreIds.value = score;
  }

  onChooseCommunity(CommunityPickerModel res) {
    community.value = res;
    communityId.value = res.id!;
    communityIName.value = res.name!;
    onInitList();
  }

  onInitList() async {
    switch (tabIndex.value) {
      case 0:
        params['pageNum'] = 1;
        allList.value = [];
        allList.refresh();
        await getRepairAllList(isLoad: false);
        scrollToTop();
        break;
      case 1:
        paramsCopy['pageNum'] = 1;
        copyList.value = [];
        copyList.refresh();
        await getRepairCopyList(isLoad: false);
        scrollToTop();
        break;
    }
  }

  /// 滚动到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 = '';
    // resetCommunity();
    onInitFreshList();
  }

  resetCommunity() {
    community.value = CommunityPickerModel();
    communityId.value = '';
    communityIName.value = '';
  }

  onResetInner() async {
    statusCode.value = '';
    filterStatusCode.value = '';
    businessTypeId.value = '';
    checkScoreIds.value = 0;
    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': 'process', 'show': true, 'quantity': 0},
    {'name': '已挂起', 'code': 'hangUp', 'show': true, 'quantity': 0},
    {'name': '已解决', 'code': 'solve', 'show': false, 'quantity': 0},
  ].obs;

  Future getRepairStatistic(params) async {
    final res = await _repairService.getRepairStatistic(params);
    print(res.data);
    final _data = res.data;
    statisticStatus.forEach((item) {
          if (item['code'] == 'process')
            {item['quantity'] = _data?.process ?? 0;};
          if (item['code'] == 'hangUp') {item['quantity'] = _data?.hangUp ?? 0;};
        });
    statisticStatus.refresh();
  }

  filterStatus(String code) {
    statusCode.value = code;
    filterStatusCode.value = code;
    onInitFreshList();
  }

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

  Future getStatusEnum() async {
    if (statusList.length > 1) return;
    final res = await _repairService.getStatusEnum();
    statusList.value = res.data ?? [];
    statusList.refresh();
  }

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

  bool get isFilterStatus =>
      statusCode.value != '' ||
      businessTypeId.value.isNotEmpty ||
      checkSortIds.length > 0;

  /// ==========================================  列表
  submit() async {
    statusCode.value = filterStatusCode.value;
    onInitFreshList();
    Get.back();
  }

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

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

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

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

  onSetTabIndex(index) {
    // FocusScope.of(context).requestFocus(FocusNode());
    tabIndex.value = index;
    onInitFreshList();
  }

  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 getRepairAllList(isLoad: true);
        break;
      case 1:
        paramsCopy['pageNum'] = 1;
        copyList.value = [];
        copyList.refresh();
        await getRepairCopyList(isLoad: true);
        break;
      default:
        break;
    }
  }

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

  late RepairDetailModel repairDetail;

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

  /// 全部报修列表
  Future getRepairAllList({bool isLoad = true}) async {
    if (!isLoad) params['pageNum'] = 1;
    var paramsData = {
      'communityId': communityId.value.isNotEmpty ? communityId.value : null,
      'status': statusCode.value,
      'businessTypeId':
          businessTypeId.value.isNotEmpty ? businessTypeId.value : null,
      'sortIds': checkSortIds.length > 0 ? checkSortIds.join(',') : null,
      'internalSortId': innerSort.value.id,
      'startDate': selectDate.value.isNotEmpty ? selectDate.value : null,
      'endDate': selectDate.value.isNotEmpty ? selectDate.value : null,
      'evaluationScoreFilter':
          checkScoreIds.value == 0 ? null : checkScoreIds.value,
    };
    print(paramsData);
    if (isMoblieMatch(searchKeyWord.value)) {
      paramsData['mobile'] = searchKeyWord.value;
      paramsData['nameFuzzy'] = '';
    } else {
      paramsData['mobile'] = '';
      paramsData['nameFuzzy'] = searchKeyWord.value;
    }
    //同步更新统计
    await getRepairStatistic(paramsData);
    var res = await _repairService.getRepairList({
      ...paramsData,
      ...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 getRepairCopyList({bool isLoad = true}) async {
    if (!isLoad) paramsCopy['pageNum'] = 1;
    var paramsData = {
      'communityId': communityId.value.isNotEmpty ? communityId.value : null,
      'status': statusCode.value,
      'businessTypeId':
          businessTypeId.value.isNotEmpty ? businessTypeId.value : null,
      'sortIds': checkSortIds.length > 0 ? checkSortIds.join(',') : null,
      'internalSortId': innerSort.value.id,
      'startDate': selectDate.value.isNotEmpty ? selectDate.value : null,
      'endDate': selectDate.value.isNotEmpty ? selectDate.value : null,
      'evaluationScoreFilter':
          checkScoreIds.value == 0 ? null : checkScoreIds.value,
    };
    print(paramsData);
    if (isMoblieMatch(searchKeyWord.value)) {
      paramsData['mobile'] = searchKeyWord.value;
      paramsData['nameFuzzy'] = '';
    } else {
      paramsData['mobile'] = '';
      paramsData['nameFuzzy'] = searchKeyWord.value;
    }
    //同步更新统计
    await getRepairStatistic(paramsData);
    var res = await _repairService.getRepairList({
      ...paramsData,
      ...paramsCopy,
    });

    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 {
      paramsCopy['pageNum']++;
    }
    isLoad ? copyList.addAll(_list) : copyList.value = _list;
    copyList.refresh();
  }

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

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