/*
 * @Author: WuWei
 * @Date: 2020-08-07 11:29:42
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2023-11-02 16:10:51
 * @Description:
 */

import 'package:app_package/app_package.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:app_package/src/api/employee.dart';
import 'package:get/get.dart';
import 'package:app_package/src/models/community_picker.dart';
import '../service/impl/pay_index_impl.dart';
import '../models/pay_type.dart';

class FilterIndexStore extends GetxController {
  void onInit() {
    super.onInit();
    getPayTypeList();
    if (Get.arguments['payWayCodesFirst'] != null) {
      payWayCodesFirst.value = Get.arguments['payWayCodesFirst'];
      payWayCodesFirst.refresh();
    }
  }

  void onInitFilter() async {}

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

  ///从储存中取出的当前小区 拿出来可能是空
  CommunityModel? get currentCommunity => communityGlobalStore.data;
  var communityId = ''.obs;

  var payAtStart = ''.obs;
  var payAtEnd = '', obs;

  var payAtStartDate = ''.obs;
  var payAtEndDate = ''.obs;

  /// 账单筛选开始时间
  var payBillAtStart = ''.obs;

  /// 账单筛选结束时间
  var payBillAtEnd = ''.obs;

  /// 选择筛选账单缴费起始时间
  onPickBillStartDate(date) {
    payBillAtStart.value = date;
  }

  /// 选择账单缴费结束时间
  onPickBillEndDate(date) {
    payBillAtEnd.value = date;
  }

  /// 业务行为 全部/收入/支出/作废
  final Map<String, String> behaviorMenu = {
    'ALL': 'all',
    'IN': 'in',
    'OUT': 'out',
    'CANCEL': 'cancel',
  };
  final behaviorType = [
    {'name': '全部', 'code': 'all', 'icon': ''},
    {
      'name': '收入',
      'code': 'in',
      'icon': 'lib/assets/in.png',
    },
    {
      'name': '支出',
      'code': 'out',
      'icon': 'lib/assets/out.png',
    },
    {
      'name': '作废',
      'code': 'cancel',
      'icon': 'lib/assets/cancel.png',
    },
  ];

  var currentBehaviorType = 'all'.obs;
  onChooseBehavior(code) {
    currentBehaviorType.value = code;
  }

  ///支付方式列表
  var payWayListFirst = [
    {'code': 'all', 'field': 'all', 'name': '全部', 'children': [], 'status': ''},
    {
      'code': '0',
      'field': 'offLine',
      'name': '线下',
      'children': [],
      'status': ''
    },
    {
      'code': '1',
      'field': 'onLine',
      'name': '线上',
      'children': [],
      'status': ''
    },
    {'code': '2', 'field': 'inner', 'name': '内部', 'children': [], 'status': ''},
  ].obs;

  var payWayListSecond = <PayTypeItem>[].obs;
  var payWayAnswerFirst = [].obs;

  var currentShowFirst = {}.obs;
  var currentShowCode = ''.obs;
  var payWayCodesFirst = ['all'].obs;
  var payWayCodesSecond = [].obs;

  var payTypeList = [].obs;
  var payTypeAllList = PayTypeModel().obs;

  /// 获取支付方式列表
  Future getPayTypeList() async {
    final res = await PayIndexServiceImpl().getPayTypeList({
      'communityId': currentCommunity?.id,
    });
    payTypeAllList.value = res.data ?? PayTypeModel();
    payWayListSecond.value = [];
    payWayListFirst.forEach((item) {
          if (item['field'] == 'onLine')
            {item['children'] = payTypeAllList.value.onLine ?? [];}
          else if (item['field'] == 'offLine')
            {item['children'] = payTypeAllList.value.offLine ?? [];}
          else if (item['field'] == 'inner')
            {item['children'] = payTypeAllList.value.inner ?? [];};
        });
    payTypeAllList.refresh();
    payWayListSecond.refresh();
  }

  /// 支付方式 一级选择
  onChangePayFirst(item) {
    /// 全选的特殊处理
    if (item['code'] == 'all') {
      payWayCodesFirst.value = [];
      payWayCodesSecond.value = [];
      payWayListFirst.forEach((item) => item['status'] = '');
      if (!payWayCodesFirst.contains(item['code'])) {
        payWayCodesFirst.value = ['all'];
      }
      return;
    }
    if (payWayCodesFirst.contains(item['code'])) {
      payWayCodesFirst.remove(item['code']);
      item['children'].forEach((e) => {payWayCodesSecond.remove(e.code)});
    } else {
      payWayCodesFirst.remove('all');
      payWayCodesFirst.add(item['code']);
      item['children'].forEach((e) => {
            if (!payWayCodesSecond.contains(e.code))
              {payWayCodesSecond.add(e.code)}
          });
    }
    item['status'] = '';
    onSetShowList(item);
  }

  /// 支付方式 二级选择
  onChangePaySecond(item) {
    if (payWayCodesSecond.contains(item.code)) {
      payWayCodesSecond.remove(item.code);
      payWayCodesFirst.remove(currentShowFirst['code']);
    } else {
      payWayCodesFirst.remove('all');
      payWayCodesSecond.add(item.code);
    }
    final isAll = currentShowFirst['children']
        .every((e) => payWayCodesSecond.contains(e.code));
    final matchSome = currentShowFirst['children']
            .where((e) => payWayCodesSecond.contains(e.code)) ??
        [];
    if (isAll) {
      payWayCodesFirst.add(currentShowFirst['code']);
    }
    currentShowFirst['status'] = !isAll && matchSome.length > 0 ? 'half' : '';
    currentShowFirst.refresh();
    payWayListFirst.refresh();
  }

  onSetShowList(item) {
    currentShowFirst.value = item;
    currentShowCode.value = item['code'];
    if (item['field'] == 'all') {
      payWayListSecond.value = [];
    } else {
      payWayListSecond.value = item['children'];
    }
  }

  /// 所选小区对象
  CommunityPickerModel? communityList;

  /// 所选小区名称
  String communityIName = '';

  /// 确定之后显示的所选小区名称
  String communityINameBySubmit = '';

  /// 获取小区列表
  Future<List<CommunityPickerModel>> getAsyncCommunityList() async {
    var res = await EmployeeApi.getDomainCommunityListToPicker();
    return res.data ?? [];
  }

  /// 选择小区
  onChooseCommunity(CommunityPickerModel res) {
    communityId.value = res.id ?? '';
    communityList = res;
    communityIName = res.name ?? '';
  }

  reset() {
    payWayCodesFirst.value = ['all'];
    payWayCodesSecond.value = [];
    currentBehaviorType.value = '';
    payBillAtStart.value = '';
    payBillAtEnd.value = '';
    payWayListFirst.forEach((item) => item['status'] = '');
  }

  /// 筛选重置
  onResetInner() {
    reset();
    Get.back(result: {
      'currentBehaviorType': 'all',
      'payBillAtStart': null,
      'payBillAtEnd': null,
      'payWayCodesFirst': ['all'],
      'payWayCodesSecond': [],
    });
  }

  back() {
    Get.back();
  }

  /// 确认筛选
  submit() {
    Get.back(result: {
      /// 业务行为
      'currentBehaviorType': currentBehaviorType.value,
      'payBillAtStart': payBillAtStart.value,
      'payBillAtEnd': payBillAtEnd.value,

      /// 收支方式一级code
      'payWayCodesFirst': payWayCodesFirst,

      /// 收支方式二级code
      'payWayCodesSecond': payWayCodesSecond,
    });
  }
}
