import 'dart:async';
import 'dart:io';
import 'package:decimal/decimal.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:sk_base_mobile/apis/index.dart';
import 'package:sk_base_mobile/constants/enum.dart';
import 'package:sk_base_mobile/db_helper/dbHelper.dart';
import 'package:sk_base_mobile/models/index.dart';
import 'package:sk_base_mobile/screens/inventory_inout/inventory_inout_controller.dart';
import 'package:sk_base_mobile/util/date.util.dart';
import 'package:sk_base_mobile/util/logger_util.dart';
import 'package:sk_base_mobile/util/media_util.dart';
import 'package:sk_base_mobile/util/snack_bar.util.dart';

class NewInventoryInoutController extends GetxController {
  final formKey = GlobalKey<FormState>();
  final int? inOrOut;
  DateTime? pickedDate;
  final DbHelper db = DbHelper();
  RxInt selectedImage = 0.obs;
  RxBool lowPeriority = false.obs;
  RxBool labelFocus = false.obs;
  RxBool categoryFocus = false.obs;
  RxBool descriptionFocus = false.obs;
  RxString selectedDate = ''.obs;
  RxString startTime = ''.obs;
  RxString endTime = ''.obs;
  RxBool loading = false.obs;
  final inventoryInoutController = Get.put(InventoryInoutController());
  final label = TextEditingController().obs;
  final description = TextEditingController().obs;
  final category = TextEditingController().obs;
  RxList<ProjectModel> projects = <ProjectModel>[].obs;
  RxList<ProductModel> products = <ProductModel>[].obs;
  final projectTextController = TextEditingController();
  final productTextController = TextEditingController();
  final dateTextController = TextEditingController();
  final quantityTextController = TextEditingController();
  final unitPriceTextController = TextEditingController();
  final amountTextController = TextEditingController();
  final agentTextController = TextEditingController();
  final remarkTextController = TextEditingController();
  final positionTextController = TextEditingController();
  final uploadImgFilesPath = <String>[].obs;
  final uploadScrollController = ScrollController();
  Map<String, dynamic> payload = {};
  NewInventoryInoutController({this.inOrOut});

  Future<List<ProjectModel>> getProjects({String? keyword}) async {
    final res =
        await Api.getProjects({'page': 1, 'pageSize': 10, 'name': keyword});
    if (res.data != null) {
      projects.assignAll(
          res.data!.items.map((e) => ProjectModel.fromJson(e)).toList());
    }
    return projects;
  }

  Future<List<ProductModel>> getProducts({String? keyword}) async {
    final res =
        await Api.getProducts({'page': 1, 'pageSize': 10, 'keyword': keyword});
    if (res.data != null) {
      products.assignAll(
          res.data!.items.map((e) => ProductModel.fromJson(e)).toList());
    }
    return products;
  }

  @override
  onReady() {
    super.onReady();
    dateTextController.text = DateUtil.format(DateTime.now());
    payload['time'] = DateUtil.format(DateTime.now());
    payload['inOrOut'] = inOrOut;
  }

  /// 实时计算数量，单价，金额之间的关系
  void calculatePrice(String changedField) {
    Decimal quantity = Decimal.fromInt(0);
    Decimal unitPrice = Decimal.fromInt(0);
    Decimal amount = Decimal.fromInt(0);
    if (quantityTextController.text.isNotEmpty) {
      quantity = Decimal.parse(quantityTextController.text);
    }
    if (unitPriceTextController.text.isNotEmpty) {
      unitPrice = Decimal.parse(unitPriceTextController.text);
    }
    if (amountTextController.text.isNotEmpty) {
      amount = Decimal.parse(amountTextController.text);
    }
    if (InventoryInOrOutEnum.Out == inOrOut) {
      if (changedField != 'amount') {
        Decimal result = unitPrice * quantity;
        amountTextController.text =
            result != Decimal.zero ? result.toString() : '';
      }
    } else {
      // 入库一般是先输入总价和数量，然后计算单价
      if (changedField != 'unitPrice' && quantity != Decimal.zero) {
        Decimal result =
            (amount / quantity).toDecimal(scaleOnInfinitePrecision: 10);
        unitPriceTextController.text =
            result != Decimal.zero ? result.toString() : '';
      } else if (changedField != 'amount') {
        Decimal result = (unitPrice * quantity);
        amountTextController.text =
            result != Decimal.zero ? result.toString() : '';
      }
    }
  }

  /// 创建出入库记录
  Future<void> create() async {
    if (payload['projectId'] == null) {
      SnackBarUtil().info(
        '项目不能为空',
      );
      return;
    }
    if (payload['productId'] == null) {
      SnackBarUtil().info(
        '产品不能为空',
      );
      return;
    }
    if (payload['time'] == null) {
      SnackBarUtil().info(
        '时间不能为空',
      );
      return;
    }
    payload['quantity'] = quantityTextController.text;
    if (payload['quantity'].isEmpty) {
      SnackBarUtil().info(
        '数量不能为空',
      );
      return;
    }
    payload['agent'] = agentTextController.text;
    if (payload['agent'].isEmpty) {
      SnackBarUtil().info(
        '经办人不能为空',
      );
      return;
    }
    if (unitPriceTextController.text.isEmpty) {
      payload.remove('unitPrice');
    } else {
      payload['unitPrice'] = unitPriceTextController.text;
    }
    if (amountTextController.text.isEmpty) {
      payload.remove('amount');
    } else {
      payload['amount'] = amountTextController.text;
    }

    payload['remark'] = remarkTextController.text;
    loading.value = true;
    // uploadImgFilesPath

    try {
      // final recordId = res.data as int;
      // 批量同时上传
      final uploadRes = await Future.wait(uploadImgFilesPath
          .map((filePath) => MediaUtil().uploadImg(File(filePath),
              bussinessModule: StorageBussinessModuleEnum.MaterialsInOut,
              bussinessRecordId: null))
          .toList());
      List<int> fileIds = [];
      if (uploadRes.isNotEmpty) {
        fileIds = uploadRes.map((e) => e!.id!).toList();
      }
      final response = await Api.createInventoryInout(payload);
      // 保存照片
      if (fileIds.isNotEmpty) {
        await Api.updateInventoryInout(
            response.data, {'fileIds': uploadRes.map((e) => e!.id).toList()});
      }
      Get.back(result: true);
      SnackBarUtil().success(
        '提交成功',
      );
    } catch (e) {
      LoggerUtil().error(e);
    } finally {
      loading.value = false;
    }
  }

  Future<void> photoPicker() async {
    XFile? pickedFile = await MediaUtil().getImageFromCamera();
    if (pickedFile != null) {
      uploadImgFilesPath.add(pickedFile.path);
      Future.delayed(const Duration(milliseconds: 100), () {
        // 滚动到最右边
        uploadScrollController.animateTo(
          uploadScrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 200),
          curve: Curves.easeOut,
        );
      });
    }
    // await PhotoPickerUtil().showPicker(callback: (XFile pickedFile) async {
    //   await LoadingUtil.to.show(status: '上传中...');
    //   try {
    //     String? filename = await MediaUtil().uploadImg(File(pickedFile.path));
    //     if (filename.isNotEmpty) {
    //       final res = await Api.updateAvatar(filename);
    //       if (res.data != null) {
    //         SnackBarUtil().success('上传成功');
    //       }
    //     }
    //     // uploadImgFilePath(pickedFile.path);
    //     Get.back();
    //   } catch (e) {
    //     SnackBarUtil().error('上传失败，请重试');
    //   } finally {
    //     await LoadingUtil.to.dismiss();
    //   }
    // });
  }

  picStartTime(BuildContext context) async {
    var picker =
        await showTimePicker(context: context, initialTime: TimeOfDay.now());
    if (picker != null) {
      startTime.value =
          '${DateUtil.addPrefix(picker.hourOfPeriod.toString())}:${DateUtil.addPrefix(picker.minute.toString())}:${picker.period.name.toUpperCase()}';
    }
  }

  picEndTime(BuildContext context) async {
    var picker =
        await showTimePicker(context: context, initialTime: TimeOfDay.now());
    if (picker != null) {
      endTime.value =
          '${DateUtil.addPrefix(picker.hourOfPeriod.toString())}:${DateUtil.addPrefix(picker.minute.toString())}:${picker.period.name.toUpperCase()}';
    }
  }

  showDatePick() async {
    final picker = await showDatePicker(
        context: Get.context!,
        initialDate: DateTime.now(),
        firstDate: DateTime(2000, 1, 1),
        lastDate: DateTime.now().add(const Duration(days: 7)));
    if (picker != null) {
      pickedDate = picker;
      selectedDate.value =
          '${DateUtil.addPrefix(picker.day.toString())}/${DateUtil.addPrefix(picker.month.toString())}/${picker.year}';
    }
  }

  changeImage(int index) {
    selectedImage.value = index;
  }

  setLabelFocus() {
    labelFocus.value = true;
    categoryFocus.value = false;
    descriptionFocus.value = false;
  }

  setCategoryFocus() {
    labelFocus.value = false;
    categoryFocus.value = true;
    descriptionFocus.value = false;
  }

  setDescriptionFocus() {
    labelFocus.value = false;
    categoryFocus.value = false;
    descriptionFocus.value = true;
  }

  onTapOutside() {
    labelFocus.value = false;
    categoryFocus.value = false;
    descriptionFocus.value = false;
  }

  insertTask(BuildContext context) {
    if (label.value.text.toString().isEmpty) {
      SnackBarUtil().warning(
        'Warning',
        message: 'Enter valid label',
      );
      return;
    }
    if (category.value.text.toString().isEmpty) {
      SnackBarUtil().warning(
        'Warning',
        message: 'Enter Correct Category',
      );
      return;
    }
    if (selectedDate.isEmpty) {
      // selectedDate.value =
      //     '${Utils.addPrefix(DateTime.now().day.toString())}/${Utils.addPrefix(DateTime.now().month.toString())}/${Utils.addPrefix(DateTime.now().year.toString())}';
      showDatePick();
    }
    if (startTime.isEmpty) {
      picStartTime(context);
      return;
    }
    if (endTime.isEmpty) {
      picEndTime(context);
      return;
    }
    loading.value = true;

    // db
    //     .insert(TaskModel(
    //         key: DateTime.now().microsecondsSinceEpoch.toString(),
    //         startTime: startTime.value,
    //         endTime: endTime.value,
    //         date: selectedDate.value,
    //         periority: lowPeriority.value ? 'Low' : 'High',
    //         description: description.value.text.toString(),
    //         category: category.value.text.toString(),
    //         title: label.value.text.toString(),
    //         image: selectedImage.value.toString(),
    //         show: 'yes',
    //         status: 'unComplete'))
    //     .then((value) {
    //   Duration dif = pickedDate!.difference(DateTime(
    //       DateTime.now().year, DateTime.now().month, DateTime.now().day));
    //   inventoryInoutlist[dif.inDays].add(value);
    //   Timer(const Duration(seconds: 1), () {
    //     loading.value = false;
    //     Get.back();
    //     SnackBarUtil().success(
    //       'Successful',
    //       message: 'Task is created',
    //     );
    //   });
    // });
  }
}
