import 'dart:async';

import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import '../models/intelligent_list_model.dart';
import '../service/intelligent_service.dart';
import '../service/impl/intelligent_impl.dart';
import '../components/showStatusPicker.dart';

class PrivateIntelligentIndexStore with ChangeNotifier {
  final BuildContext context, providerContext;
  late Map<String, dynamic> routingArgs;
  PrivateIntelligentIndexStore(this.context, this.providerContext) {
    routingArgs = (ModalRoute.of(context)?.settings.arguments ??
            new Map<String, dynamic>()) as Map<String, dynamic>? ??
        {};
  }
  final authGlobalStore = GetIt.I.get<AuthGlobalStore>();
  final appGlobalStore = GetIt.I.get<AppGlobalStore>();
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

  ///从储存中取出的当前小区 拿出来可能是空

  CommunityModel? get currentCommunity => communityGlobalStore.data;

  String? get chargeMode => appGlobalStore.chargeMode;

  final scorllViewListKey = GlobalKey<WisScrollViewState>();

  final IntelligentService _intelligentService = IntelligentServiceImpl();

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

  String meterNames = '';

  String? status = '';

  String selectStatus = '';

  String? meterType = '';

  Future onInit() async {
    await Future.wait([
      appGlobalStore.getMeterChargeMode(),
      getIntelligentList(isLoad: false),
    ]);
  }

  ///智能表列表
  List<IntelligentListModel> intelligentList = [];

  /// 智能表请求列表
  Future getIntelligentList({bool isLoad = true}) async {
    if (!isLoad) params['pageNum'] = 1;
    if (currentCommunity?.id == null) {
      WToastUtil.show('小区不能为空！');
      return;
    }

    params['communityId'] = currentCommunity?.id;
    if (meterType != null && meterType != '') {
      params['meterType'] = meterType;
    } else {
      params.remove('meterType');
    }
    if (chargeMode != 'transcribeCharging') {
      params['status'] = status;
    }
    var res = await _intelligentService.getIntelligentList({
      ...params,
      'meterNames': meterNames,
    });
    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      scorllViewListKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      scorllViewListKey.currentState?.isLast();
    } else {
      params['pageNum']++;
    }
    isLoad ? intelligentList.addAll(_list) : intelligentList = _list;
    notifyListeners();
  }

  void onNameSearchTrigger() {
    intelligentList = [];
    scorllViewListKey.currentState?.initTrigger();
  }

  void onNameInput(value) {
    meterNames = value;
    this.onNameSearchTrigger();
  }

  /// 通电
  Future handleMeterOn(item, isDetail) async {
    if (authGlobalStore.info?.id == null) {
      return;
    }
    WLoadingUtil.show();

    var res = await (_intelligentService.getMeterOnAndOff(
      {
        'meterId': isDetail ? item['meterId'] : item.meterId,
        'empId': authGlobalStore.info?.id,
        'powerOn': true
      },
    ));

    WLoadingUtil.hide();

    if (res == true) {
      WToastUtil.show('通电成功！');
      if (!isDetail) {
        intelligentList = [];
        scorllViewListKey.currentState?.initTrigger();
      }
    } else {
      WToastUtil.show('通电失败！');
    }
    notifyListeners();
  }

  /// 断电
  Future<void> handleMeterOff(item, isDetail) async {
    WLoadingUtil.show();

    var res = await (_intelligentService.getMeterOnAndOff({
      'meterId': isDetail ? item['meterId'] : item.meterId,
      'empId': authGlobalStore.info?.id,
      'powerOn': false
    }));
    WLoadingUtil.hide();

    if (res == true) {
      WToastUtil.show('断电成功！');
      if (!isDetail) {
        intelligentList = [];
        scorllViewListKey.currentState?.initTrigger();
      }
    } else {
      WToastUtil.show('断电失败！');
    }
    notifyListeners();
  }

  /// 筛选
  handleShowChoose() async {
    var value = await StatusAndTypePicker.show(
        context, meterType, status, chargeMode != 'transcribeCharging');

    if (value != null && value['type'] != null && value['type'] != '') {
      meterType = value['type'];
    } else {
      meterType = '';
    }

    if (value != null &&
        value['status'] != null &&
        chargeMode != 'transcribeCharging') {
      status = value['status'];
    } else {
      status = '';
    }
    intelligentList = [];
    scorllViewListKey.currentState?.initTrigger();
    notifyListeners();
  }

  /// 修改对应智能表的值
  handleChangeListData(value) {
    for (var i = 0; i < intelligentList.length; i++) {
      if (intelligentList[i].meterId == value['meterId']) {
        intelligentList[i].powerOn = value['powerOn'];
      }
    }
    notifyListeners();
  }

  ///智能表详情页
  routeToDetail(IntelligentListModel item) async {
    await Navigator.pushNamed(
      context,
      'intelligent/detail',
      arguments: {
        'item': item.toJson(),
      },
    ).then((value) {
      handleChangeListData(value);
      notifyListeners();
    });
  }
}
