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/util/debouncer.dart';
import 'package:sk_base_mobile/util/screen_adaper_util.dart';

class ProductSearch extends StatelessWidget {
  Function(ProductModel)? onProductSelected;
  ProductSearch({super.key, this.onProductSelected});
  final controller = Get.put(ProductSearchController());
  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,
          ),
          Row(
            children: [
              Text(
                '产品编号',
                style: listTitleTextStyle,
              ),
              Expanded(
                  child: Text(
                '名称',
                textAlign: TextAlign.center,
                style: listTitleTextStyle,
              )),
              Text(
                '规格',
                style: listTitleTextStyle,
              )
            ],
          ),
          Expanded(child: buildProductList())
        ],
      ),
    );
  }

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

    return Row(
      children: [
        Expanded(
            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),
                  ),
                ))),
      ],
    );
  }

  Widget buildProductList() {
    return Obx(
      () => SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        controller: controller.refreshController,
        onLoading: controller.onLoading,
        onRefresh: controller.onRefresh,
        child: ListView.separated(
            itemCount: controller.products.length,
            separatorBuilder: (context, index) => const Divider(
                  height: 1,
                  color: AppTheme.dividerColor,
                ),
            itemBuilder: (context, index) {
              final itemData = controller.products[index];
              return InkWell(
                onTap: () {
                  if (onProductSelected != null) onProductSelected!(itemData);
                },
                child: Container(
                  padding:
                      EdgeInsets.symmetric(vertical: ScreenAdaper.height(10)),
                  child: Row(
                    children: [
                      Container(
                        //最小宽度
                        constraints:
                            BoxConstraints(minWidth: ScreenAdaper.width(100)),
                        child: Text(
                          itemData.productNumber!,
                          style: TextStyle(fontSize: ScreenAdaper.sp(20)),
                        ),
                      ),
                      SizedBox(
                        width: ScreenAdaper.width(10),
                      ),
                      Expanded(
                          child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '${itemData.name}',
                            style: TextStyle(fontSize: ScreenAdaper.sp(20)),
                          ),
                          Text(
                            '${itemData.company?.name}',
                            style: TextStyle(
                                fontSize: ScreenAdaper.sp(15),
                                color: AppTheme.grey),
                          )
                        ],
                      )),
                      SizedBox(
                        width: ScreenAdaper.width(10),
                      ),
                      Container(
                        //最小宽度
                        constraints:
                            BoxConstraints(minWidth: ScreenAdaper.width(100)),
                        child: Text(itemData.productSpecification ?? ''),
                      )
                    ],
                  ),
                ),
              );
            }),
      ),
    );
  }
}

class ProductSearchController extends GetxController {
  RxList<ProductModel> products = RxList([]);
  RxString searchKey = ''.obs;
  final searchBarTextConroller = TextEditingController();
  RefreshController refreshController = RefreshController(initialRefresh: true);
  int page = 1;
  int limit = 15;
  int total = 0;
  Future<List<ProductModel>> getData({bool isRefresh = false}) async {
    if (isRefresh == true) {
      page = 1;
    } else {
      page++;
    }
    final res = await Api.getProducts(
        {'page': page, 'pageSize': 30, 'keyword': searchKey.value});
    List<ProductModel> newList =
        res.data!.items.map((e) => ProductModel.fromJson(e)).toList();
    isRefresh == true ? products.assignAll(newList) : products.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();
    });
  }
}
