/*
 * @Author: WuWei
 * @Date: 2020-06-29 11:03:14
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2023-04-12 16:35:33
 * @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:app_package/src/api/employee.dart';
import 'package:app_package/src/models/community_picker.dart';
import 'package:report_package/src/models/inner_sort_list.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import '../service/impl/report_service_impl.dart';
import '../service/report_service.dart';
import '../models/report_list_model.dart';
import '../models/status.dart';

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

  /// tab 控制器
  TabController? tabController;

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

  final ReportService _reportService = ReportServiceImpl();

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

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

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

  /// 滚动位置
  double? scrollHeight;
  var scoreList = [5, 4, 3, 2, 1].obs;
  var statusList = [].obs;
  var dealPersonList = [].obs;
  var typeList = [].obs;
  var sortList = [].obs;
  var innerSortList = [].obs;
  var checkScoreIds = 0.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 = 'process'.obs;
  var filterStatusCode = 'process'.obs;
  var community = CommunityPickerModel().obs;
  var communityId = ''.obs;
  var communityIName = ''.obs;

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

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

  ///获取用户管辖的小区列表

  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!;
    }
  }

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

  onInitData() async {
    communityId.value = currentCommunity!.id!;
    getAsyncCommunityList(isInit: true);
    onInitList();
    // getInnerSortList();
    getTypeList();
    getStatusEnum();
    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:
        params['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 _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();
  }

  /// ==========================================  状态
  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 getReportStatistic(params) async {
    final res = await _reportService.getReportStatistic(params);
    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 _reportService.getStatusEnum();
    statusList.value = res.data ?? [];
    statusList.refresh();
  }

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

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

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

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

  submit() async {
    statusCode.value = filterStatusCode.value;
    // 需要小区变动才去请求
    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 getRepairAllList(isLoad: true);
        break;
      case 1:
        params['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;
    }
  }

  bool isMoblieMatch(value) {
    Pattern pattern = r'^[0-9]+$';
    RegExp regExp = new RegExp(pattern as String);
    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,
    };
    if (isMoblieMatch(searchKeyWord.value)) {
      paramsData['mobile'] = searchKeyWord.value;
      paramsData['nameFuzzy'] = '';
    } else {
      paramsData['mobile'] = '';
      paramsData['nameFuzzy'] = searchKeyWord.value;
    }
    // 同步更新统计
    getReportStatistic(paramsData);
    var res = await _reportService.getReportList({
      ...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) params['pageNum'] = 1;
    var paramsData = {
      'communityId': communityId.value.isNotEmpty ? communityId.value : null,
      'mailTo': userInfo!.id,
      '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,
    };
    if (isMoblieMatch(searchKeyWord.value)) {
      paramsData['mobile'] = searchKeyWord.value;
      paramsData['nameFuzzy'] = '';
    } else {
      paramsData['mobile'] = '';
      paramsData['nameFuzzy'] = searchKeyWord.value;
    }
    // 同步更新统计
    getReportStatistic(paramsData);
    var res = await _reportService.getReportList({
      ...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 ? copyList.addAll(_list) : copyList.value = _list;
    copyList.refresh();
  }

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

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