/*
 * @Author       : WuWei
 * @LastEditors  : WuWei
 * @Date         : 2022-05-24 15:23:21
 * @LastEditTime : 2023-05-15 15:18:48
 * @Description  : Do not edit
 */
import 'package:flutter/material.dart';
import 'package:smart_devices_package/src/models/timing_type.dart';
import 'package:smart_devices_package/src/service/impl/sd_impl.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

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

  Future<void> onInit() async {
    if (routingArgs['item'] != null) {
      type = routingArgs['item']['args']['behavior'] == 'OPEN' ? true : false;
      var cronArr = routingArgs['item']['cronExpression'].split(' ');
      var weekString = cronArr[5];
      if (weekString == '*' || weekString == '?') {
        cycleType = null;
      } else if (weekString == '2,3,4,5,6') {
        cycleType = 'work';
      } else if (weekString == '1,2,3,4,5,6,7') {
        cycleType = 'day';
      } else {
        cycleType = 'set';
        weeks = weekString.split(',');
      }
      time = '${cronArr[2]}:${cronArr[1]}';
      notifyListeners();
    }
    // Future.wait([
    //   onGetTypeList(),
    // ]);
  }

  /// 操作类型
  List<TimingTypeModel> typeList = [];

  Future<void> onGetTypeList() async {
    var res = await SmartDevicesServiceImpl().getTimingType();
    typeList = res.data ?? [];
    notifyListeners();
  }

  /// 选择类型
  bool? type;

  void onSetType(value) {
    type = value;
    notifyListeners();
  }

  String? time;

  /// 选择时间
  void onSetTime(value) {
    time = value;
    notifyListeners();
  }

  List? cycle;
  String? cycleType;
  List weeks = [];

  /// 选择星期几
  void onSetWeeks(value) {
    if (weeks.contains(value)) {
      weeks.removeAt(weeks.indexWhere((element) => element == value));
    } else {
      weeks = [value, ...weeks];
    }
    notifyListeners();
  }

  /// 选择周期
  void onSetCycle(value) {
    if (value != 'set') {
      weeks = [];
    }
    cycleType = value;
    notifyListeners();
  }

  List times = [];
  CronBean get cronItem => new CronBean(
        int.parse(time!.split(':').toList().last),
        null,
        int.parse(time!.split(':').toList().first),
        null,
        null,
        null,
      );

  String get cron => setCron();

  onSave() async {
    if (type == null) {
      WToastUtil.show('请选择操作类型');
      return;
    }

    if (time == null) {
      WToastUtil.show('请选择时间设置');
      return;
    }
    if (routingArgs['item'] == null) {
      addTiming();
    } else {
      editTiming();
    }
  }

  onDelete() async {
    bool? isConfirm = await WModalUtil.showSync(
      '确定删除此定时设置吗?',
      title: '删除提醒',
    );
    if (isConfirm == true) {
      var res = await SmartDevicesServiceImpl()
          .deleteTiming(routingArgs['item']['id']);
      if (res.data == true) {
        WToastUtil.show('删除成功');
        Navigator.pop(context);
      } else {
        WToastUtil.show('删除失败');
      }
    }
  }

  addTiming() async {
    var res = await SmartDevicesServiceImpl().addTiming({
      'startTime': DateTime.now().toFormat(WisDateTimeFormat.dateAndTime),
      'taskCode': 'SMART_DEVICE_OPERATE',
      'name': '${routingArgs['detail']['controllerId']} $cron',
      'enable': true,
      'cronExpression': cron,
      'args': {
        'controllerId': routingArgs['detail']['controllerId'],
        'behavior': type == true ? 'OPEN' : 'CLOSE',
      }
    });

    if (res.data == true) {
      WToastUtil.show('设置保存成功！');
      Navigator.pop(context);
    }
  }

  editTiming() async {
    var args = {
      'startTime': DateTime.now().toFormat(WisDateTimeFormat.dateAndTime),
      'taskCode': 'SMART_DEVICE_OPERATE',
      'name': '${routingArgs['detail']['controllerId']} $cron',
      'enable': true,
      'cronExpression': cron,
      'args': {
        'controllerId': routingArgs['detail']['controllerId'],
        'behavior': type == true ? 'OPEN' : 'CLOSE',
      }
    };
    var res = await SmartDevicesServiceImpl()
        .editTiming(args, routingArgs['item']['id']);

    if (res.data == true) {
      WToastUtil.show('设置保存成功！');
      Navigator.pop(context);
    }
  }

  setCron() {
    var minute = time?.split(':')[1];
    var hour = time?.split(':')[0];
    var day = '?';
    var month = '*';
    dynamic week = '*';

    var cron = '';
    switch (cycleType) {
      case 'day':
        week = '1,2,3,4,5,6,7';
        cron = '0 $minute $hour $day $month $week';
        break;
      case 'work':
        week = '2,3,4,5,6';
        cron = '0 $minute $hour $day $month $week';
        break;
      case 'set':
        week = weeks.length != 0 ? weeks.join(',') : '*';
        cron = '0 $minute $hour $day $month $week';
        break;
      default:
        cron = '0 $minute $hour $day $month $week';
    }
    return cron;
  }
}
