import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:eitc_erm_app/chat/chat_home.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/circular_loading.dart';
import 'package:eitc_erm_app/widget/image_error.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:permission_handler/permission_handler.dart';

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

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

class OnlineConsultation extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => OnlineConsultationState();
}

class OnlineConsultationState extends State<OnlineConsultation> {
  List<String> uploadImg = ["assets/images/upload_photo.png"];
  TextEditingController resourceController = TextEditingController();
  String age = "请选择年龄";
  String sex = "请选择性别";
  List<int> ageList = List.generate(101, (index) => index);

  @override
  void initState() {
    super.initState();
    // initPlatformState();
  }

  Future<void> initPlatformState() async {
    //相机权限
    if (await requestCameraPermission() == false) {
      return;
    }
    //录音权限
    if (await requestMicrophonePermission() == false) {
      return;
    }
  }

  Future<bool> requestCameraPermission() async {
    var status = await Permission.camera.status;
    if (status == PermissionStatus.granted) {
      return true;
    } else {
      status = await Permission.camera.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  Future<bool> requestMicrophonePermission() async {
    var status = await Permission.microphone.status;
    if (status == PermissionStatus.granted) {
      return true;
    } else {
      status = await Permission.microphone.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Global.BackgroundColor,
        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: SingleChildScrollView(
            child: Container(
                padding: EdgeInsets.all(10),
                child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(10),
                        child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '问诊资料',
                                style: TextStyle(
                                    fontSize: 20, color: Colors.black),
                              ),
                            ]),
                      ),
                      ClipRRect(
                        borderRadius: BorderRadius.circular(10.0),
                        child: Container(
                          color: Colors.white,
                          padding: const EdgeInsets.all(10),
                          child: Column(
                              mainAxisSize: MainAxisSize.min,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                /*Padding(
                                  padding: EdgeInsets.all(10),
                                  child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          '挂号费',
                                          style: TextStyle(
                                              fontSize: 15, color: Colors.grey),
                                        ),
                                        Text(
                                          '¥12.5',
                                          style: TextStyle(fontSize: 15),
                                        ),
                                      ]),
                                ),*/
                                Padding(
                                  padding: EdgeInsets.all(10),
                                  child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          '就诊人',
                                          style: TextStyle(
                                              fontSize: 15, color: Colors.grey),
                                        ),
                                        Text(
                                          Global
                                              .patient
                                              .data![Global.selectPatient]
                                              .patientName
                                              .toString(),
                                          style: TextStyle(fontSize: 15),
                                        ),
                                      ]),
                                ),
                                Padding(
                                  padding: EdgeInsets.all(10),
                                  child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          '年龄',
                                          style: TextStyle(
                                              fontSize: 15, color: Colors.grey),
                                        ),
                                        GestureDetector(
                                            onTap: () {
                                              selectItem(ageList, 0);
                                            },
                                            child: Row(children: <Widget>[
                                              Text(
                                                age,
                                                style: TextStyle(
                                                  color: Colors.black,
                                                ),
                                              ),
                                              Icon(
                                                Icons.keyboard_arrow_down,
                                                color: Colors.black,
                                              ),
                                            ])),
                                      ]),
                                ),
                                Padding(
                                  padding: EdgeInsets.all(10),
                                  child: GestureDetector(
                                    onTap: () {
                                      selectItem(['男', '女'], 1);
                                    },
                                    child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            '性别',
                                            style: TextStyle(
                                                fontSize: 15,
                                                color: Colors.grey),
                                          ),
                                          Row(children: <Widget>[
                                            Text(
                                              sex,
                                              style: TextStyle(
                                                color: Colors.black,
                                              ),
                                            ),
                                            Icon(
                                              Icons.keyboard_arrow_down,
                                              color: Colors.black,
                                            ),
                                          ])
                                        ]),
                                  ),
                                ),
                                Padding(
                                  padding: EdgeInsets.all(10),
                                  child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          '咨询医生',
                                          style: TextStyle(
                                              fontSize: 15, color: Colors.grey),
                                        ),
                                        Text(
                                          Global
                                              .doctor
                                              .data![Global.selectDoctor]
                                              .nickName
                                              .toString(),
                                          style: TextStyle(fontSize: 15),
                                        ),
                                      ]),
                                ),
                              ]),
                        ),
                      ),
                      SizedBox(height: 8),
                      Padding(
                        padding: EdgeInsets.all(10),
                        child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '病情资料',
                                style: TextStyle(
                                    fontSize: 20, color: Colors.black),
                              ),
                            ]),
                      ),
                      ClipRRect(
                        borderRadius: BorderRadius.circular(10.0),
                        child: Container(
                          color: Colors.white,
                          padding: const EdgeInsets.all(10),
                          child: Column(
                              mainAxisSize: MainAxisSize.min,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Padding(
                                  padding: EdgeInsets.all(10),
                                  child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Expanded(
                                          child: TextField(
                                            maxLines: 5,
                                            enabled: true,
                                            controller: resourceController,
                                            decoration: InputDecoration(
                                              border: OutlineInputBorder(),
                                              hintText:
                                                  '请简单描述病情，录入：主要症状、发病时间、治疗过程、病情变化、想得到什么样的帮助等',
                                            ),
                                          ),
                                        ),
                                      ]),
                                ),
                              ]),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.all(5),
                        child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '上传患处、病历、检查单等照片',
                                style: TextStyle(fontSize: 10),
                              ),
                              SizedBox(height: 3),
                              GridView.builder(
                                padding: const EdgeInsets.all(10),
                                shrinkWrap: true,
                                physics: NeverScrollableScrollPhysics(),
                                gridDelegate:
                                    const SliverGridDelegateWithFixedCrossAxisCount(
                                  //注意此行
                                  crossAxisCount: 3, //每行 widget 数量
                                  crossAxisSpacing: 10, //widget 水平之间的距离
                                  mainAxisSpacing: 10, //widget 垂直之间的距离
                                ),
                                itemCount: uploadImg.length,
                                // itemCount: 2,
                                itemBuilder: _customWidget,
                              ),
                              /*GestureDetector(
                            onTap: () {
                              uploadFile();
                            },
                            child:
                            Image(
                                image: AssetImage('assets/images/upload_photo.png'),
                              ),),*/
                            ]),
                      ),
                      ElevatedButton(
                        child: Text("下一步",
                            style:
                                TextStyle(color: Colors.white, fontSize: 15)),
                        style: ButtonStyle(
                          backgroundColor:
                              MaterialStateProperty.resolveWith<Color>(
                                  (states) {
                            return Colors.blue; // Regular color
                          }),
                          fixedSize: MaterialStateProperty.all<Size>(
                            Size(MediaQuery.of(context).size.width - 30,
                                30), // 设置宽度和高度
                          ),
                        ),
                        onPressed: () {
                          editChatDisease();
                        },
                      ),
                    ]))));
  }

  Widget _customWidget(BuildContext context, int index) {
    return GestureDetector(
      onTap: () {
        if (index == 0) {
          uploadFile();
        }
      },
      child: index == 0
          ? const Image(
              image: AssetImage(
                'assets/images/upload_photo.png',
              ),
              width: 80,
            )
          : CachedNetworkImage(
              width: 80,
              height: 80,
              fit: BoxFit.cover,
              imageUrl: uploadImg[index],
              progressIndicatorBuilder: (ctx, _, progress) => Circularloading(
                value: progress.progress,
              ),
              errorWidget: (ctx, _, __) => const ImageError(
                size: 80,
              ),
            ),
    );
  }

  void uploadFile() async {
    FilePickerResult? result = await FilePicker.platform
        .pickFiles(allowedExtensions: ["jpg"], type: FileType.custom);

    if (result != null) {
      if (result.files.single.extension != "jpg") {
        Component.toast("请选择jpg格式的图片", 2);
        return;
      }
      String fileName = result.files.single.name;
      String? filePath = result.files.single.path;
      FormData formData = FormData.fromMap({
        "file": await MultipartFile.fromFile(filePath!, filename: fileName),
        "path": "chat",
      });

      try {
        Component.toast("正在上传,请稍后", 2);
        Map<String, String> headers = {
          'token': Global.token,
        };
        Response response = await Dio().post(
            '${Global.BaseUrl}common/minioUploadImage',
            data: formData,
            options: Options(headers: headers));
        if (response.statusCode == 200) {
          var json = decodeBodyToJson(response.data);
          logd("上传图片结果=$json");
          Normal2Response mNormal2Response = new Normal2Response.fromJson(json);
          if (mNormal2Response.code == Global.responseSuccessCode) {
            // Component.toast("上传成功！", 2);
            uploadImg.add(mNormal2Response.msg.toString());
            setState(() {});
          } else {
            Component.toast(mNormal2Response.msg.toString(), 0);
          }
        } else {
          Component.toast("出错了，请稍后再试！", 0);
          return null;
        }
      } catch (e) {
        logd(e);
      }
    }
  }

  Future<void> editChatDisease() async {
    if (age == "请选择年龄") {
      Component.toast("请选择患者年龄！", 0);
      return;
    }
    if (sex == "请选择性别") {
      Component.toast("请选择患者性别！", 0);
      return;
    }
    if (resourceController.text.isEmpty) {
      Component.toast("请填写病情资料！", 0);
      return;
    }
    if (uploadImg.length < 1) {
      Component.toast("请上传病历图片！", 0);
      return;
    }

    String uploadImgStr = uploadImg
        .sublist(1, uploadImg.length)
        .toString()
        .replaceAll("[", "")
        .replaceAll("]", "");
    logd(uploadImgStr);

    int ageInt = int.parse(age);
    int sexInt = 0;
    if (sex == "女") sexInt = 1;

    var params = {
      'name': Global.patient.data![Global.selectPatient].patientName.toString(),
      'age': ageInt,
      'sex': sexInt,
      'docker': Global.doctor.data![Global.selectDoctor].nickName.toString(),
      'resource': resourceController.text,
      'patientId': Global.patient.data![Global.selectPatient].patientId,
      'url': uploadImgStr,
    };

    logd(params);

    var response = await http.put(
        Uri.parse('${Global.BaseUrl}chat/editChatDisease'),
        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) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
              builder: (context) => ChatHome(
                    doctorId: Global.doctor.data![Global.selectDoctor].userId
                        .toString(),
                    doctorName:
                        Global.doctor.data![Global.selectDoctor].nickName,
                  )),
        );
        /*Navigator.pushAndRemoveUntil(
          context,
          MaterialPageRoute(builder: (context) => ChatHome()), (route) => false,
        );*/
      } else {
        Component.toast(mNormalResponse.msg.toString(), 0);
      }
    } else {
      Component.toast("出错了，请稍后再试！", 0);
      return null;
    }
  }

  selectItem(List list, int item) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SingleChildScrollView(
          child: Container(
            width: double.infinity,
            height: list.length * 50,
            child: Column(
              children: List.generate(
                list.length,
                (index) => GestureDetector(
                  onTap: () {
                    setState(() {
                      switch (item) {
                        case 0:
                          age = list[index].toString();
                          break;
                        case 1:
                          sex = list[index];
                          break;
                      }
                    });
                    Navigator.pop(context);
                  },
                  child: Padding(
                    padding: const EdgeInsets.all(10),
                    child: Text(
                      '                 ${list[index]}                 ',
                      style: TextStyle(fontSize: 18),
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
