import 'dart:io';

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/utils/logger.dart';
import 'package:eitc_erm_app/widget/line.dart';
import 'package:eitc_erm_app/widget/user_header.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import 'bean/doctor_list.dart';
import 'bean/favourite_doctor_list.dart';
import 'bean/normal_response.dart';
import 'confirm_registration.dart';
import 'online_consultation.dart';

/*void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(DoctorDetail());
}*/
late DoctorListEntity mDoctorListEntity = new DoctorListEntity();
int mWhich = 0;
String selectDateStr = "";
String halfHourLater = "";
FavouriteDoctorListEntity mFavouriteDoctorListEntity =
    new FavouriteDoctorListEntity();

class DoctorDetail extends StatefulWidget {
  DoctorDetail({required Key key, required doctorListEntity, which})
      : super(key: key) {
    mDoctorListEntity = doctorListEntity;
    mWhich = which;
    logd(mDoctorListEntity.data![mWhich].userId.toString() +
        " =====================");
  }

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

class DoctorDetailState extends State<DoctorDetail> {
  List<Widget> widgetList = [];

  @override
  void initState() {
    super.initState();
    fetchData();

    String? doctorProficient = mDoctorListEntity.data?[mWhich].doctorProficient;
    List<String>? doctorProficientList = doctorProficient?.split(',');
    if (doctorProficientList != null) {
      for (var i = 0; i < doctorProficientList.length; i++) {
        widgetList.add(
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 6.0, vertical: 2.0),
            decoration: BoxDecoration(
                color: Colors.lightBlueAccent,
                borderRadius: BorderRadius.circular(30)),
            child: Text(
              ' ${doctorProficientList[i]} ',
              style: const TextStyle(
                fontSize: 10,
                color: Colors.white,
              ),
              textAlign: TextAlign.center,
            ),
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('医生详情',
            style: TextStyle(
              color: Colors.white,
            )),
        centerTitle: true,
        elevation: 0.5,
        backgroundColor: Global.StatusBarColor,
        leading: IconButton(
          tooltip: '返回上一页',
          icon: const Icon(
            Icons.arrow_back_ios,
            color: Colors.white,
          ),
          onPressed: () {
            Navigator.of(context).pop();
            //_nextPage(-1);
          },
        ),
      ),
      body: Container(
        padding: const EdgeInsets.all(10),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Row(mainAxisSize: MainAxisSize.max, children: [
            Padding(
              padding: const EdgeInsets.only(left: 10, top: 10, right: 10),
              child: SizedBox.fromSize(
                size: const Size.square(60),
                child: UserHeader(
                  url:
                      "${Global.ImageUrl}${mDoctorListEntity.data?[mWhich].avatar}",
                ),
              ),
            ),
            const SizedBox(
              width: 5,
            ),
            Expanded(
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  '${mDoctorListEntity.data?[mWhich].nickName}',
                                  style: const TextStyle(fontSize: 18),
                                ),
                                const SizedBox(
                                  width: 10,
                                ),
                                Text(
                                  mDoctorListEntity.data?[mWhich].postNames ??
                                      "",
                                  style: const TextStyle(
                                      fontSize: 15, color: Colors.brown),
                                ),
                              ]),
                          const Spacer(),
                          if (mDoctorListEntity.data?[mWhich].isCollection == 0)
                            GestureDetector(
                                child: const Icon(
                                  Icons.favorite_border,
                                  color: Colors.grey,
                                ),
                                onTap: () {
                                  collectDoctor();
                                }),
                          if (mDoctorListEntity.data?[mWhich].isCollection == 1)
                            GestureDetector(
                                child: const Icon(
                                  Icons.favorite,
                                  color: Colors.red,
                                ),
                                onTap: () {
                                  cancelCollectDoctor();
                                }),
                        ]),
                    Container(
                      padding: const EdgeInsets.only(top: 5),
                      alignment: Alignment.centerLeft,
                      width: double.infinity,
                      child: Text(
                        '服务人数：${mDoctorListEntity.data?[mWhich].receivePatientNum}人',
                        style:
                            const TextStyle(fontSize: 15, color: Colors.grey),
                      ),
                    ),
                  ]),
            ),
          ]),
          Padding(
            padding: const EdgeInsets.all(10),
            child: Text(
              mDoctorListEntity.data?[mWhich].doctorBlurb ?? "简介：暂无。",
              style: const TextStyle(color: Colors.grey),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(10),
            child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
              const Text(
                '擅长：',
                style: TextStyle(color: Colors.grey),
              ),
              widgetList.isEmpty
                  ? const Text(
                      "暂无。",
                      style: TextStyle(color: Colors.grey),
                    )
                  : Expanded(
                      child: Wrap(
                      direction: Axis.horizontal,
                      spacing: 5.0,
                      runSpacing: 5.0,
                      children: widgetList,
                    )),
            ]),
          ),
          Line(),
          const Padding(
            padding: EdgeInsets.all(10),
            child: Text(
              '服务项目',
              style: TextStyle(fontSize: 18, color: Colors.black),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                const Row(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Icon(
                      Icons.collections_bookmark,
                      color: Colors.blue,
                      size: 35,
                    ),
                    SizedBox(width: 10),
                    Text('图文咨询',
                        style:
                            TextStyle(color: Colors.deepPurple, fontSize: 20)),
                  ],
                ),
                ElevatedButton(
                  style: ButtonStyle(
                    backgroundColor:
                        WidgetStateProperty.resolveWith<Color>((states) {
                      return Colors.orange; // Regular color
                    }),
                  ),
                  onPressed: () {
                    if (Global.selectPatient != -1) {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => OnlineConsultation()),
                      );
                    } else {
                      Component.toast("请先选择就诊人", 1);
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                SelectPatient("fromDoctorDetail")),
                      );
                    }
                  },
                  child: const Text("问诊",
                      style: TextStyle(color: Colors.white, fontSize: 15)),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                const Row(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Icon(
                      Icons.reddit_outlined,
                      color: Colors.blue,
                      size: 35,
                    ),
                    SizedBox(width: 10),
                    Text('挂号预约',
                        style:
                            TextStyle(color: Colors.deepPurple, fontSize: 20)),
                  ],
                ),
                ElevatedButton(
                  style: ButtonStyle(
                    backgroundColor:
                        WidgetStateProperty.resolveWith<Color>((states) {
                      return Colors.blue; // Regular color
                    }),
                  ),
                  onPressed: () async {
                    if (Global.selectPatient != -1) {
                      if (selectDateStr.isEmpty) {
                        Component.toast("请选择预约时间", 0);
                        _showDatePicker(0);
                        return;
                      }
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => ConfirmRegistration(
                                  visitTime: selectDateStr,
                                  visitTimeEnd: halfHourLater,
                                  userListEntity: Global.patient,
                                  whichPatient: Global.selectPatient,
                                  doctorListEntity: mDoctorListEntity,
                                  key: const Key(''),
                                  which: mWhich)));
                    } else {
                      Component.toast("请先选择就诊人", 1);
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                SelectPatient("fromDoctorDetail")),
                      );
                    }
                  },
                  child: const Text("挂号",
                      style: TextStyle(color: Colors.white, fontSize: 15)),
                ),
              ],
            ),
          ),
        ]),
      ),
    );
  }

  Future<void> collectDoctor() async {
    var params = {
      "avatar": mDoctorListEntity.data?[mWhich].avatar,
      "briefIntroduction": mDoctorListEntity.data?[mWhich].doctorBlurb,
      "doctorId": mDoctorListEntity.data?[mWhich].userId,
      "doctorName": mDoctorListEntity.data?[mWhich].nickName,
      "label": "",
      "postName": mDoctorListEntity.data?[mWhich].postNames
    };
    var response = await http.post(
        Uri.parse(
            '${Global.BaseUrl}collection-doctor/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 = new NormalResponse.fromJson(json);
      if (mNormalResponse.code == Global.responseSuccessCode) {
        Component.toast("收藏成功！", 2);
        setState(() {
          mDoctorListEntity.data?[mWhich].isCollection = 1;
        });
      } else {
        Component.toast(mNormalResponse.msg.toString(), 0);
      }
    } else {
      Component.toast("出错了，请稍后再试！", 0);
      return null;
    }
  }

  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);
    if (response.statusCode == 200) {
      final json = decodeBodyToJson(response.bodyBytes);
      logd("收藏的医生列表=$json");
      mFavouriteDoctorListEntity = 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;
    }
  }

  Future<void> cancelCollectDoctor() async {
    var params = {
      "avatar": mDoctorListEntity.data?[mWhich].avatar,
      "briefIntroduction": mDoctorListEntity.data?[mWhich].doctorBlurb,
      "doctorId": mDoctorListEntity.data?[mWhich].userId,
      "doctorName": mDoctorListEntity.data?[mWhich].nickName,
      "label": "",
      "postName": mDoctorListEntity.data?[mWhich].postNames
    };
    var response = await http.post(
        Uri.parse(
            '${Global.BaseUrl}collection-doctor/cancel-collect-doctor'),
        body: encodeBody(params),
        headers: jsonHeaders(withToken: true));
    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(() {
          mDoctorListEntity.data?[mWhich].isCollection = 0;
        });
      } else {
        Component.toast(mNormalResponse.msg.toString(), 0);
      }
    } else {
      Component.toast("出错了，请稍后再试！", 0);
      return null;
    }
  }

  void _showDatePicker(int addDay) async {
    DateTime dateTime = DateTime(
        DateTime.now().year,
        DateTime.now().month,
        DateTime.now().day + addDay,
        DateTime.now().minute > 30
            ? DateTime.now().hour + 1
            : DateTime.now().hour,
        DateTime.now().minute > 30 ? 0 : 30);
    // 默认时间
    selectDateStr = dateTime.toString().replaceAll(":00.000", "");
    halfHourLater = dateTime
        .add(const Duration(minutes: 30))
        .toString()
        .replaceAll(":00.000", "");
    // 显示对话框
    await showCupertinoModalPopup<void>(
      context: context,
      builder: (BuildContext context) {
        return Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              SizedBox(height: 500),
              Expanded(
                child: Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(10),
                          topRight: Radius.circular(10)),
                      color: Colors.white),
                  child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Padding(
                          padding: const EdgeInsets.fromLTRB(30, 10, 30, 0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Material(
                                color: Colors.grey,
                                borderRadius: BorderRadius.circular(5),
                                child: InkWell(
                                  onTap: () {
                                    selectDateStr = "";
                                    Navigator.of(context).pop();
                                  },
                                  child: Container(
                                      height: 30,
                                      width: 50,
                                      alignment: Alignment.center,
                                      child: Text(
                                        "取消",
                                        style: TextStyle(
                                          color: Colors.white,
                                        ),
                                      )),
                                ),
                              ),
                              Material(
                                color: Colors.green,
                                borderRadius: BorderRadius.circular(5),
                                child: InkWell(
                                  onTap: () {
                                    Navigator.of(context).pop();
                                  },
                                  child: Container(
                                      height: 30,
                                      width: 50,
                                      alignment: Alignment.center,
                                      child: Text(
                                        "确定",
                                        style: TextStyle(
                                          color: Colors.white,
                                        ),
                                      )),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Expanded(
                          child: CupertinoDatePicker(
                            mode: CupertinoDatePickerMode.dateAndTime,
                            // 日期选择器模式 `time`,`date`,`dateAndTime`, 默认`dateAndTime`
                            initialDateTime: DateTime(
                                DateTime.now().year,
                                DateTime.now().month,
                                DateTime.now().day + addDay,
                                DateTime.now().minute > 30
                                    ? DateTime.now().hour + 1
                                    : DateTime.now().hour,
                                DateTime.now().minute > 30 ? 0 : 30),
                            // 初始化日期
                            minimumDate: DateTime(2024, 07, 09),
                            // 最小可选日期
                            maximumDate: DateTime(2025, 07, 22),
                            // 最大可选日期
                            minimumYear: 2024,
                            // 最小年份
                            maximumYear: 2025,
                            // 最大年份
                            minuteInterval: 30,
                            // 分钟间隔  initialDateTime.minute 必须可以整除 minuteInterval 必须是 60 的整数因子
                            use24hFormat: true,
                            // 是否使用24小时制
                            dateOrder: DatePickerDateOrder.dmy,
                            // 日期选择器排序方式 默认年/月/日
                            backgroundColor: Colors.white,
                            // 选中日期变化回调
                            onDateTimeChanged: (dateTime) {
                              logd(dateTime);
                              selectDateStr =
                                  dateTime.toString().replaceAll(":00.000", "");
                              halfHourLater = dateTime
                                  .add(const Duration(minutes: 30))
                                  .toString()
                                  .replaceAll(":00.000", "");
                              // _chooseDateTime = dateTime;
                            },
                          ),
                        ),
                      ]),
                ),
              ),
            ]);
      },
    );
  }
}
