import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sk_base_mobile/app_theme.dart';
import 'package:sk_base_mobile/db_helper/dbHelper.dart';
import 'package:sk_base_mobile/screens/new_inventory_inout/new_inventory_inout.dart';
import 'package:sk_base_mobile/screens/new_inventory_inout/new_inventory_inout_controller.dart';
import 'package:sk_base_mobile/util/date.util.dart';
import 'package:sk_base_mobile/util/modal.util.dart';
import 'package:sk_base_mobile/util/screen_adaper_util.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> list = [
    [].obs,
    [].obs,
    [].obs,
    [].obs,
    [].obs,
    [].obs,
    [].obs,
  ].obs;
  RxInt barIndex = 0.obs;
  RxList model = [].obs;
  final ScrollController scrollController = ScrollController();

  /// 打开出库还是入库选择框
  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: BorderRadius.all(Radius.circular(30)),
                          child: Material(
                            child: Ink(
                              decoration: BoxDecoration(
                                gradient: LinearGradient(
                                  colors: [Colors.green[300]!, Colors.green],
                                ),
                                borderRadius:
                                    BorderRadius.all(Radius.circular(30)),
                              ),
                              child: ElevatedButton(
                                onPressed: () {
                                  Get.back();
                                  showInventoryInoutCreateDialog('in');
                                },
                                style: ButtonStyle(
                                  backgroundColor: MaterialStateProperty.all(
                                      Colors.transparent),
                                  shadowColor: MaterialStateProperty.all(
                                      Colors.transparent),
                                  shape: MaterialStateProperty.all(
                                    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('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<void> showInventoryInoutCreateDialog(String inOrOut) async {
    final isTablet = Responsive.isTablet(Get.context!);
    isTablet
        ? showGeneralDialog(
            context: Get.overlayContext!,
            barrierLabel: "CreateInventoryInout",
            barrierDismissible: true,
            transitionDuration: const Duration(milliseconds: 400),
            pageBuilder: (_, __, ___) {
              return Container(
                margin: EdgeInsets.symmetric(
                    horizontal: ScreenAdaper.width(100),
                    vertical: ScreenAdaper.height(60)),
                child: ClipRRect(
                    borderRadius: BorderRadius.circular(30),
                    child: Material(child: NewInventoryInout())),
              );
            },
            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) => Get.delete<NewInventoryInoutController>())
        : showModalBottomSheet(
            elevation: 0,
            isScrollControlled: true,
            backgroundColor: Colors.white,
            context: Get.overlayContext!,
            builder: (context) {
              return NewInventoryInout(inOrOut: inOrOut);
            },
          );
  }

  getTasks() async {
    db.getData().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.addPrefix(dateTime.add(Duration(days: value)).day.toString())}/${DateUtil.addPrefix(dateTime.add(Duration(days: value)).month.toString())}/${DateUtil.addPrefix(dateTime.add(Duration(days: value)).year.toString())}';
  }

  getSepretLists() {
    List<RxList<dynamic>> tempList = [];
    for (int i = 0; i < 7; i++) {
      RxList tempList1 = [].obs;
      tempList1.clear();
      for (int j = 0; j < model.length; j++) {
        if (model[j].date == getDateAccordingTabs(i)) {
          tempList1.add(model[j]);
        }
      }
      tempList.add(tempList1);
    }
    list = tempList;
  }

  onMoveNextPage() {
    if (currentIndex.value < 7) {
      setIndex(currentIndex.value + 1);
    }
  }

  onMoveBack() {
    if (currentIndex.value > 0) {
      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',
            );
          });
        }
    }
  }
}
