import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sk_base_mobile/apis/index.dart';
import 'package:sk_base_mobile/app_theme.dart';
import 'package:sk_base_mobile/constants/bg_color.dart';
import 'package:sk_base_mobile/models/index.dart';
import 'package:sk_base_mobile/models/inventory.model.dart';
import 'package:sk_base_mobile/util/debouncer.dart';
import 'package:sk_base_mobile/util/screen_adaper_util.dart';

class InventorySearch extends StatelessWidget {
  Function(InventoryModel)? onInventorySelected;
  Function(InventoryModel)? beforeSelectedCheck;
  InventorySearch(
      {super.key, this.onInventorySelected, this.beforeSelectedCheck});
  final controller = Get.put(InventorySearchController());
  final listTitleTextStyle =
      TextStyle(fontSize: ScreenAdaper.sp(20), fontWeight: FontWeight.w600);
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(
          horizontal: ScreenAdaper.width(20),
          vertical: ScreenAdaper.height(20)),
      child: Column(
        children: [
          buildSearchBar(),
          SizedBox(
            height: ScreenAdaper.height(defaultPadding) / 2,
          ),
          Expanded(child: buildInventoryList())
        ],
      ),
    );
  }

  Widget buildSearchBar() {
    final doSearch = debouncer((String value) {
      controller.searchKey.value = value;
      controller.onRefresh();
    }, delayTime: 500);

    return Row(
      children: [
        Expanded(
            flex: 5,
            child: TextField(
                controller: controller.searchBarTextConroller,
                onChanged: (value) => doSearch(value),
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.symmetric(
                      vertical: ScreenAdaper.height(10),
                      horizontal: ScreenAdaper.width(10)),
                  hintText: '名称，编号，规格',
                  floatingLabelBehavior: FloatingLabelBehavior.always,
                  prefixIcon: const Icon(Icons.search),
                  // 当searchBarController有值时不显示
                  suffixIcon: Obx(() => controller.searchKey.value.isEmpty
                      ? const SizedBox()
                      : IconButton(
                          icon: const Icon(Icons.clear),
                          onPressed: () {
                            controller.searchKey.value = '';
                            controller.searchBarTextConroller.clear();
                            doSearch('');
                          },
                        )),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                ))),
        SizedBox(
          width: ScreenAdaper.width(20),
        ),
        buildHasInventoryPicker()
      ],
    );
  }

  Widget buildHasInventoryPicker() {
    return Container(
        width: ScreenAdaper.width(150),
        constraints: BoxConstraints(minWidth: ScreenAdaper.width(150)),
        child: Obx(
          () => DropdownButtonFormField(
              value: controller.hasInventoryStatus.value,
              items: [
                DropdownMenuItem(
                  child: Text('全部'),
                  value: 0,
                ),
                DropdownMenuItem(
                  child: const Text('有库存'),
                  value: 1,
                ),
                DropdownMenuItem(
                  child: const Text('无库存'),
                  value: 2,
                ),
              ],
              onChanged: (value) {
                controller.hasInventoryStatus.value = value!;
                controller.onRefresh();
              },
              decoration: InputDecoration(
                contentPadding: EdgeInsets.symmetric(
                    vertical: ScreenAdaper.height(15),
                    horizontal: ScreenAdaper.width(15)),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(ScreenAdaper.sp(15)),
                ),
              )),
        ));
  }

  Widget buildInventoryList() {
    final textStyle = TextStyle(fontSize: ScreenAdaper.sp(22));
    return Obx(() => SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        controller: controller.refreshController,
        onLoading: controller.onLoading,
        onRefresh: controller.onRefresh,
        child: Table(columnWidths: {
          0: FixedColumnWidth(100),
          1: FlexColumnWidth(2),
          2: MinColumnWidth(FixedColumnWidth(200), FixedColumnWidth(200)),
          3: MinColumnWidth(FixedColumnWidth(100), FixedColumnWidth(100)),
          4: MinColumnWidth(FixedColumnWidth(80), FixedColumnWidth(80)),
        }, children: [
          // table header
          TableRow(
              decoration: BoxDecoration(
                  border:
                      Border(bottom: BorderSide(color: AppTheme.dividerColor))),
              children: [
                TableCell(
                    verticalAlignment: TableCellVerticalAlignment.middle,
                    child: Container(
                      alignment: Alignment.centerLeft,
                      height: ScreenAdaper.height(60),
                      child: Text(
                        '库存编号',
                        style: listTitleTextStyle,
                      ),
                    )),
                TableCell(
                    verticalAlignment: TableCellVerticalAlignment.middle,
                    child: Text(
                      '产品名称',
                      style: listTitleTextStyle,
                    )),
                TableCell(
                  verticalAlignment: TableCellVerticalAlignment.middle,
                  child: Text(
                    '规格',
                    style: listTitleTextStyle,
                  ),
                ),
                TableCell(
                  verticalAlignment: TableCellVerticalAlignment.middle,
                  child: Text(
                    '单价',
                    style: listTitleTextStyle,
                  ),
                ),
                TableCell(
                  verticalAlignment: TableCellVerticalAlignment.middle,
                  child: Text(
                    '数量',
                    textAlign: TextAlign.right,
                    style: listTitleTextStyle,
                  ),
                ),
              ]),
          ...controller.inventories.map((itemData) {
            return TableRow(
                decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(color: AppTheme.dividerColor))),
                children: [
                  buildTableCell(
                      Text(
                        itemData.inventoryNumber!,
                        style: textStyle,
                      ),
                      itemData: itemData),
                  buildTableCell(
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '${itemData.product?.name}',
                            style: textStyle,
                          ),
                          Text(
                            '${itemData.product?.company?.name}',
                            style: TextStyle(
                                fontSize: ScreenAdaper.sp(15),
                                color: AppTheme.grey),
                          )
                        ],
                      ),
                      itemData: itemData),
                  // 规格
                  buildTableCell(
                      Text(itemData.product?.productSpecification ?? '',
                          style: textStyle),
                      itemData: itemData),
                  // 单价
                  buildTableCell(
                      Text(
                        '￥${double.parse('${itemData.unitPrice}')}',
                        style: textStyle,
                      ),
                      itemData: itemData),

                  // 库存数量
                  buildTableCell(
                      Text(
                          '${itemData.quantity}${itemData.product?.unit?.label ?? ''}',
                          textAlign: TextAlign.right,
                          style: textStyle),
                      itemData: itemData,
                      alignment: Alignment.centerRight),
                ]);
          }).toList()
        ])));
  }

  Widget buildInventoryList1() {
    final textStyle = TextStyle(fontSize: ScreenAdaper.sp(22));
    return Obx(
      () => SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        controller: controller.refreshController,
        onLoading: controller.onLoading,
        onRefresh: controller.onRefresh,
        child: ListView.separated(
            itemCount: controller.inventories.length,
            separatorBuilder: (context, index) => const Divider(
                  height: 1,
                  color: AppTheme.dividerColor,
                ),
            itemBuilder: (context, index) {
              final itemData = controller.inventories[index];
              return InkWell(
                onTap: () {
                  if (onInventorySelected != null)
                    onInventorySelected!(itemData);
                },
                child: Container(
                  padding:
                      EdgeInsets.symmetric(vertical: ScreenAdaper.height(10)),
                  child: Row(
                    children: [
                      Container(
                        //最小宽度
                        constraints:
                            BoxConstraints(minWidth: ScreenAdaper.width(100)),
                        child: Text(
                          itemData.inventoryNumber!,
                          style: textStyle,
                        ),
                      ),
                      SizedBox(
                        width: ScreenAdaper.width(10),
                      ),
                      Expanded(
                          flex: 8,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '${itemData.product?.name}',
                                style: textStyle,
                              ),
                              Text(
                                '${itemData.product?.company?.name}',
                                style: TextStyle(
                                    fontSize: ScreenAdaper.sp(15),
                                    color: AppTheme.grey),
                              )
                            ],
                          )),
                      SizedBox(
                        width: ScreenAdaper.width(10),
                      ),
                      // 规格
                      Expanded(
                          child: Container(
                        constraints:
                            BoxConstraints(minWidth: ScreenAdaper.width(100)),
                        child: Text(
                            itemData.product?.productSpecification ?? '',
                            style: textStyle),
                      )),
                      SizedBox(
                        width: ScreenAdaper.width(10),
                      ),
                      // 单价
                      Container(
                        constraints:
                            BoxConstraints(minWidth: ScreenAdaper.width(100)),
                        child: Text(
                            '￥${double.parse('${itemData.unitPrice}')}${double.parse('${itemData.unitPrice}')}${double.parse('${itemData.unitPrice}')}${double.parse('${itemData.unitPrice}')}',
                            style: textStyle),
                      ),
                      SizedBox(
                        width: ScreenAdaper.width(10),
                      ),
                      // 库存数量
                      Expanded(
                          child: Container(
                        alignment: Alignment.centerRight,
                        constraints:
                            BoxConstraints(minWidth: ScreenAdaper.width(80)),
                        child: Text(
                            '${itemData.quantity}${itemData.quantity}${itemData.product?.unit?.label ?? ''}',
                            style: textStyle),
                      ))
                    ],
                  ),
                ),
              );
            }),
      ),
    );
  }

  Widget buildTableCell(Widget child,
      {required InventoryModel itemData, AlignmentGeometry? alignment}) {
    return TableCell(
      verticalAlignment: TableCellVerticalAlignment.middle,
      child: InkWell(
        onTap: () {
          if (beforeSelectedCheck != null) {
            if (!beforeSelectedCheck!(itemData)) {
              return;
            }
          }
          if (onInventorySelected != null) onInventorySelected!(itemData);
        },
        child: Container(
            constraints: BoxConstraints(minHeight: ScreenAdaper.height(80)),
            alignment: alignment ?? Alignment.centerLeft,
            child: child),
      ),
    );
  }
}

class InventorySearchController extends GetxController {
  RxList<InventoryModel> inventories = RxList([]);
  RxString searchKey = ''.obs;
  final searchBarTextConroller = TextEditingController();
  RefreshController refreshController = RefreshController(initialRefresh: true);
  int page = 1;
  int limit = 15;
  int total = 0;
  RxInt hasInventoryStatus = RxInt(1);
  Future<List<InventoryModel>> getData({bool isRefresh = false}) async {
    if (isRefresh == true) {
      page = 1;
    } else {
      page++;
    }
    final res = await Api.getInventory({
      'page': page,
      'pageSize': 15,
      'keyword': searchKey.value,
      'isCreateInout': true,
      'isHasInventory': hasInventoryStatus.value,
    });
    List<InventoryModel> newList =
        res.data!.items.map((e) => InventoryModel.fromJson(e)).toList();
    isRefresh == true
        ? inventories.assignAll(newList)
        : inventories.addAll(newList);

    return newList;
  }

  Future<void> onRefresh() async {
    await getData(isRefresh: true).then((_) {
      refreshController.refreshCompleted(resetFooterState: true);
    }).catchError((_) {
      refreshController.refreshFailed();
    });
  }

  Future<void> onLoading() async {
    await getData().then((_) {
      if (_.isEmpty) {
        refreshController.loadNoData();
      } else {
        refreshController.loadComplete();
      }
    }).catchError((_) {
      refreshController.loadFailed();
    });
  }
}
