import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sk_base_mobile/apis/index.dart';
import 'package:sk_base_mobile/app_theme.dart';
import 'package:sk_base_mobile/constants/enum.dart';
import 'package:sk_base_mobile/db_helper/dbHelper.dart';
import 'package:sk_base_mobile/screens/inventory_inout/components/inventory_inout_info.dart';
import 'package:sk_base_mobile/screens/new_inventory_inout/new_inventory_inout.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/modal.util.dart';
import 'package:sk_base_mobile/util/screen_adaper_util.dart';
import '../../models/index.dart';
import 'components/responsive.dart';

class InventoryInoutController extends GetxController {
  RxMap userData = {}.obs;
  RxInt currentIndex = 0.obs;
  final PageController pageController = PageController();
  final DateTime dateTime = DateTime.now();
  final DbHelper db = DbHelper();
  List<RxList<InventoryInOutModel>> list = [
    <InventoryInOutModel>[].obs,
    <InventoryInOutModel>[].obs,
    <InventoryInOutModel>[].obs,
    <InventoryInOutModel>[].obs,
    <InventoryInOutModel>[].obs,
    <InventoryInOutModel>[].obs,
    <InventoryInOutModel>[].obs,
  ].obs;
  RxInt barIndex = 0.obs;
  RxList model = [].obs;
  final ScrollController scrollController = ScrollController();
  final daysNum = 20;
  @override
  void onInit() {
    super.onInit();
    getData();
  }

  Future<void> changePage(int index) async {
    LoggerUtil()
        .info(DateUtil.format(DateTime.now().add(Duration(days: -index))));
  }

  /// 打开出库还是入库选择框
  Future<void> showInOrOutPickerDialog() async {
    showDialog(
      context: Get.overlayContext!,
      builder: (_) => Align(
          alignment: Alignment.center,
          widthFactor: 1,
          heightFactor: 1,
          child: SizedBox(
              width: ScreenAdaper.width(1000),
              height: ScreenAdaper.height(500),
              child: TweenAnimationBuilder(
                curve: Curves.easeInOut,
                tween: Tween<double>(begin: 0, end: 1),
                duration: const Duration(milliseconds: 200),
                builder: (context, value, child) {
                  return Stack(
                    alignment: Alignment.center,
                    children: [
                      AnimatedPositioned(
                        duration: const Duration(milliseconds: 100),
                        left: value * 80,
                        child: ClipRRect(
                          borderRadius:
                              const BorderRadius.all(Radius.circular(30)),
                          child: Material(
                            child: Ink(
                              decoration: BoxDecoration(
                                gradient: LinearGradient(
                                  colors: [Colors.green[300]!, Colors.green],
                                ),
                                borderRadius:
                                    const BorderRadius.all(Radius.circular(30)),
                              ),
                              child: ElevatedButton(
                                onPressed: () {
                                  Get.back();
                                  showInventoryInoutCreateDialog(
                                      InventoryInOrOutEnum.In);
                                },
                                style: ButtonStyle(
                                  backgroundColor: MaterialStateProperty.all(
                                      Colors.transparent),
                                  shadowColor: MaterialStateProperty.all(
                                      Colors.transparent),
                                  shape: MaterialStateProperty.all(
                                    const RoundedRectangleBorder(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(30)),
                                    ),
                                  ),
                                  padding: MaterialStateProperty.all(
                                      EdgeInsets.zero),
                                ),
                                child: Container(
                                  height: ScreenAdaper.height(350),
                                  width: ScreenAdaper.height(350),
                                  alignment: Alignment.center,
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Icon(
                                        Icons.add_circle_outline,
                                        color: AppTheme.nearlyWhite,
                                        size: ScreenAdaper.sp(80),
                                      ),
                                      SizedBox(
                                        height: ScreenAdaper.height(10),
                                      ),
                                      Text(
                                        '入库',
                                        style: TextStyle(
                                          decoration: TextDecoration.none,
                                          color: AppTheme.nearlyWhite,
                                          fontSize: ScreenAdaper.sp(60),
                                          letterSpacing: ScreenAdaper.width(5),
                                          fontWeight: FontWeight.w700,
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                      AnimatedPositioned(
                        duration: const Duration(milliseconds: 100),
                        right: value * 80,
                        child: ClipRRect(
                          borderRadius:
                              const BorderRadius.all(Radius.circular(30)),
                          child: Material(
                            child: Ink(
                              decoration: BoxDecoration(
                                gradient: LinearGradient(
                                  colors: [Colors.red[300]!, Colors.red],
                                ),
                                borderRadius:
                                    const BorderRadius.all(Radius.circular(30)),
                              ),
                              child: ElevatedButton(
                                onPressed: () {
                                  Get.back();
                                  showInventoryInoutCreateDialog(
                                      InventoryInOrOutEnum.Out);
                                },
                                style: ButtonStyle(
                                  backgroundColor: MaterialStateProperty.all(
                                      Colors.transparent),
                                  shadowColor: MaterialStateProperty.all(
                                      Colors.transparent),
                                  shape: MaterialStateProperty.all(
                                    const RoundedRectangleBorder(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(30)),
                                    ),
                                  ),
                                  padding: MaterialStateProperty.all(
                                      EdgeInsets.zero),
                                ),
                                child: Container(
                                  height: ScreenAdaper.height(350),
                                  width: ScreenAdaper.height(350),
                                  alignment: Alignment.center,
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Icon(
                                        Icons.remove_circle_outline,
                                        color: AppTheme.nearlyWhite,
                                        size: ScreenAdaper.sp(80),
                                      ),
                                      SizedBox(
                                        height: ScreenAdaper.height(10),
                                      ),
                                      Text(
                                        '出库',
                                        style: TextStyle(
                                          decoration: TextDecoration.none,
                                          color: AppTheme.nearlyWhite,
                                          fontSize: ScreenAdaper.sp(60),
                                          letterSpacing: ScreenAdaper.width(5),
                                          fontWeight: FontWeight.w700,
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  );
                },
              ))),
    );
  }

  /// 打开新建库存出入库对话框
  Future showInventoryInoutCreateDialog(int inOrOut) async {
    final isTablet = Responsive.isTablet(Get.context!);
    return isTablet
        ? Get.generalDialog(
            barrierLabel: "CreateInventoryInout",
            barrierDismissible: true,
            transitionDuration: const Duration(milliseconds: 400),
            pageBuilder: (_, __, ___) {
              return NewInventoryInout(
                inOrOut: inOrOut,
              );
            },
            transitionBuilder: (_, anim, __, child) {
              Tween<Offset> tween;
              tween = Tween(begin: const Offset(0, -1), end: Offset.zero);
              return SlideTransition(
                position: tween.animate(
                  CurvedAnimation(parent: anim, curve: Curves.easeInOut),
                ),
                child: child,
              );
            },
          ).then((value) {
            if (value != null) {
              getData();
            }
          })
        : showModalBottomSheet(
            elevation: 0,
            isScrollControlled: true,
            backgroundColor: Colors.white,
            context: Get.overlayContext!,
            builder: (context) {
              return NewInventoryInout(inOrOut: inOrOut);
            },
          );
  }

  Future showInventoryInoutInfoDialog(int id) async {
    ModalUtil.showGeneralDialog(
            width: ScreenAdaper.width(Get.width - 100),
            height: ScreenAdaper.height(Get.height - 100),
            content: InventoryInoutInfo(inventoryInoutId: id))
        .then((value) => {Get.delete<InventoryInouInfoController>()});
  }

  Future<List<InventoryInOutModel>> getInoutHistory() async {
    final res = await Api.getInventoryInout({});
    printInfo(info: res.toString());
    if (res.data != null) {
      return res.data!.items
          .map((e) => InventoryInOutModel.fromJson(e))
          .toList();
    }
    return [];
    // final List<Map<String, Object?>> queryResult =
    //     await dbClient!.query('Tasks');
    // return queryResult.map((e) => TaskModel.fromMap(e)).toList();
  }

  getData() async {
    getInoutHistory().then((value) {
      model.value = value;
      getSepretLists();
    });
  }

  setIndex(int value) {
    pageController.animateToPage(value,
        duration: const Duration(milliseconds: 300), curve: Curves.easeIn);
    currentIndex.value = value;
  }

  getDateAccordingTabs(int value) {
    return DateUtil.format(dateTime.add(Duration(days: -(daysNum - value))));
  }

  getSepretLists() {
    List<RxList<InventoryInOutModel>> tempList = [];
    for (int i = daysNum; i > 0; i--) {
      RxList<InventoryInOutModel> tempList1 = <InventoryInOutModel>[].obs;
      tempList1.clear();
      for (int j = 0; j < model.length; j++) {
        final sourceDateStr = DateUtil.format(model[j].time);
        final currentDateStr = getDateAccordingTabs(i);
        if (sourceDateStr == currentDateStr) {
          tempList1.add(model[j]);
        }
      }
      tempList.add(tempList1);
    }
    list.assignAll(tempList);
  }

  onMoveNextPage() {
    if (currentIndex.value > 0) {
      setIndex(currentIndex.value - 1);
    }
  }

  onMoveBack() {
    if (currentIndex.value < 20) {
      setIndex(currentIndex.value + 1);
    }
  }

  onTaskComplete(
      int value, int index, int ind, String key, BuildContext context) {
    switch (value) {
      case 3:
      // {
      //   ModalUtil.showWarningDialog('Complete Task',
      //       'This task will be marked as completed', 'Confirm', () {
      //     list[ind][index].status = 'complete';
      //     list[ind].add('');
      //     list[ind].remove('');
      //     db.update(key, 'status', 'complete');
      //   });
      // }
      case 2:
        {
          ModalUtil.showWarningDialog(
              'Delete Task', 'Are you want to sure to remove', 'Confirm', () {
            list[ind].remove(list[ind][index]);
            db.delete(
              key,
              'Tasks',
            );
          });
        }
    }
  }
}
