import 'package:flutter/material.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';
import 'package:flyinsono/lab/components/data_container/data_grid_item.dart';
import 'package:flyinsono/lab/components/data_container/data_list_item.dart';
import 'package:flyinsono/lab/components/fixed_height_grid_delegate.dart';
import 'package:flyinsono/lab/components/selection_rect/selection_rect.dart';
import 'package:flyinsono/lab/components/view_mode_switcher/view_mode_switcher.dart';
import 'package:flyinsono/lab/pages/lab_import/controller.dart';
import 'package:flyinsono/lab/style/lab_box_decoration.dart';
import 'package:get/get.dart';

class DataSelector extends GetView<LabImportController> {
  const DataSelector({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      clipBehavior: Clip.hardEdge,
      decoration: LabBoxDecoration.base,
      padding: const EdgeInsets.all(15),
      child: Column(
        children: [
          Container(
            height: 40,
            child: Row(
              children: [
                // Text(
                //   "筛选：",
                //   overflow: TextOverflow.ellipsis,
                //   style: TextStyle(
                //     fontSize: 13,
                //     fontWeight: FontWeight.bold,
                //     color: LabColors.text600,
                //   ),
                // ),
                Obx(
                  () => controller.state.isTableRefreshing
                      ? Text(
                          "全部数据（0）",
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 13,
                            fontWeight: FontWeight.bold,
                            color: LabColors.text800,
                          ),
                        )
                      : Text(
                          "全部数据（${controller.importData.length}）",
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 13,
                            fontWeight: FontWeight.bold,
                            color: LabColors.text800,
                          ),
                        ),
                ),
                Expanded(child: Container()),
                Text(
                  "排序：",
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.bold,
                    color: LabColors.text600,
                  ),
                ),
                Text(
                  "时间倒序",
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.bold,
                    color: LabColors.text800,
                  ),
                ),
                SizedBox(width: 20),
                GetBuilder<LabImportController>(
                  id: LabImportController.viewModeSwitcherId,
                  builder: (_) {
                    return ViewModeSwitcher(
                      viewMode: controller.viewMode,
                      onModeChanged: (mode) {
                        controller.changeViewMode(mode);
                      },
                    );
                  },
                ),
              ],
            ),
          ),
          SizedBox(height: 15),
          Expanded(
            child: GetBuilder<LabImportController>(
              id: LabImportController.importDataViewId,
              builder: (_) {
                if (controller.viewMode == ViewMode.list) {
                  return _buildProjectDataInListView();
                }
                return _buildProjectDataInGridView();
              },
            ),
          ),
        ],
      ),
    );
  }

  // 以 3 列的形式展示项目数据
  Widget _buildProjectDataInGridView() {
    return Obx(() => SelectionRect(
          scrollController: controller.dataViewScrollController,
          dataLayoutType: DataLayoutType.Grid,
          itemHeight: 60,
          columnCount: 4,
          xSpacing: 10,
          ySpacing: 10,
          rightPadding: 10,
          onSelectionUpdating: (indexs) {
            controller.setItemHightlight(indexs);
          },
          onSelectionEnd: (indexs) {
            controller.setItemHightlight({});
            indexs.removeWhere((element) =>
                element < 0 || element >= controller.importData.length);
            if (indexs.every(
                (element) => controller.selectedIndex.contains(element))) {
              controller.setItemSelectStatus(indexs, false);
              return;
            }
            controller.setItemSelectStatus(indexs, true);
          },
          child: controller.state.isTableRefreshing
              ? Expanded(
                  child: SizedBox.square(
                  dimension: 40,
                  child: Center(
                    child: Padding(
                      padding: const EdgeInsets.all(0),
                      child: CircularProgressIndicator(
                        strokeWidth: 2.5,
                        color: LabColors.base600,
                      ),
                    ),
                  ),
                ))
              : GridView.builder(
                  shrinkWrap: true,
                  controller: controller.dataViewScrollController,
                  padding: EdgeInsets.only(right: 10),
                  gridDelegate: FixedHeightGridDelegate(
                    crossAxisCount: 4,
                    crossAxisSpacing: 10,
                    mainAxisSpacing: 10,
                    height: 60, //48 dp of height
                  ),
                  itemCount: controller.importData.length,
                  itemBuilder: (BuildContext context, int index) {
                    return _buildDataGridItem(index);
                  },
                ),
        ));
  }

  // 以数据行的形式展示项目数据
  Widget _buildProjectDataInListView() {
    return Obx(() => Column(
          children: [
            DataListTitle(
              title: "样品名称",
              selectable: true,
            ),
            Expanded(
              child: SelectionRect(
                scrollController: controller.dataViewScrollController,
                dataLayoutType: DataLayoutType.List,
                itemHeight: 40,
                onSelectionUpdating: (indexs) {
                  controller.setItemHightlight(indexs);
                },
                onSelectionEnd: (indexs) {
                  controller.setItemHightlight({});
                  indexs.removeWhere((element) =>
                      element < 0 || element >= controller.importData.length);
                  if (indexs.every((element) =>
                      controller.selectedIndex.contains(element))) {
                    controller.setItemSelectStatus(indexs, false);
                    return;
                  }
                  controller.setItemSelectStatus(indexs, true);
                },
                child: controller.state.isTableRefreshing
                    ? Expanded(
                        child: SizedBox.square(
                        dimension: 40,
                        child: Center(
                          child: Padding(
                            padding: const EdgeInsets.all(0),
                            child: CircularProgressIndicator(
                              strokeWidth: 2.5,
                              color: LabColors.base600,
                            ),
                          ),
                        ),
                      ))
                    : ListView.builder(
                        shrinkWrap: true,
                        controller: controller.dataViewScrollController,
                        itemCount: controller.importData.length,
                        itemExtent: 40,
                        itemBuilder: (BuildContext context, int index) {
                          return _buildDataListItem(index);
                        },
                      ),
              ),
            ),
          ],
        ));
  }

  Widget _buildDataGridItem(int index) {
    return DataGridItem(
      projectDataName: controller.importData[index].sampleDataName!,
      projectDataId: controller.importData[index].sampleDataID!,
      projectDataFileSize: controller.importData[index].sampleDataSize!,
      onClick: () {
        controller.clickDataItem(index);
      },
      selectable: true,
      selected: controller.selectedIndex.contains(index),
      highlighted: controller.hightlightedIndex.contains(index),
      onCheckBoxChanged: (value) {
        if (value != null) {
          controller.setItemSelectStatus({index}, value);
        }
      },
    );
  }

  Widget _buildDataListItem(int index) {
    return DataListItem(
      projectDataName: controller.importData[index].sampleDataName!,
      projectDataId: controller.importData[index].sampleDataID!,
      projectDataFileSize: controller.importData[index].sampleDataSize!,
      onClick: () {
        controller.clickDataItem(index);
      },
      selectable: true,
      selected: controller.selectedIndex.contains(index),
      highlighted: controller.hightlightedIndex.contains(index),
      onCheckBoxChanged: (value) {
        if (value != null) {
          controller.setItemSelectStatus({index}, value);
        }
      },
    );
  }
}
