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

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:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';

import 'bean/normal_response.dart';
import 'bean/normal_response2.dart';
import 'package:http/http.dart' as http;

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 MaterialApp(
        home: 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: Container(
        child: Expanded(
          child: Column(
            children: [
              index == 0
                  ? Image(
                      image: AssetImage(
                        'assets/images/upload_photo.png',
                      ),
                      width: 80,
                    )
                  : Image.network(
                      // 图片地址
                      uploadImg[index],
                      width: 80,
                      fit: BoxFit.cover,
                      excludeFromSemantics: true,
                      errorBuilder: (context, error, stackTrace) => Icon(
                        Icons.image,
                        size: 80,
                        color: Colors.grey,
                      ),
                      loadingBuilder: (context, child, loadingProgress) {
                        if (loadingProgress == null) return child;
                        return Center(
                          child: CircularProgressIndicator(
                            value: loadingProgress.expectedTotalBytes != null
                                ? loadingProgress.cumulativeBytesLoaded /
                                    loadingProgress.expectedTotalBytes!
                                : null,
                          ),
                        );
                      },
                    ),
            ],
          ),
        ),
      ),
    );
  }

  void uploadFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();

    if (result != null) {
      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 {
        Map<String, String> headers = {
          'token': '${Global.token}',
        };
        Response response = await Dio().post(
            Global.BaseUrl + 'common/minioUploadImage',
            data: formData,
            options: Options(headers: headers));
        print(response.data);
        if (response.statusCode == 200) {
          Normal2Response mNormal2Response =
              new Normal2Response.fromJson(response.data);
          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) {
        print(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("]", "");
    print(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,
    };

    print(params);

    Map<String, String> headers = {
      HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
      'token': '${Global.token}',
    };
    var response = await http.put(
        Uri.parse(Global.BaseUrl + 'chat/editChatDisease'),
        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) {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => ChatHome("")),
        );
        /*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),
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
