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/api.dart';
import 'package:sk_base_mobile/constants/enum.dart';
import 'package:sk_base_mobile/db_helper/db_help.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/loading_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>();
  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;
  final inventoryInoutController = Get.find<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 uploadProductImgFilesPath = <String>[].obs;
  final uploadAgentImgFilesPath = <String>[].obs;
  // final uploadImgFilesPath = <String>[].obs
  final productUploadScrollController = ScrollController();
  final agentUploadScrollController = 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 = SkDateUtil.format(DateTime.now());
    payload['time'] = SkDateUtil.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().error(
        '项目不能为空',
      );
      return;
    }
    if (payload['productId'] == null) {
      SnackBarUtil().error(
        '产品不能为空',
      );
      return;
    }
    // 暂时时间定位提交时间
    // if (payload['time'] == null) {
    //   SnackBarUtil().error(
    //     '时间不能为空',
    //   );
    //   return;
    // }

    payload['time'] = SkDateUtil.format(DateTime.now(), formats: [
      'yyyy',
      '-',
      'mm',
      '-',
      'dd',
      ' ',
      'HH',
      ':',
      'nn',
      ":",
      'ss'
    ]);
    payload['quantity'] = quantityTextController.text;

    if (payload['quantity'].isEmpty || payload['quantity'] == '0') {
      SnackBarUtil().error(
        '数量必须大于1',
      );
      return;
    }
    payload['agent'] = agentTextController.text;
    if (payload['agent'].isEmpty) {
      SnackBarUtil().error(
        '经办人不能为空',
      );
      return;
    }
    if (uploadProductImgFilesPath.isEmpty) {
      SnackBarUtil().error(
        '请上传产品照片',
      );
      return;
    }
    if (uploadAgentImgFilesPath.isEmpty) {
      SnackBarUtil().error(
        '请上传经办人照片',
      );
      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;
    await LoadingUtil.to.show(status: '提交中请稍后...');
    // uploadImgFilesPath

    try {
      // final recordId = res.data as int;
      // 批量同时上传
      final uploadRes = await Future.wait([
        ...uploadProductImgFilesPath,
        ...uploadAgentImgFilesPath
      ]
          .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 {
      LoadingUtil.to.dismiss();
    }
  }

  Future<void> photoPicker(String type) async {
    XFile? pickedFile =
        await MediaUtil().getImageFromCamera(isFront: type == 'agent');
    if (pickedFile != null) {
      if (type == 'product') {
        uploadProductImgFilesPath.add(pickedFile.path);
        Future.delayed(const Duration(milliseconds: 100), () {
          // 滚动到最右边
          productUploadScrollController.animateTo(
            productUploadScrollController.position.maxScrollExtent,
            duration: const Duration(milliseconds: 200),
            curve: Curves.easeOut,
          );
        });
      } else {
        uploadAgentImgFilesPath.add(pickedFile.path);
        Future.delayed(const Duration(milliseconds: 100), () {
          // 滚动到最右边
          agentUploadScrollController.animateTo(
            agentUploadScrollController.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 =
          '${SkDateUtil.addPrefix(picker.hourOfPeriod.toString())}:${SkDateUtil.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 =
          '${SkDateUtil.addPrefix(picker.hourOfPeriod.toString())}:${SkDateUtil.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 =
          '${SkDateUtil.addPrefix(picker.day.toString())}/${SkDateUtil.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().error(
      //   'Warning',
      //   message: 'Enter valid label',
      // );
      // return;
    }
    if (category.value.text.toString().isEmpty) {
      // SnackBarUtil().error(
      //   '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;
    }

    // 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',
    //     );
    //   });
    // });
  }
}
