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';
import 'package:sk_base_mobile/widgets/core/zt_search_select.dart';
import 'package:sk_base_mobile/widgets/empty.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.height(25), fontWeight: FontWeight.w600);
  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.symmetric(
            horizontal: ScreenAdaper.width(20),
            vertical: ScreenAdaper.height(20)),
        child: GestureDetector(
          onTap: () {
            FocusScope.of(context).unfocus();
          },
          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: Obx(() => 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: controller.searchKey.value.isEmpty
                      ? null
                      : IconButton(
                          icon: const Icon(Icons.clear),
                          onPressed: () {
                            controller.searchKey.value = '';
                            controller.searchBarTextConroller.clear();
                            doSearch('');
                          },
                        ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                )))),
        SizedBox(
          width: ScreenAdaper.width(5),
        ),
        buildProjectPicker(),
        SizedBox(
          width: ScreenAdaper.width(5),
        ),
        buildHasInventoryPicker()
      ],
    );
  }

  // 项目选择
  Widget buildProjectPicker() {
    return Container(
        width: ScreenAdaper.width(250),
        constraints: BoxConstraints(minWidth: ScreenAdaper.width(250)),
        child: Obx(
          () => DropdownButtonFormField<int>(
              value: controller.projectId.value,
              isExpanded: true,
              items: [
                DropdownMenuItem(
                  child: Text('所有项目'),
                  value: 0,
                ),
                ...controller.projects.map((element) => DropdownMenuItem(
                    child: Text('${element.name}'), value: element.id))
              ],
              onChanged: (value) {
                controller.projectId.value = value;
                controller.refreshController.requestRefresh();
              },
              decoration: InputDecoration(
                contentPadding: EdgeInsets.symmetric(
                    vertical: ScreenAdaper.height(15),
                    horizontal: ScreenAdaper.width(15)),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(ScreenAdaper.sp(15)),
                ),
              )),
        ));
    // return Container(
    //     width: ScreenAdaper.width(200),
    //     constraints: BoxConstraints(minWidth: ScreenAdaper.width(200)),
    //     child: ZtSearchSelect<ProjectModel>(
    //         isRequired: true,
    //         contentPadding:
    //             EdgeInsets.symmetric(horizontal: ScreenAdaper.width(15)),
    //         textController: controller.projectTextController,
    //         hintText: '请选择所属项目',
    //         itemBuilder: (_, itemData) => Container(
    //             padding: EdgeInsets.symmetric(
    //                 vertical: ScreenAdaper.height(15),
    //                 horizontal: ScreenAdaper.width(20)),
    //             child: Text(
    //               '${itemData.name}',
    //               style: TextStyle(fontSize: ScreenAdaper.height(20)),
    //             )),
    //         suggestionsCallback: (String keyword) {
    //           return controller.getProjects(keyword: keyword);
    //         },
    //         onClear: () {
    //           controller.projectId = null;
    //         },
    //         onSelected: (ProjectModel project) {
    //           controller.projectTextController.text = project.name ?? '';
    //           controller.projectId = project.id;
    //         }));
  }

  Widget buildHasInventoryPicker() {
    return Container(
        width: ScreenAdaper.width(200),
        constraints: BoxConstraints(minWidth: ScreenAdaper.width(200)),
        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.refreshController.requestRefresh();
              },
              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.height(25));
    return Obx(() => SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        controller: controller.refreshController,
        onLoading: controller.onLoading,
        onRefresh: controller.onRefresh,
        child: controller.refreshController.isLoading
            ? SizedBox()
            : controller.inventories.isEmpty
                ? Center(
                    child: Empty(text: '暂无库存'),
                  )
                : !ScreenAdaper.isLandspace()
                    ? buildPortraitList()
                    : Table(columnWidths: {
                        0: MinColumnWidth(
                            FixedColumnWidth(80), FixedColumnWidth(80)),
                        1: MinColumnWidth(
                            FixedColumnWidth(
                                ScreenAdaper.screenShortDistance() / 5),
                            FixedColumnWidth(
                                ScreenAdaper.screenShortDistance() / 5)),
                        2: FlexColumnWidth(
                            ScreenAdaper.screenShortDistance() / 4),
                        3: FlexColumnWidth(
                            ScreenAdaper.screenShortDistance() / 4),
                        4: MinColumnWidth(
                            FixedColumnWidth(
                                ScreenAdaper.screenShortDistance() / 5),
                            FixedColumnWidth(
                                ScreenAdaper.screenShortDistance() / 5)),
                        5: MinColumnWidth(
                            FixedColumnWidth(
                                ScreenAdaper.screenShortDistance() / 6),
                            FixedColumnWidth(
                                ScreenAdaper.screenShortDistance() / 6)),
                      }, 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(
                                  '单价',
                                  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.project?.name}',
                                          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.height(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 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: AbsorbPointer(
            child: Container(
                constraints: BoxConstraints(minHeight: ScreenAdaper.height(80)),
                alignment: alignment ?? Alignment.centerLeft,
                child: child)),
      ),
    );
  }

  Widget buildPortraitList() {
    return ListView.separated(
        itemBuilder: (_, index) {
          final itemData = controller.inventories[index];
          return InkWell(
              onTap: () {
                if (beforeSelectedCheck != null) {
                  if (!beforeSelectedCheck!(itemData)) {
                    return;
                  }
                }
                if (onInventorySelected != null) onInventorySelected!(itemData);
              },
              child: Container(
                child: Row(children: [
                  Text(
                    '${itemData.inventoryNumber}',
                    style: TextStyle(fontSize: ScreenAdaper.sp(40)),
                  ),
                  SizedBox(
                    width: ScreenAdaper.width(10),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '${itemData.product?.name}${itemData.product?.productSpecification != '' ? '(${itemData.product?.productSpecification})' : ''}',
                        style: TextStyle(fontSize: ScreenAdaper.sp(40)),
                      ),
                      Text(
                        '${itemData.product?.company?.name}',
                        style: TextStyle(
                            fontSize: ScreenAdaper.sp(30),
                            color: AppTheme.grey),
                      ),
                      Text('￥${double.parse('${itemData.unitPrice}')}',
                          style: TextStyle(
                              fontSize: ScreenAdaper.sp(30),
                              color: AppTheme.grey))
                    ],
                  ),
                  Spacer(),
                  Text(
                      '${itemData.quantity}${itemData.product?.unit?.label ?? ''}',
                      style: TextStyle(fontSize: ScreenAdaper.sp(40))),
                ]),
              ));
        },
        separatorBuilder: (_, index) => Divider(
              color: AppTheme.dividerColor,
            ),
        itemCount: controller.inventories.length);
  }
}

class InventorySearchController extends GetxController {
  RxList<InventoryModel> inventories = RxList([]);
  final projectTextController = TextEditingController();
  RxString searchKey = ''.obs;
  final searchBarTextConroller = TextEditingController();
  RefreshController refreshController = RefreshController(initialRefresh: true);
  int page = 1;
  int limit = 15;
  int total = 0;
  RxInt hasInventoryStatus = RxInt(1);
  RxList<ProjectModel> projects = <ProjectModel>[].obs;
  RxnInt projectId = RxnInt(0);
  @override
  onReady() {
    super.onReady();
    getProjects();
  }

  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,
      'projectId': projectId.value == 0 ? null : projectId.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<List<ProjectModel>> getProjects({String? keyword}) async {
    final res =
        await Api.getProjects({'page': 1, 'pageSize': 10, 'name': keyword});
    if (res.data != null) {
      projects.assignAll(
          res.data!.items.map((e) => ProjectModel.fromJson(e)).toList());
    }
    return projects;
  }

  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();
    });
  }
}
