/*
 * @Author       : WuWei
 * @LastEditors: wuwei
 * @Date         : 2021-07-23 14:50:43
 * @LastEditTime: 2024-01-26 15:10:55
 * @Description  : Do not edit
 */
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:task_package/src/impl/qrcode_impl.dart';
import 'package:task_package/src/impl/task_service_impl.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

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

  String? relationIds;

  /// tab 控制器
  TabController? tabController;

  ScrollController controller = new ScrollController();

  final scrollViewKey = GlobalKey<WisScrollViewState>();

  int pageNum = 1;
  var dataList = [].obs;
  var searchText = ''.obs;
  var status = ''.obs;
  var type = ''.obs;
  var taskTypeList = [].obs;

  onSearch(v) async {
    searchText.value = v;
    pageNum = 1;
    dataList.value = [];
    dataList.refresh();
    scrollViewKey.currentState?.initTrigger();
  }

  init() async {
    if (Get.arguments['id'] != null) {
      relationIds = Get.arguments['id'];
      await onGetTaskListItem();
    }

    await onGetScanTaskList();
  }

  /// 获取预设清单列表
  onGetTaskListItem() async {
    if (taskTypeList.length != 0) {
      return;
    }
    var res =
        await TaskServiceImpl.instance!.getInventoryList({"preset": true});
    taskTypeList.value = res.data ?? [];
    taskTypeList.refresh();
  }

  chooseType(data) {
    type.value = data;
    pageNum = 1;
    dataList.value = [];
    dataList.refresh();
    scrollViewKey.currentState?.initTrigger();
  }

  Future<void> onGetScanTaskList() async {
    var params = {
      'inventoryIds': type.value == '' ? null : type.value,
      'status': status.value == '' ? null : status.value,
    };
    var res = await QrcodeServiceImpl.instance!.getTaskList({
      ...params,
      'pageNum': pageNum,
      'pageSize': 20,
      'type': 'scan_qrCode',
      'relationIds': relationIds,
      'title': searchText.value == "" ? null : searchText.value,
    });
    final _data = res.data;
    pageNum == 1
        ? dataList.value = _data?.list ?? []
        : dataList.addAll(_data?.list ?? []);
    dataList.refresh();
    if ((_data?.total ?? 0) == 0) {
      scrollViewKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0) &&
        _data!.total! > 0) {
      scrollViewKey.currentState?.isLast();
    } else {
      pageNum++;
    }
  }

  /// 未开始提示任务开始
  Future<void> onStartTask(item) async {
    bool? confirm = await WModalUtil.showSync(
      '开始后任务不可再修改，并将通知任务派发人，确认开始吗？',
      title: '确认开始该任务？',
      confirmText: '确认开始',
    );
    if (confirm == true) {
      var res = await TaskServiceImpl.instance!.putStartTask(item?.id);
      if (res) {
        WToastUtil.show('任务开始成功');
        await checkOrder(item);
        await onResetList();
      } else {
        WToastUtil.show('任务开启失败');
      }
    }
  }

  route2Detail(item) async {
    if (item?.status == 'no_open' || item?.status == 'doing') {
      ///逻辑判断
      ///1. 是否按序
      ///2. 是否当前二维码执行点
      checkTaskAvaliable(item);
    } else {
      onHandleToDetail(item);
    }
  }

  /// 校验任务
  Future<void> checkTaskAvaliable(item) async {
    /// 判断是否到生效时间
    if (item?.canStartTime != null) {
      final now = DateTime.now();
      final time = DateTime.parse(item?.canStartTime);

      /// 比较时间
      if (time.difference(now).inMilliseconds > 0) {
        WToastUtil.show('该任务生效时间为${item?.canStartTime}');
        return;
      }
    }

    ///是否开始
    if (item?.status == 'no_open') {
      onStartTask(item);
      return;
    }

    checkOrder(item);
  }

  checkOrder(item) async {
    /// 是否按序
    if (item?.seqencing == true) {
      var res = await QrcodeServiceImpl.instance!.getCheckTask({
        'exPlatformId': item?.id,
        'relationIds': relationIds,
      });

      ///  是否可以执行
      if (res.data?.executable == true) {
        onHandleToDetail(item);
      } else {
        WToastUtil.show(res.data!.message!);
      }
    } else {
      onHandleToDetail(item);
    }
  }

  onHandleToDetail(item) async {
    /// 待领取直接到任务详情 否则到节点详情
    if (item.status == 'waitReceive') {
      /// 跳转详情
      Get.toNamed(
        'task/detail',
        arguments: {
          'id': item.id,
          'isChild': item.isChild,
        },
      )!
          .then((value) => {
                onResetList(),
              });
    } else {
      /// 跳转详情
      Get.toNamed(
        'task/point_form',
        arguments: {
          'id': item.id,
          'relationIds': relationIds,
          'type': 'scan',
        },
      )!
          .then((value) => {
                onResetList(),
              });
    }
  }

  ///重置列表
  Future<void> onResetList() async {
    pageNum = 1;
    dataList.value = [];
    dataList.refresh();

    onGetScanTaskList();
  }

  /// 跳转筛选
  toFilterPage() {
    Get.toNamed(
      'task/scan_filter',
      arguments: {
        'status': status.value,
        'type': type.value,
      },
    )!
        .then((res) => {
              if (res != null)
                {
                  status.value = res['status'],
                  type.value = res['type'],
                  pageNum = 1,
                  dataList.value = [],
                  dataList.refresh(),
                  scrollViewKey.currentState?.initTrigger(),
                }
            });
  }
}
