import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:farmer_client/pages/home/widgets/headers.dart';
import 'package:farmer_client/widgets/CarsCard.dart';
import 'package:farmer_client/widgets/RefreshMoreList.dart';
import 'package:farmer_client/models/app.dart';
import 'package:farmer_client/models/entities/CardListModel.dart';
import 'package:farmer_client/models/entities/CardTypeModel.dart';
import 'package:farmer_client/services/homeAPI.dart';

class MoreCars extends StatefulWidget {
  const MoreCars({Key? key}) : super(key: key);
  @override
  State<MoreCars> createState() => _MoreCarsState();
}

class _MoreCarsState extends State<MoreCars> with TickerProviderStateMixin {
  late TabController _controller;
  String? location = AppController.t.locationStr;

  //农机分类列表
  final typeList = Rx<List<CardTypeModel>>([]);
  //顶部的tab栏是否加载完成标识位
  bool hasTopLoad = false;
  //当前选中项的下标
  int index = 0;
  //当前选中项的类型Id
  String typeId = '';

  //农机列表
  final machineryList = Rx<List<CardListModel>>([]);
  late int maxSum; //最多条数
  Function? Refresh;

  final params = Rx<Map<String, dynamic>>({
    'pageNum': 1,
    'location': AppController.t.locationStr ?? '112.087465,32.687507',
    'typeId': ''
  });

  @override
  void initState() {
    super.initState();
    _controller = TabController(length: typeList.value.length, vsync: this);
    _geList();
  }

  //获取数据
  void _geList() {
    getMachineryType({'pageSize': 500}).then((value) {
      EasyLoading.show(status: '数据加载中...');
      final list = <CardTypeModel>[];
      List<CardTypeModel> newTabs = [
        CardTypeModel.fromJson({'name': '全部'})
      ];
      value['records'].forEach((item) {
        list.add(CardTypeModel.fromJson(item));
      });
      //将全部的选项的农机放到tab栏的第一位
      list.insertAll(0, newTabs);
      typeList(list);
      _controller = TabController(length: typeList.value.length, vsync: this);
      EasyLoading.dismiss();
    });
  }

  //切换农机类型
  void _handleTabChange(i) {
    index = i;
    Map<String, dynamic> map = {...params.value};
    map['pageNum'] = 1;
    if (index == 0) {
      typeId = '';
    } else {
      typeId = typeList.value[index].typeId.toString();
    }
    map['typeId'] = typeId;
    params(map);
    Refresh!();
  }

  List<CardListModel> GetList(value) {
    List<CardListModel> list = [];
    if (value != null)
      value.forEach((item) => {list.add(CardListModel.fromJson(item))});
    return list;
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.transparent,
        foregroundColor: const Color(0xFF333333),
        elevation: 0,
        toolbarHeight: 44.w,
        title: Text(
          '更多',
          style: TextStyle(
              color: const Color(0xFF333333),
              fontWeight: FontWeight.bold,
              fontSize: 17.sp,
              letterSpacing: 2),
        ),
      ),
      body: SafeArea(
        child: Container(
          alignment: Alignment.center,
          decoration: const BoxDecoration(color: Colors.white),
          child: Column(
            children: [
              ListView(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                children: [
                  Container(
                    margin: EdgeInsets.all(15.w),
                    child: TypeHeader(
                      type: false,
                    ),
                  ),
                  Obx(() => TabBar(
                        labelStyle: TextStyle(
                            fontSize: ScreenUtil().setSp(19),
                            fontWeight: FontWeight.bold),
                        //选中的样式
                        unselectedLabelStyle:
                            TextStyle(fontSize: ScreenUtil().setSp(16)),
                        //未选中的样式
                        controller: _controller,
                        isScrollable: true,
                        //可滚动
                        indicatorColor: Colors.black,
                        //指示器的颜色
                        labelColor: Colors.black,
                        //选中文字颜色
                        unselectedLabelColor: Color(0xffadadad),
                        // indicatorSize: TabBarIndicatorSize.label, //指示器与文字等宽
                        tabs: typeList.value
                            .map((e) => Tab(text: e.name.toString()))
                            .toList(),
                        onTap: (int i) {
                          _handleTabChange(i);
                        },
                      )),
                ],
              ),
              Expanded(
                child: _buildListView(context),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildListView(BuildContext context) {
    return RefreshMoreList(
      pPrams: params,
      cardText: '暂无农机',
      fetch: getMachinery,
      useState: (state) {
        machineryList(GetList(state));
      },
      builder: ({required BuildContext context, required Function toggle}) {
        Refresh = toggle;
        return Obx(
          () => Column(
            children: machineryList.value
                .map(
                  (item) => CarsCard(item: item),
                )
                .toList(),
          ),
        );
      },
    );
  }
}
