import 'dart:io';

import 'package:eitc_erm_app/utils/Component.dart';
import 'package:eitc_erm_app/utils/Constants.dart';
import 'package:eitc_erm_app/utils/logger.dart';
import 'package:eitc_erm_app/widget/loading.dart';
import 'package:eitc_erm_app/widget/user_header.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import 'bean/favourite_doctor_list.dart';
import 'bean/normal_response.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyDoctor());
}

class MyDoctor extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyDoctorState();
}

class MyDoctorState extends State<MyDoctor> {
  ValueNotifier<dynamic> result = ValueNotifier(null);
  late Future<FavouriteDoctorListEntity?> _future;

  @override
  void initState() {
    super.initState();
    _future = fetchData();
  }

  Future<FavouriteDoctorListEntity?> fetchData() async {
    Map<String, String> headers = {
      'token': Global.token,
    };

    final response = await http.get(
        Uri.parse('${Global.BaseUrl}collection-doctor/list'),
        headers: headers);
    logd(response.body.toString());
    if (response.statusCode == 200) {
      final json = decodeBodyToJson(response.bodyBytes);
      logd("收藏的医生列表=$json");
      FavouriteDoctorListEntity mFavouriteDoctorListEntity =
          new FavouriteDoctorListEntity.fromJson(json);
      if (mFavouriteDoctorListEntity.code == Global.responseSuccessCode) {
        return mFavouriteDoctorListEntity;
      } else {
        Component.toast(mFavouriteDoctorListEntity.msg.toString(), 0);
      }
      return null;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text('收藏的医生',
            style: TextStyle(
              color: Colors.white,
            )),
        centerTitle: true,
        elevation: 0.5,
        backgroundColor: Global.StatusBarColor,
        leading: new IconButton(
          tooltip: '返回上一页',
          icon: const Icon(
            Icons.arrow_back_ios,
            color: Colors.white,
          ),
          onPressed: () {
            Navigator.of(context).pop();
            //_nextPage(-1);
          },
        ),
      ),
      body: Center(
        child: FutureBuilder<FavouriteDoctorListEntity?>(
          future: _future,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              FavouriteDoctorListEntity? data = snapshot.data;
              return ListView.builder(
                itemCount: data?.data?.length,
                itemBuilder: (context, index) {
                  return Container(
                    color: Colors.white,
                    margin: const EdgeInsets.all(8),
                    width: double.infinity,
                    child: ListTile(
                      title: Row(mainAxisSize: MainAxisSize.max, children: [
                        Padding(
                          padding: const EdgeInsets.all(10),
                          child: UserHeader(
                            url:
                                "${Global.ImageUrl}${data!.data![index].avatar}",
                          ),
                        ),
                        Expanded(
                          child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              mainAxisSize: MainAxisSize.max,
                              children: [
                                const SizedBox(
                                  height: 20,
                                ),
                                Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          textBaseline: TextBaseline.alphabetic,
                                          children: [
                                            Text(
                                              data.data![index].doctorName
                                                  .toString(),
                                              style:
                                                  const TextStyle(fontSize: 18),
                                            ),
                                            const SizedBox(
                                              width: 5,
                                            ),
                                            Text(
                                              data!.data![index].postName
                                                  .toString(),
                                              style: const TextStyle(
                                                  fontSize: 15,
                                                  color: Colors.grey),
                                            ),
                                          ]),
                                      const Spacer(),
                                      GestureDetector(
                                          child: const Icon(
                                            Icons.favorite,
                                            color: Colors.red,
                                          ),
                                          onTap: () {
                                            cancelCollectDoctor(data, index);
                                          }),
                                    ]),
                                const SizedBox(
                                  height: 30,
                                ),
                                /*Row(children: [
                                    ElevatedButton(
                                      style: ButtonStyle(
                                        padding: MaterialStateProperty.all(
                                            EdgeInsets.all(3)),
                                        minimumSize:
                                        MaterialStateProperty.all(Size.zero),
                                        backgroundColor:
                                        MaterialStateProperty.all(Colors.blue),
                                      ),
                                      child: Text(
                                        '传统整形',
                                        style: const TextStyle(
                                            fontSize: 8, color: Colors.white),
                                      ),
                                      onPressed: () {},
                                    ),
                                    ElevatedButton(
                                      style: ButtonStyle(
                                        padding: MaterialStateProperty.all(
                                            EdgeInsets.all(3)),
                                        minimumSize:
                                        MaterialStateProperty.all(Size.zero),
                                        backgroundColor:
                                        MaterialStateProperty.all(Colors.blue),
                                      ),
                                      child: Text(
                                        '隐形校正',
                                        style: const TextStyle(
                                            fontSize: 8, color: Colors.white),
                                      ),
                                      onPressed: () {},
                                    ),
                                    ElevatedButton(
                                      style: ButtonStyle(
                                        backgroundColor:
                                        MaterialStateProperty.all(Colors.blue),
                                        padding: MaterialStateProperty.all(
                                            EdgeInsets.all(3)),
                                        minimumSize:
                                        MaterialStateProperty.all(Size.zero),
                                      ),
                                      child: Text(
                                        '反颌（地包天）',
                                        style: const TextStyle(
                                            fontSize: 8, color: Colors.white),
                                      ),
                                      onPressed: () {},
                                    ),
                                  ]),*/
                              ]),
                        ),
                      ]),
                      subtitle: Padding(
                        padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                        child: Text(
                          data!.data![index].briefIntroduction == null
                              ? "简介：暂无。"
                              : data!.data![index].briefIntroduction.toString(),
                          style: const TextStyle(color: Colors.grey),
                        ),
                      ),
                      onTap: () {
                        //这里doctor_list里的Data和favourite_doctor_list里的Data字段对应不上
                        //无法从Global.doctor中找到doctor_list的Data
                        /*Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => DoctorDetail(
                                    key: const Key(""),
                                    doctorListEntity: Global.doctor,
                                    which: index,
                                  )),
                        );*/
                      },
                    ),
                  );
                },
              );
            } else if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}');
            }
            return const ColorLoader();
          },
        ),
      ),
    );
  }

  Future<void> cancelCollectDoctor(
      FavouriteDoctorListEntity mFavouriteDoctorListEntity, int mWhich) async {
    var params = {
      "avatar": mFavouriteDoctorListEntity.data?[mWhich].avatar,
      "briefIntroduction":
          mFavouriteDoctorListEntity.data?[mWhich].briefIntroduction,
      "doctorId": mFavouriteDoctorListEntity.data?[mWhich].doctorId,
      "doctorName": mFavouriteDoctorListEntity.data?[mWhich].doctorName,
      "label": mFavouriteDoctorListEntity.data?[mWhich].label,
      "postName": mFavouriteDoctorListEntity.data?[mWhich].postName
    };

    var response = await http.post(
        Uri.parse(
            '${Global.BaseUrl}collection-doctor/cancel-collect-doctor'),
        body: encodeBody(params),
        headers: jsonHeaders(withToken: true));
    logd(response.body.toString());
    if (response.statusCode == 200) {
      final json = decodeBodyToJson(response.bodyBytes);
      logd("取消收藏医生结果=json");
      NormalResponse mNormalResponse = NormalResponse.fromJson(json);
      if (mNormalResponse.code == Global.responseSuccessCode) {
        Component.toast("取消成功！", 2);
        setState(() {
          _future = fetchData();
        });
      } else {
        Component.toast(mNormalResponse.msg.toString(), 0);
      }
    } else {
      Component.toast("出错了，请稍后再试！", 0);
      return null;
    }
  }

  void _gotoDectorDetail(Data data) {}
}
