/*
 * @Author: wjc
 * @Date: 2022-04-18 10:21:09
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-06-07 16:18:55
 * @Description: 
 */
import 'package:flutter/material.dart';
import 'package:app_package/app_package.dart';
import 'package:smart_devices_package/src/models/sd_detail_list_model.dart';
import 'package:smart_devices_package/src/models/sd_detail_model.dart';
import 'package:smart_devices_package/src/models/sd_timing_list.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import '../service/impl/sd_impl.dart';
import '../service/sd_service.dart';

class PrivateDetailStore with ChangeNotifier {
  final BuildContext context, providerContext;
  late Map<dynamic, dynamic> routingArgs;
  PrivateDetailStore(this.context, this.providerContext) {
    routingArgs = (ModalRoute.of(context)?.settings.arguments ??
            new Map<String, dynamic>()) as Map<String, dynamic>? ??
        {};
  }
  final scorllViewListKeyIndex = GlobalKey<WisScrollViewState>();
  final scorllViewTimingKey = GlobalKey<WisScrollViewState>();
  final authGlobalStore = GetIt.I.get<AuthGlobalStore>();

  final SmartDevicesService _smartDevicesService = SmartDevicesServiceImpl();

  Map<String, dynamic> params = {
    'pageNum': 1,
    'pageSize': 20,
  };
  SmartDevicesDetailModel deviceDetail = new SmartDevicesDetailModel();

  Future getDetail({isChange = false}) async {
    Future.wait([getDeviceDetail(), getDeviceRecord(isLoad: false)]);
    routingArgs['item']['status'] =
        !isChange && routingArgs['item']['status'] == 0 ? 0 : 1;
    notifyListeners();
  }

  ///智能表详情
  Future getDeviceDetail() async {
    var res = await _smartDevicesService.getDeviceDetail({
      'id': routingArgs['item']['id'],
    });
    deviceDetail = res.data!;
    notifyListeners();
  }

  ///智能表详细列表
  List<SmartDevicesDetailListModel> detailList = [];

  Future getDeviceRecord({bool isLoad = true}) async {
    if (!isLoad) params['pageNum'] = 1;
    if (routingArgs['item']['id'] == null) return;
    var res = await _smartDevicesService.getDeviceRecord({
      ...params,
      'controllerId': routingArgs['item']['controllerId'],
    });
    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      scorllViewListKeyIndex.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      scorllViewListKeyIndex.currentState?.isLast();
    } else {
      params['pageNum']++;
    }
    isLoad ? detailList.addAll(_list) : detailList = _list;
    notifyListeners();
  }

  /// 智能设备-操作
  Future<void> handleDeviceOperate(item, behavior) async {
    if (authGlobalStore.info?.id == null) {
      return;
    }
    WLoadingUtil.show();
    var res = await _smartDevicesService.getDeviceOnAndOff(
      {
        'controllerId': item['controllerId'],
        'behavior': behavior,
      },
    );

    WLoadingUtil.hide();

    if (res) {
      WToastUtil.show('操作成功！');
      scorllViewListKeyIndex.currentState?.initTrigger();
    } else {
      WToastUtil.show('操作失败！');
    }
    notifyListeners();
  }

  Map paramsTiming = {
    'pageNum': 1,
    'pageSize': 20,
  };
  List<TimingListModel> timingList = [];

  /// 获取定时列表
  Future<void> getTimingList({bool isLoad = true}) async {
    if (!isLoad) paramsTiming['pageNum'] = 1;
    var res = await _smartDevicesService.getTimingList({
      'args': routingArgs['item']['controllerId'],
      ...paramsTiming,
    });
    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      scorllViewTimingKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      scorllViewTimingKey.currentState?.isLast();
    } else {
      paramsTiming['pageNum']++;
    }
    isLoad ? timingList.addAll(_list) : timingList = _list;
    notifyListeners();
  }

  /// 设置设备详情tab标签索引
  int tabIndex = 0;
  void setTabIndex(index) {
    tabIndex = index;
    notifyListeners();
  }

  /// 打开定时开关
  setSwitchOnOff(item, isOpen) {}

  /// 跳转新增定时页面
  Future<void> route2TimingPage(item) async {
    await Navigator.pushNamed(
      context,
      'smart_devices/timing_set',
      arguments: {
        'item': item == null ? null : item.toJson(),
        'detail': routingArgs['item'],
      },
    );
    timingList = [];
    paramsTiming['pageNum'] = 1;
    scorllViewTimingKey.currentState?.initTrigger();
    notifyListeners();
  }

  /// 智能设备-操作
  Future handleDeviceOnOff(item, behavior) async {
    bool? isConfirm = await WModalUtil.showSync(
      '${behavior == true ? '启用后可对其设备进行操作，不可进行编辑。确认启用吗？' : '停用后不可对其进行操作，可对其进行编辑。确认停用吗？'}',
      title: '${behavior == true ? '启用' : '停用'}提醒',
    );
    if (isConfirm == true) {
      WLoadingUtil.show();
      if (behavior) {
        var res = await SmartDevicesServiceImpl().patchTimingEnable(item?.id);
        WLoadingUtil.hide();

        if (res.data == true) {
          WToastUtil.show('定时开启成功！');
          timingList = [];
          paramsTiming['pageNum'] = 1;
          scorllViewTimingKey.currentState?.initTrigger();
          notifyListeners();
        } else {
          WToastUtil.show('定时开启失败！');
        }
      } else {
        var res = await SmartDevicesServiceImpl().patchTimingDisable(item?.id);
        WLoadingUtil.hide();
        if (res.data == true) {
          WToastUtil.show('定时关闭成功！');
          timingList = [];
          paramsTiming['pageNum'] = 1;
          scorllViewTimingKey.currentState?.initTrigger();
          notifyListeners();
        } else {
          WToastUtil.show('定时关闭失败！');
        }
      }
    }
  }
}
