/*
 * @Author: XianKaiQun
 * @Date: 2020-09-11 09:42:18
 * @LastEditors: wuwei
 * @LastEditTime: 2024-03-20 11:38:43
 * @Description: 
 */
import 'package:get/get.dart';
import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:intl/intl.dart' show DateFormat;
import 'package:api_package/meterReading_house.get.dart' as houseInterface;
import 'package:api_package/meterReading_common.get.dart' as commonInterface;
import 'package:api_package/meterReading_house_count.get.dart'
    as houseStatInterface;
import 'package:api_package/meterReading_common_statistics.get.dart'
    as commonStatInterface;
import 'package:api_package/metercommons_transcribes.post.dart'
    as commonRecordInterface;
import 'package:api_package/meterhouses_transcribes.post.dart'
    as houseRecordInterface;

class PrivateIndexStore with ChangeNotifier {
  final BuildContext context, providerContext;
  late Map<String, dynamic> routingArgs;
  PrivateIndexStore(this.context, this.providerContext) {
    routingArgs = (ModalRoute.of(context)?.settings.arguments ??
            new Map<String, dynamic>()) as Map<String, dynamic>? ??
        {};
  }

  ///房屋搜索
  String? houseSearchKey = '';
  onHouseSubmint(v) {
    houseSearchKey = v;
    houseMeterList = [];
    commonMeterList = [];
    scrollViewKey.currentState?.initTrigger();
  }

  ///表名称搜索
  String meterSearchKey = '';
  onMeterSubmint(v) {
    meterSearchKey = v;
    houseMeterList = [];
    commonMeterList = [];
    scrollViewKey.currentState?.initTrigger();
  }

  /// tab 控制器
  late TabController tabController;
  int tabIndex = 0;

  String? meterType;
  DateTime? meterDate;

  String statusType = '';
  String  order = 'asc';
  ///弹窗筛选
  var filterHouse = {
    'name': '',
    'buildId': '',
    'unitId': '',
  };

  var filterCommon = {
    'name': '',
    'buildId': '',
    'unitId': '',
  };

  // tab切换
  onSetTabIndex(int index) {
    FocusScope.of(context).requestFocus(FocusNode());
    tabController.index = index;
    tabIndex = index;
    this.changeIsHouse(index);
  }

  ///弹窗筛选
  filterChange(values) {}

  ///是否住户表？
  bool isHouse = true;

  void changeIsHouse(int index) {
    // houseSearchKey = '';
    // meterSearchKey = '';
    if (index == 0) {
      isHouse = true;
      houseMeterList = [];
    } else {
      isHouse = false;
      commonMeterList = [];
    }
    scrollViewKey.currentState?.initTrigger();
    notifyListeners();
  }

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

  String? get communityId => communityGlobalStore.data.id;

  final scrollViewKey = GlobalKey<WisScrollViewState>();
  late Map<String, dynamic> params = {
    'pageNum': 1,
    'pageSize': 20,
  };
  getData({bool isLoad = false}) async {
    if (!isLoad) params['pageNum'] = 1;
    if (!isLoad) {
      isHouse ? await getHouseStat() : await getCommonStat();
    }
    if (isHouse) {
      await getHouseMeterList(isLoad: isLoad);
    } else {
      await getCommonMeterList(isLoad: isLoad);
    }
  }

  ///统计
  String? currentYearMonth; //当前账期
  num? transcribed; //已抄
  num? untranscribe; //未抄

  ///住户统计
  Future<void> getHouseStat() async {
    final res = await houseStatInterface.Interface.request(
      HttpUtil.instance,
      queryParameters: {
        'communityId': communityId,
        'buildId': filterHouse['buildId'],
        'unitId': filterHouse['unitId'],
        'meterType': meterType,
        'name': houseSearchKey?.isEmpty == true ? null : houseSearchKey,
        'readTime': meterDate != null
            ? DateFormat('yyyy-MM-dd').format(meterDate!)
            : null,
      },
    );
    transcribed = res.data?.communityHasTranscribe;
    currentYearMonth = res.data?.currentYearMonth;
    untranscribe = res.data?.communityNoTranscribe;
    notifyListeners();
  }

  ///公共统计
  Future<void> getCommonStat() async {
    final res = await commonStatInterface.Interface.request(
      HttpUtil.instance,
      queryParameters: {
        'communityId': communityId,
        'buildId': filterCommon['buildId'],
        'unitId': filterCommon['unitId'],
        'meterType': meterType,
        'readTime': meterDate != null
            ? DateFormat('yyyy-MM-dd').format(meterDate!)
            : null,
        'fuzzyMeterName':
            meterSearchKey.isEmpty == true ? null : meterSearchKey,
      },
    );
    transcribed = res.data?.communityHasTranscribe;
    untranscribe = res.data?.communityNoTranscribe;
    currentYearMonth = res.data?.currentYearMonth;
    notifyListeners();
  }

  ///保存
  Future<bool> onSave({
    num? number,
    String? id,
    String? source,
    String? readTime,
  }) async {
    if (source == 'house') {
      //找到对应的houseIndex   然后通过id获取该house中的仪表index
      final int houseindex = houseMeterList.indexWhere((e) =>
          e.meterHouseInfos
              .where((element) => element.id == id)
              .toList()
              .length !=
          0);
      final int meterIndex = houseMeterList[houseindex]
          .meterHouseInfos
          .indexWhere((e) => e.id == id);

      /// 2023.09.12 去除重抄
      bool success = false;

      final res = await houseRecordInterface.Interface.request(
          HttpUtil.instance,
          data: {
            'transcribeAmount': number,
            'meterId': id,
            'readTime': '${readTime}:00',
          });
      success = res.data != null;

      //手动修改列表数据
      if (success) {
        await getHouseStat();
        houseMeterList[houseindex].meterHouseInfos[meterIndex].transcribes =
            true; //是否已抄
        houseMeterList[houseindex].meterHouseInfos[meterIndex].readerDate =
            '${readTime}:00';
        notifyListeners();
      }

      return success;
    }

    ///公共表
    else {
      final int meterIndex = commonMeterList.indexWhere((e) => e.id == id);

      /// 2023.09.12 去除重抄
      bool success = false;

      final res = await commonRecordInterface.Interface.request(
          HttpUtil.instance,
          data: {
            'transcribeAmount': number,
            'meterId': id,
            'readTime': '${readTime}:00',
          });
      success = res.data != null;

      //手动修改列表数据
      if (success) {
        commonMeterList[meterIndex].transcribes = true;
        commonMeterList[meterIndex].readerDate = '${readTime}:00';
        await getCommonStat();
        notifyListeners();
      }

      return success;
    }
  }

  List<houseInterface.$DataModel> houseMeterList = [];
  List<commonInterface.$DataModel> commonMeterList = [];

  ///住户表列表
  Future getHouseMeterList({bool isLoad = true}) async {
    final res = await houseInterface.Interface.request(
      HttpUtil.instance,
      queryParameters: {
        ...params,
        'communityId': communityId,
        'buildId': filterHouse['buildId'],
        'unitId': filterHouse['unitId'],
        'meterType': meterType,
        'roomNo': houseSearchKey,
        'readTime': meterDate != null
            ? DateFormat('yyyy-MM-dd').format(meterDate!)
            : null,
        'order':order,
        'read': statusType != '' ? statusType == 'true' ? true : false :  null,
      },
    );
    final _data = res.data;
    if ((_data?.total ?? 0) == 0) {
      scrollViewKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      scrollViewKey.currentState?.isLast();
    } else {
      params['pageNum']++;
    }

    final _list = _data?.list ?? [];
    isLoad ? houseMeterList.addAll(_list) : houseMeterList = _list;
    notifyListeners();
  }

  ///公共表
  Future getCommonMeterList({bool isLoad = true}) async {
    final res = await commonInterface.Interface.request(
      HttpUtil.instance,
      queryParameters: {
        ...params,
        'communityId': communityId,
        'buildId': filterCommon['buildId'],
        'unitId': filterCommon['unitId'],
        'meterType': meterType,
        'fuzzyMeterName': meterSearchKey,
        'readTime': meterDate != null
            ? DateFormat('yyyy-MM-dd').format(meterDate!)
            : null,
        'read': statusType != '' ? statusType == 'true' ? true : false :  null,
      },
    );
    final _data = res.data;

    if ((_data?.total ?? 0) == 0) {
      scrollViewKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      scrollViewKey.currentState?.isLast();
    } else {
      params['pageNum']++;
    }

    final _list = _data?.list ?? [];
    isLoad ? commonMeterList.addAll(_list) : commonMeterList = _list;
    notifyListeners();
  }

  toFilter() async {
    await Get.toNamed('metered/filter', arguments: {
      'meterType': meterType == null ? '' : meterType,
      'filterValues': isHouse == true ? filterHouse : filterCommon,
      'isHouse': isHouse,
      'meterDate': meterDate,
      'order': order,
      'statusType': statusType,
    })!
        .then((res) {
      if (res != null) {
        if (isHouse == true) {
          filterHouse = res['filterValues'];
        } else {
          filterCommon = res['filterValues'];
        }
        statusType = res['statusType'];
        order = res['order'];
        meterDate = res['meterDate'];
        meterType = res['meterType'];
        houseMeterList = [];
        commonMeterList = [];
        notifyListeners();
        scrollViewKey.currentState?.initTrigger();
      }
    });
  }
}
