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

import 'package:carousel_slider/carousel_controller.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:eitc_erm_app/select_clinic.dart';
import 'package:eitc_erm_app/select_doctor.dart';
import 'package:eitc_erm_app/select_patient.dart';
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:eitc_erm_app/widget/marquee_widget.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import 'Introduce.dart';
import 'bean/doctor_list.dart';
import 'bean/hospital_detail.dart';
import 'bean/notice_manage_list.dart';
import 'bean/user_info.dart';
import 'doctor_detail.dart';
import 'login.dart';
import 'notice_list.dart';

/*void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(Home());
}*/
late BuildContext parentCxt;

class Home extends StatefulWidget {
  Home(BuildContext context) {
    parentCxt = context;
  }

  @override
  State<StatefulWidget> createState() => HomeState();
}

class HomeState extends State<Home> {
  NoticeManageList mNoticeManageList = new NoticeManageList();
  List<String> noticeList = [" "];

  @override
  void initState() {
    super.initState();
    getInfo();
    noticeManageList();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("${Global.clinic}"),
          centerTitle: true,
          actions: <Widget>[
            IconButton(
                icon: Icon(
                  Icons.loop,
                  color: Colors.black,
                ),
                onPressed: () {
                  Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(
                        builder: (context) => SelectClinic("fromHome")),
                  );
                }),
          ],
        ),
        body: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min, //横向大小
            crossAxisAlignment: CrossAxisAlignment.center, //纵向对齐方式
            children: [
              Banner(),
              Padding(
                  padding: const EdgeInsets.all(10),
                  child: Row(children: [
                    SizedBox(width: 1),
                    Text(
                      '▊',
                      style: const TextStyle(fontSize: 15, color: Colors.blue),
                    ),
                    SizedBox(width: 20),
                    Text(
                      '门诊服务',
                      style: const TextStyle(fontSize: 15),
                    ),
                  ])),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly, //元素与空白互相间隔
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                    child: GestureDetector(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => SelectPatient("")),
                        );
                      },
                      child: Container(
                        color: Colors.greenAccent,
                        width: 160,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            SizedBox(height: 10),
                            Icon(
                              Icons.account_balance_wallet_outlined,
                              color: Colors.green,
                            ),
                            SizedBox(height: 10),
                            Text("预约挂号",
                                style: const TextStyle(
                                    fontSize: 15, color: Colors.green)),
                            SizedBox(height: 10),
                            Text("点击在线预约挂号",
                                style: const TextStyle(
                                    fontSize: 15, color: Colors.green)),
                            SizedBox(height: 10),
                          ],
                        ),
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                    child: GestureDetector(
                      onTap: () {
                        // if(Global.selectDoctor == -1) {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => SelectDoctor("")),
                        );
                        /*} else {
                          */ /*Navigator.push(
                            context,
                            MaterialPageRoute(builder: (context) => ChatHome()),
                          );*/ /*
                          Navigator.push(
                            context,
                            MaterialPageRoute(builder: (context) => OnlineConsultationDetail()),
                          );
                        }*/
                      },
                      child: Container(
                        color: Colors.orange,
                        width: 160,
                        child: Column(children: [
                          SizedBox(height: 10),
                          Icon(
                            Icons.account_balance_wallet_outlined,
                            color: Colors.yellow,
                          ),
                          SizedBox(height: 10),
                          Text("线上咨询",
                              style: const TextStyle(
                                  fontSize: 15, color: Colors.yellow)),
                          SizedBox(height: 10),
                          Text("点击在线咨询医生",
                              style: const TextStyle(
                                  fontSize: 15, color: Colors.yellow)),
                          SizedBox(height: 10),
                        ]),
                      ),
                    ),
                  ),
                ],
              ),
              Padding(
                  padding: const EdgeInsets.only(left: 6),
                  child: Row(children: [
                    Icon(
                      Icons.notifications,
                      color: Colors.lightGreen,
                      size: 18,
                    ),
                    SizedBox(width: 18),
                    Expanded(
                      child: Container(
                        alignment: Alignment.center,
                        width: double.infinity,
                        height: 24,
                        child: noticeList.length > 0
                            ? buildMarqueeWidget(noticeList)
                            : Text(
                                '',
                              ),
                      ),
                    ),
                  ])),
              Padding(
                  padding: const EdgeInsets.all(10),
                  child: Row(
                      // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        SizedBox(width: 1),
                        Text(
                          '▊',
                          style:
                              const TextStyle(fontSize: 15, color: Colors.blue),
                        ),
                        SizedBox(width: 20),
                        Text(
                          '医生推荐',
                          style: const TextStyle(fontSize: 15),
                        ),
                        /*SizedBox(width: 190),
                        Text(
                          '查看更多>>',
                          style:
                              const TextStyle(fontSize: 13, color: Colors.grey),
                        ),*/
                      ])),
              DoctorRecommend(),
            ],
          ),
        ),
      ),
      routes: {
        '/login': (context) => Login(),
      },
    );
  }

  MarqueeWidget buildMarqueeWidget(List<String> loopList) {
    ///上下轮播 安全提示
    return MarqueeWidget(
      //子Item构建器
      itemBuilder: (BuildContext context, int index) {
        String itemStr = loopList[index];
        //通常可以是一个 Text文本
        return GestureDetector(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => NoticeList(mNoticeManageList)),
              );
            },
            child: Text(
              itemStr,
              style: TextStyle(
                fontSize: 16,
                color: Colors.lightGreen,
                fontWeight: FontWeight.w700,
              ),
            ));
      },
      //循环的提示消息数量
      count: loopList.length,
    );
  }

  Future<UserInfo?> getInfo() async {
    print(Global.token);
    final response =
        await http.get(Uri.parse('${Global.BaseUrl}user/getInfo'), headers: {
      HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
      'token': '${Global.token}',
    });
    print("==== " + response.body);
    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      UserInfo mUserInfo = new UserInfo.fromJson(jsonResponse);
      if (mUserInfo.code == Global.responseSuccessCode) {
        final data = mUserInfo.data;
        if (data != null) {
          Global.userId = data.id!;
          Global.userIdentificationCard = data.identificationCard!;
          Global.loginPhoneNo = data.phoneNumber!;
        }
      } else {
        Component.toast(mUserInfo.msg.toString(), 0);
      }
      return mUserInfo;
    } else {
      Component.toast("获取用户信息出错！", 0);
    }
  }

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

    final response = await http.get(
        Uri.parse(Global.BaseUrl + 'notice-manage/list'),
        headers: headers);
    print(response.body.toString());
    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      print(jsonString);
      mNoticeManageList = new NoticeManageList.fromJson(jsonResponse);
      if (mNoticeManageList.code == Global.responseSuccessCode) {
        noticeList.clear();
        for (int i = 0; i < mNoticeManageList.data!.length; i++) {
          String line = mNoticeManageList.data![i].noticeTitle.toString();
          if (line.length > 18) line = line.substring(0, 18) + "...";
          noticeList.add(line);
        }
        setState(() {});
        return mNoticeManageList;
      } else {
        Component.toast(mNoticeManageList.msg.toString(), 0);
      }
      return null;
    } else {
      Component.toast("获取通知出错！", 0);
      return null;
    }
  }
}

class Banner extends StatefulWidget {
  const Banner({super.key});

  @override
  BannerState createState() => BannerState();
}

class BannerState extends State<Banner> {
  HospitalDetail mHospitalDetail = new HospitalDetail();

  @override
  void initState() {
    super.initState();
    fetchHospitalData();
  }

  Future<HospitalDetail?> fetchHospitalData() async {
    print(Global.token);
    final response = await http
        .get(Uri.parse('${Global.BaseUrl}clinic-info/detail'), headers: {
      HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
      'token': '${Global.token}',
    });
    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      print(jsonResponse);
      mHospitalDetail = new HospitalDetail.fromJson(jsonResponse);
      if (mHospitalDetail.code == Global.responseSuccessCode) {
        if (mHospitalDetail.data != null) {
          if (mHospitalDetail.data?.bannerPic1 != null) {
            list[0] =
                Global.ImageUrl + mHospitalDetail.data!.bannerPic1.toString();
          }
          if (mHospitalDetail.data?.bannerPic2 != null) {
            list[1] =
                Global.ImageUrl + mHospitalDetail.data!.bannerPic2.toString();
          }
          if (mHospitalDetail.data?.bannerPic3 != null) {
            list[2] =
                Global.ImageUrl + mHospitalDetail.data!.bannerPic3.toString();
          }
        }
      } else if (mHospitalDetail.code == 401 || mHospitalDetail.code == 403) {
        Navigator.pushReplacementNamed(parentCxt, '/login');
      } else {
        Component.toast(mHospitalDetail.msg.toString(), 0);
      }
      print(list[0] + " " + list[1] + " " + list[2]);
      return mHospitalDetail;
    } else {
      Component.toast("获取顶部滚动条出错！", 0);
    }
  }

  final List list = [
    // "assets/images/banner1.png",
    // "assets/images/banner2.png",
    // "assets/images/banner3.png"
    // mHospitalDetail.data == null ? Global.ServerUrl + "ya.png" : Global.ImageUrl + mHospitalDetail.data!.bannerPic1.toString(),
    Global.ServerUrl + "ya.png",
    Global.ServerUrl + "ya.png",
    Global.ServerUrl + "ya.png"
  ];
  int _current = 0;
  final CarouselController _controller = CarouselController();

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: AlignmentDirectional.bottomCenter,
      children: [
        CarouselSlider.builder(
          carouselController: _controller,
          options: CarouselOptions(
            height: 250,
            autoPlay: true,
            viewportFraction: 1.0,
            autoPlayInterval: const Duration(seconds: 3),
            onPageChanged: (index, reason) {
              setState(() {
                _current = index;
              });
            },
          ),
          itemCount: list.length,
          itemBuilder: (BuildContext context, int index, int pageViewIndex) {
            return GestureDetector(
              onTap: () {
                switch (index) {
                  case 0:
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => Introduce(
                              hospitalDetail: mHospitalDetail,
                              key: new Key(''))),
                    );
                    break;
                  case 1:
                    break;
                  case 2:
                    break;
                }
                print("点我了${index} ${mHospitalDetail.data?.bannerPic1}");
              },
              child: Image.network(
                list[index],
                width: double.infinity,
                fit: BoxFit.fitWidth,
                excludeFromSemantics: true,
                errorBuilder: (context, error, stackTrace) {
                  return Icon(
                    Icons.image,
                    size: 80,
                    color: Colors.grey,
                  ); // 显示一个进度指示器作为错误占位
                },
              ),
              // Image(image: AssetImage(list[index]), fit: BoxFit.fitWidth),
            );
          },
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: list.asMap().entries.map((entry) {
            return GestureDetector(
              onTap: () => _controller.animateToPage(entry.key),
              child: Container(
                width: 10.0,
                height: 10.0,
                margin:
                    const EdgeInsets.symmetric(vertical: 8.0, horizontal: 4.0),
                decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: (Theme.of(context).brightness == Brightness.dark
                            ? Colors.white
                            : Colors.black)
                        .withOpacity(_current == entry.key ? 0.9 : 0.4)),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }
}

DoctorListEntity? data = new DoctorListEntity();

class DoctorRecommend extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => DoctorRecommendState();
}

class DoctorRecommendState extends State<DoctorRecommend> {
  late Future<DoctorListEntity?> _future;
  late BuildContext cxt;

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

  Future<DoctorListEntity?> fetchData() async {
    Map<String, String> headers = {
      'token': '${Global.token}',
    };
    final response =
        await http.get(Uri.parse('${Global.BaseUrl}doctor/list'), headers: {
      HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
      'token': '${Global.token}',
    });
    print(Uri.parse('${Global.BaseUrl}doctor/list'));
    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      print(jsonResponse);
      DoctorListEntity mDoctorListEntity =
          new DoctorListEntity.fromJson(jsonResponse);
      if (mDoctorListEntity.code == Global.responseSuccessCode) {
        return mDoctorListEntity;
      } else if (mDoctorListEntity.code == 401 ||
          mDoctorListEntity.code == 403) {
        Navigator.of(context).pop();
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => Login()),
        );
        return null;
      } else {
        Component.toast(mDoctorListEntity.msg.toString(), 0);
        return null;
      }
    } else {
      Component.toast("出错了，请稍后再试！", 0);
    }
  }

  @override
  Widget build(BuildContext context) {
    cxt = context;
    return MaterialApp(
      home: Container(
        child: Center(
          child: FutureBuilder<DoctorListEntity?>(
            future: _future,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                data = snapshot.data;
                return GridView.builder(
                  padding: const EdgeInsets.all(10),
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    //注意此行
                    crossAxisCount: 2, //每行 widget 数量
                    crossAxisSpacing: 10, //widget 水平之间的距离
                    mainAxisSpacing: 10, //widget 垂直之间的距离
                  ),
                  itemCount: data?.data?.length,
                  // itemCount: 2,
                  itemBuilder: _customWidget,
                );
              } else if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              }
              return ColorLoader();
            },
          ),
        ),
      ),
    );
  }

  Widget _customWidget(BuildContext context, int index) {
    return GestureDetector(
      onTap: () {
        Navigator.push(
          cxt,
          MaterialPageRoute(
              builder: (context) => DoctorDetail(
                  doctorListEntity: data, key: new Key(''), which: index)),
        );
      },
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.circular(8),
          color: Colors.white,
        ),
        child: Column(
          children: [
            const SizedBox(
              height: 10,
            ),
            Image.network(
              // 图片地址
              "${Global.ImageUrl}${data?.data?[index].avatar}",
              width: 50,
              fit: BoxFit.cover,
              excludeFromSemantics: true,
              errorBuilder: (context, error, stackTrace) => Icon(
                Icons.person_pin,
                size: 50,
                color: Colors.grey,
              ),
            ),
            Text(
              '${data?.data?[index].nickName} \n ${data?.data?[index].deptName == null ? "" : data?.data?[index].deptName} ${data?.data?[index].postNames == null ? "" : data?.data?[index].postNames}',
              textAlign: TextAlign.center,
              style: const TextStyle(
                  fontSize: 13,
                  color: Colors.black,
                  decorationColor: Colors.white,
                  fontWeight: FontWeight.normal),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                     if(data!.data![index].doctorProficient != null && data!.data![index].doctorProficient!.split(",").length! > 0)
                  ElevatedButton(
                      style: ButtonStyle(
                        minimumSize: MaterialStateProperty.all(Size(20, 15)),
                        backgroundColor: MaterialStateProperty.all(Colors.blue),
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      ),
                      child: Text(
                        data!.data![index].doctorProficient!.split(",")[0],
                        style:
                            const TextStyle(fontSize: 10, color: Colors.white),
                      ),
                      onPressed: () {},
                    ),
                    if(data!.data![index].doctorProficient != null && data!.data![index].doctorProficient!.split(",").length! > 1)
                    ElevatedButton(
                      style: ButtonStyle(
                        minimumSize: MaterialStateProperty.all(Size(20, 15)),
                        backgroundColor: MaterialStateProperty.all(Colors.blue),
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      ),
                      child: Text(
                        data!.data![index].doctorProficient!.split(",")[1],
                        style:
                            const TextStyle(fontSize: 10, color: Colors.white),
                      ),
                      onPressed: () {},
                    ),
                  ]),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    if(data!.data![index].doctorProficient != null && data!.data![index].doctorProficient!.split(",").length! > 2)
                    ElevatedButton(
                      style: ButtonStyle(
                        minimumSize: MaterialStateProperty.all(Size(20, 15)),
                        backgroundColor: MaterialStateProperty.all(Colors.blue),
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      ),
                      child: Text(
                        data!.data![index].doctorProficient!.split(",")[2],
                        style:
                        const TextStyle(fontSize: 10, color: Colors.white),
                      ),
                      onPressed: () {},
                    ),
                    if(data!.data![index].doctorProficient != null && data!.data![index].doctorProficient!.split(",").length! > 3)
                    ElevatedButton(
                      style: ButtonStyle(
                        minimumSize: MaterialStateProperty.all(Size(20, 15)),
                        backgroundColor: MaterialStateProperty.all(Colors.blue),
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      ),
                      child: Text(
                        data!.data![index].doctorProficient!.split(",")[3],
                        style:
                        const TextStyle(fontSize: 10, color: Colors.white),
                      ),
                      onPressed: () {},
                    ),
                  ]),
            ),
          ],
        ),
      ),
    );
  }
}
