import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

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

import 'bean/favourite_doctor_list.dart';
import 'bean/message_box_s_list_entity.dart';
import 'bean/normal_response.dart';
import 'bean/pda_patrol_time_list.dart';
import 'doctor_detail.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);
    print(response.body.toString());
    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      print(jsonString);
      FavouriteDoctorListEntity mFavouriteDoctorListEntity =
          new FavouriteDoctorListEntity.fromJson(jsonResponse);
      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 MaterialApp(
      home: 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(
                        margin: const EdgeInsets.all(8),
                        width: double.infinity,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(3.0),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black54,
                              offset: Offset(5.0, 5.0),
                              blurRadius: 5.0,
                            ),
                          ],
                        ),
                        child: ListTile(
                          title: Row(mainAxisSize: MainAxisSize.max, children: [
                            Padding(
                              padding: const EdgeInsets.all(10),
                              child: Image.network(
                                // 图片地址
                                "${Global.ImageUrl}${data!.data![index].avatar}",
                                width: 60,
                                fit: BoxFit.cover,
                                excludeFromSemantics: true,
                                errorBuilder: (context, error, stackTrace) => Icon(
                                  Icons.person_pin,
                                  size: 60,
                                  color: Colors.grey,
                                ),
                              ),
                            ),
                        Expanded(
                            flex: 4,
                            child:
                            Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                mainAxisSize: MainAxisSize.max,
                                children: [
                                  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),
                                              ),
                                              SizedBox(
                                                width: 5,
                                              ),
                                              Text(
                                                data!.data![index].postName
                                                    .toString(),
                                                style: const TextStyle(
                                                    fontSize: 15,
                                                    color: Colors.grey),
                                              ),
                                            ]),
                                        SizedBox(width: 75),
                                        GestureDetector(
                                            child: Icon(
                                              Icons.favorite,
                                              color: Colors.red,
                                            ),
                                            onTap: () {
                                              cancelCollectDoctor(data, mWhich);
                                            }),
                                      ]),
                                  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: EdgeInsets.fromLTRB(20, 0, 20, 0),
                              child:
                                    Text(
                                      data!.data![index].briefIntroduction == null ? "简介：暂无。" : data!.data![index].briefIntroduction
                                          .toString(),
                                      style: const TextStyle(
                                          fontSize: 10, color: Colors.grey),
                                    ),
                                  ),
                          onTap: () {
                            /*Navigator.push(
                          context,
                          MaterialPageRoute(builder: (context) => DoctorDetail()),
                        );*/
                          },
                        ),
                      );

                  },
                );
              } else if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              }
              return 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
    };

    Map<String, String> headers = {
      HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
      'token': '${Global.token}',
    };
    var response = await http.post(
        Uri.parse(Global.BaseUrl +
            'collection-doctor/cancel-collect-doctor?doctorId=' +
            mFavouriteDoctorListEntity.data![mWhich].doctorId.toString()),
        body: jsonEncode(params),
        headers: headers);
    print(response.body.toString());
    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      print(jsonString);
      NormalResponse mNormalResponse =
          new NormalResponse.fromJson(jsonResponse);
      if (mNormalResponse.code == Global.responseSuccessCode) {
        Component.toast("取消成功！", 2);
        Navigator.of(context).pop();
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => MyDoctor()),
        );
      } else {
        Component.toast(mNormalResponse.msg.toString(), 0);
      }
    } else {
      Component.toast("出错了，请稍后再试！", 0);
      return null;
    }
  }
}
