/*
 * @Author       : WuWei
 * @LastEditors: wuwei
 * @Date         : 2023-11-01 20:50:00
 * @LastEditTime: 2023-12-21 09:11:49
 * @Description  : Do not edit
 */
import 'dart:async';
import 'dart:io';
import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:intl/intl.dart' show DateFormat;
import 'package:image/image.dart' as ui;
import '../api/asset_bill.dart';
import '../models/asset_list.dart';
import '../models/owe_fee_count.dart';
import '../models/payer.dart';

class UrgePayStore extends GetxController {
  final scrollViewKey = GlobalKey<WisScrollViewState>();

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

  CommunityModel? get community => communityGlobalStore.data;
  String? assetId;
  String? assetType;
  String? assetFullName;

  var imageName = ''.obs;

  var imageId = ''.obs;

  var remark = ''.obs;

  var noticeArrearsFee = ''.obs;
  var feeNum = 0.obs;

  get timeName => DateFormat("yyyy").format(time.value) == '1900'
      ? null
      : DateFormat("yyyy-MM-dd HH:mm").format(time.value);

  var assetItem = AssetsOfAssetListModel(
    name: '全部',
    code: '',
  ).obs;
  var time = DateTime(1900).obs;

  var image;

  /// 催缴页面初始化
  Future<void> onInitData() async {
    assetId = Get.arguments['assetId'];
    assetType = Get.arguments['assetType'];
    assetFullName = Get.arguments['assetFullName'];
    await getAssetList();
    await getTotalCount();
  }

  /// 催缴登记
  Future<void> toSubmit() async {
    // if(assetItem.value.code == null || ) {

    // }
    if (payFee.value == 0) {
      WToastUtil.show('该资产未有欠费~');
      return;
    }
    // if (payFee.value != 0) {
    //   WToastUtil.show('请输入金额~');
    //   return;
    // }
    // if (feeNum.value == 0) {
    //   WToastUtil.show('请输入期数~');
    //   return;
    // }
    if (resident.value.payer == null || resident.value.payer == '') {
      WToastUtil.show('请选择住户~');
      return;
    }
    if (timeName == null || timeName == '') {
      WToastUtil.show('请选择时间~');
      return;
    }
    if (remark.value == '') {
      WToastUtil.show('请输入催缴内容~');
      return;
    }
    var params = {
      'assetId': assetItem.value.code,
      'treeSelection': assetItem.value.type,
      'remark': remark.value,
      'residentId': resident.value.id,
      'residentName': resident.value.payer,
      'mobile': resident.value.mobile,
      'photos': imageId.value,
      'type': 'artificial',
      'createAt': '${timeName}:00',
      'arrearsPeriodNum': feeNum.value,
      'noticeArrearsFee': payFee.value,
      'chargeYearMonthRange': data?.billingPeriod ?? DateFormat("yyyy-MM").format(DateTime.now()),
    };
    var res = AssetBillApi.postUrgePay(params);
    if (res != 0) {
      await WToastUtil.show('催缴登记成功！', duration: Duration(seconds: 2));
      Get.back();
    }
  }

  /// 解析字符串为double类型，如果字符串为空，则返回0
  double parseDouble(String? value) {
    return double.parse(value == '' ? '0' : value!);
  }

  Future<void> inputRemark(value) async {
    remark.value = value;
  }

  Future<void> inputFee(value) async {
    noticeArrearsFee.value = value;
  }

  Future<void> inputFeeNum(value) async {
    feeNum.value = value;
  }

  /// 住户列表
  getResidentList() async {}

  Future<void> chooseTime() async {
    var res =
        await WPickerUtil.dateAndTime(Get.context!, title: WisText('选择时间'));
    time.value = res ?? DateTime(1900);
  }

  /// 选择资产
  Future<void> chooseAssets() async {
    var res = await WPickerUtil.single<AssetsOfAssetListModel>(
      Get.context!,
      title: WisText('选择资产'),
      getData: () async => await payBillAssetList,
      initialValue: assetItem.value,
    );
    if (res != null) {
      assetItem.value = res;
      await getTotalCount();
    }
  }

  Future<void> deleteImg() async {
    image = null;
    imageId.value = '';
    imageName.value = '';
    imageId.refresh();
  }

  /// 上传凭证
  Future<void> uploadImage() async {
    final res = await WAssetPickerUtil.image(
      maxCount: 1,
      source: WImageSource.cameraAndGallery,
    );
    if (res.isNotEmpty) {
      final futures = onPostWaterMarkImg(res[0].file!);
      try {
        WLoadingUtil.show();
        final res = await futures;
        image = res;
        imageId.value = res['id'];
        imageName.value = res['name'];
      } finally {
        WLoadingUtil.hide();
      }
    }
  }

  GlobalKey wmglkey = new GlobalKey();

  /// 添加水印
  Future<File?> addWaterMark(File file) async {
    /// 水印widget 转图片
    // if (currentAddress != null) {
    var tempMark = await capturePng(wmglkey);
    print(tempMark);

    /// 水印
    ui.Image tempMarkImg = ui.decodeImage(tempMark!)!;

    /// 照片
    ui.Image fileImg = ui.decodeImage(file.readAsBytesSync())!;

    /// 照片上加上水印
    ui.Image img = ui.drawImage(fileImg, tempMarkImg);
    List<int> wmImage = ui.encodeJpg(img);

    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path;

    String picName = 'receipt_submit_${DateTime.now()}.jpg';

    ///拼接目录
    appDocPath = "$appDocPath/$picName";

    ///校验图片是否存在
    var _file = File(appDocPath);
    bool exist = await _file.exists();
    if (exist) {
      ///如果图片存在就进行删除替换
      ///如果新的图片加载失败，那么旧的图片也被删除了
      await file.delete();
    }
    await File(appDocPath).writeAsBytes(wmImage);
    return _file;
  }

  /// 上传水印照片
  Future onPostWaterMarkImg(File file) async {
    var res = await addWaterMark(file);
    if (res != null) {
      return await GlobalApi.postUploadImageObject(res);
    } else {
      WLoadingUtil.hide();
      return null;
    }
  }

  /// 预览详情图片
  void onShowImage(image) {
    List<ImageProvider> images = [];
    images.add(CachedNetworkImageProvider(AppParseUtil.image(image)));
    WisPhotoViewUtil.show(images, 0);
  }

  var data;
  var payFee = 0.0.obs;
  // Future getTotalCount() async {
  //   Map<String, dynamic> params = {
  //     'assetId': assetItem.value.code,
  //     'communityId': community?.id,
  //     'treeSelection': assetItem.value.type,
  //     'chargeYearMonthEnd': DateFormat('yyyy-MM').format(DateTime.now()),
  //   };
  //   var res = await AssetBillApi.getFeeListByMonth(params);
  //   // res.data?.detailInfos?.
  //   data = res.data ?? OweFeeCountModel();
  //   payFee = data?.payFee ?? 0;
  // }

  var payBillAssetList = <AssetsOfAssetListModel>[].obs;

  var residentList = <PayerModel>[].obs;

  var resident = PayerModel().obs;

  /// 选择住户
  Future<void> chooseResident() async {
    final res = await WPickerUtil.single<PayerModel>(
      Get.context!,
      title: Text('缴费人'),
      getData: () async => getPayerList().then((value) => value!),
    );
    if (res != null) {
      resident.value = res;
    }
  }

  Future<List<PayerModel>?> getPayerList() async {
    if (residentList.length != 0) return residentList;
    final res = await AssetBillApi.getPayerList({
      'assetId': assetId,
      'treeSelection': assetType,
      'communityId': community?.id,
    });
    residentList.value = res.data ?? [];
    return residentList;
  }

  /// 资产列表 按资产id获取全部关联资产
  Future<void> getAssetList() async {
    var res = await AssetBillApi.getAssetListByAssetId({
      'assetId': assetId,
      'treeSelection': assetType,
    });
    List<AssetsOfAssetListModel> _list = [];
    var _asset = AssetsOfAssetListModel(
      code: assetId,
      name: assetFullName,
      type: assetType,
    );
    assetItem.value = _asset;
    _list.add(_asset);

    res.data?.forEach((item) {
          if ((item.type == 'house' ||
                  item.type == 'car' ||
                  item.type == 'parkingSpace') &&
              item.assets != null &&
              item.assets!.length > 0)
            {
              item.assets?.forEach((element) {
                element.type = item.type;
                _list.add(element);
              });
            };
        });
    payBillAssetList.value = _list;
    payBillAssetList.refresh();
    residentList.refresh();
  }

  /// 获取账单总计-------------------------------------------
  Future<void> getTotalCount() async {
    Map<String, dynamic> params = {
      'assetId': assetItem.value.code != null && assetItem.value.code != ''
          ? assetItem.value.code
          : assetId,
      'treeSelection':
          assetItem.value.type != '' && assetItem.value.type != null
              ? assetItem.value.type
              : assetType,
      'identification': null,
      'feeTypeId': null,
      'communityId': community?.id,
      'chargeYearMonthEnd': DateFormat('yyyy-MM').format(DateTime.now()),
    };

    var res = await AssetBillApi.getOweFeeCount(params);
    data = res.data ?? OweFeeCountModel();
    feeNum.value = res.data?.arrearsBillingPeriodCount ?? 0;
    payFee.value = double.parse('${data?.arrearsFee ?? 0}');
  }
}
