import 'dart:convert';

import 'package:farmer_client/pages/home/widgets/home/widgets/headers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../models/app.dart';
import '../../models/entities/CardListModel.dart';
import '../../models/entities/CardTypeModel.dart';
import '../../services/homeAPI.dart';
import '../../widgets/CarsCard.dart';
import '../../widgets/NullCard.dart';
import '../../widgets/Search.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;
  final tabText = Rx<List<CardTypeModel>>([]);
  final classId = Rx<List<dynamic>>([]);
  final cardTypeList = Rx<List<CardListModel>>([]);

  String? location = AppController.t.locationStr;
  late int _selectedIndex;
  bool hasTopLoad = false;
  int index = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = TabController(length: tabText.value.length, vsync: this);
    // _controller.addListener(() {
    //   setState(() => _selectedIndex = _controller.index);
    //   print("liucheng-> ${_controller.indexIsChanging}");
    // });
    _geList();

    _getAllCarsList();
  }

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

//进来拿到全部农机
  void _getAllCarsList() {
    getMachinery(location ?? '112.087465,32.687507').then((value) {
      final list = <CardListModel>[];
      value['records'].forEach((item) {
        list.add(CardListModel.fromJson(item));
      });
      cardTypeList(list);
    });
  }

  //全部农机分类
  void _geList() {
    getMachineryType().then((value) {
      final list = <CardTypeModel>[];
      List classtypeId = [];
      List<CardTypeModel> newTabs = [
        CardTypeModel.fromJson({'name': '全部'})
      ];
      value['records'].forEach((item) {
        list.add(CardTypeModel.fromJson(item));
      });
      list.insertAll(0, newTabs);
      tabText(list);
      tabText().forEach((item) {
        classtypeId.add(item.typeId);
      });
      classId(classtypeId);

      hasTopLoad = true;
      _controller = TabController(length: tabText.value.length, vsync: this);
      print(hasTopLoad);
    });
  }

  void _handleTabChange(i) {
    index = i;
    if (index == 0) {
      _getAllCarsList();
    } else {
      final typeId = classId.value[index];
      print('typeId+$typeId');
      typeMachinery(location ?? '112.087465,32.687507', typeId.toString())
          .then((value) {
        final list = <CardListModel>[];
        value['records'].forEach((item) {
          list.add(CardListModel.fromJson(item));
        });
        cardTypeList(list);

      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        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: BoxDecoration(color: Colors.white),
          child: !hasTopLoad
              ? ListView(children: [
                  Column(
                    children: [
                      Container(
                        padding: EdgeInsets.fromLTRB(0, 15, 0, 15),
                        width: 350.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: tabText.value
                                .map((e) => Tab(text: e.name.toString()))
                                .toList(),
                            onTap: (int i) {
                              _handleTabChange(i);
                            },
                          )),
                      Container(
                        child: Obx(() => Column(
                              children: cardTypeList.value.length > 0
                                  ? cardTypeList()
                                      .map((item) => CarsCard(item: item))
                                      .toList()
                                  : [NullCard(text: '暂无农机信息！')],
                            )),
                      )
                    ],
                  )
                ])
              : Text('加载中...'),
        )));
  }
}
