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/models/user_info.model.dart';
import 'package:sk_base_mobile/util/debouncer.dart';
import 'package:sk_base_mobile/util/screen_adaper_util.dart';
import 'package:sk_base_mobile/widgets/empty.dart';
import 'package:sk_base_mobile/widgets/fade_in_cache_image.dart';

class AgentSearch extends StatelessWidget {
  Function(UserInfoModel)? onSelected;
  Function(UserInfoModel)? beforeSelectedCheck;
  AgentSearch({super.key, this.onSelected, this.beforeSelectedCheck});
  final controller = Get.put(AgentSearchController());
  final listTitleTextStyle =
      TextStyle(fontSize: ScreenAdaper.height(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: buildList())
        ],
      ),
    );
  }

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

  Widget buildList() {
    final textStyle = TextStyle(fontSize: ScreenAdaper.height(22));
    return Obx(() => SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        controller: controller.refreshController,
        onLoading: controller.onLoading,
        onRefresh: controller.onRefresh,
        child: controller.refreshController.isLoading
            ? SizedBox()
            : controller.list.isEmpty
                ? Center(
                    child: Empty(text: '暂无数据'),
                  )
                : ListView.separated(
                    separatorBuilder: (context, index) => Divider(
                          color: AppTheme.dividerColor,
                        ),
                    itemCount: controller.list.length,
                    itemBuilder: (_, index) => buildItem(index))));
  }

  Widget buildItem(int index) {
    return InkWell(
      onTap: () => {
        if (beforeSelectedCheck != null)
          {
            if (beforeSelectedCheck!(controller.list[index]))
              {onSelected!(controller.list[index])}
          }
        else
          {onSelected!(controller.list[index])}
      },
      child: Container(
        padding: EdgeInsets.symmetric(
            horizontal: ScreenAdaper.width(5),
            vertical: ScreenAdaper.height(10)),
        child: Row(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(ScreenAdaper.sp(15)),
              child: FadeInCacheImage(
                url: controller.list[index].avatar ?? '',
                width: ScreenAdaper.width(60),
                height: ScreenAdaper.width(60),
              ),
            ),
            SizedBox(
              width: ScreenAdaper.width(20),
            ),
            Text(
              '${controller.list[index].nickname}',
              style: TextStyle(fontSize: ScreenAdaper.height(25)),
            ),
            if (controller.list[index].dept != null) ...[
              SizedBox(
                width: ScreenAdaper.width(20),
              ),
              Container(
                padding: EdgeInsets.symmetric(
                    horizontal: ScreenAdaper.width(10),
                    vertical: ScreenAdaper.height(5)),
                decoration: BoxDecoration(
                    color: Colors.grey[300],
                    borderRadius: BorderRadius.circular(ScreenAdaper.sp(10))),
                child: Text('${controller.list[index].dept?.name}'),
              )
            ]
          ],
        ),
      ),
    );
  }
}

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