import 'dart:io';

import 'package:dio/dio.dart';
import 'package:eitc_erm_app/bean/normal_response.dart';
import 'package:eitc_erm_app/my_doctor.dart';
import 'package:eitc_erm_app/patient_list.dart';
import 'package:eitc_erm_app/patient_talk_list.dart';
import 'package:eitc_erm_app/record_registration.dart';
import 'package:eitc_erm_app/utils/Component.dart';
import 'package:eitc_erm_app/utils/Constants.dart';
import 'package:eitc_erm_app/utils/Utils.dart';
import 'package:eitc_erm_app/utils/logger.dart';
import 'package:eitc_erm_app/widget/image_error.dart';
import 'package:eitc_erm_app/widget/user_header.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:permission_handler/permission_handler.dart';

import 'bean/upload_entity.dart';
import 'bean/user_list.dart';
import 'change_password.dart';
import 'change_phoneno.dart';
import 'login.dart';

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

class Mine extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MineState();
}

class MineState extends State<Mine> {
  late Future<UserListEntity?> _future;

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

  MethodChannel _channel = MethodChannel('channel_name');

  Future<String?> get platformVersion async {
    final String? version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  Future<UserListEntity?> fetchData() async {
    Map<String, String> headers = {
      'token': Global.token,
    };
    final response =
        await http.get(Uri.parse('${Global.BaseUrl}user/list'), headers: jsonHeaders(withToken: true));
    if (response.statusCode == 200) {
      final json = decodeBodyToJson(response.bodyBytes);
      logd("就诊人列表=$json");
      UserListEntity mUserListEntity = new UserListEntity.fromJson(json);
      for (int i = 0; i < mUserListEntity.data!.length; i++) {
        logd("=================${mUserListEntity.data![i].isDefault}");
        if (mUserListEntity.data?[i].isDefault == 1 &&
            Global.selectPatient == -1) {
          Global.appointmentPersonId = mUserListEntity.data![i].patientId!;

          Global.selectPatient = i;
          Global.patient = mUserListEntity;
        }
      }

      return mUserListEntity;
    } else {
      Component.toast("出错了，请稍后再试！", 0);
    }
  }

  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(
        appBar: AppBar(
          title: const Text('个人中心',
              style: TextStyle(
                color: Colors.white,
              )),
          centerTitle: true,
          elevation: 0.5,
          backgroundColor: Global.StatusBarColor,
        ),
        body: SingleChildScrollView(
          child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  decoration: const BoxDecoration(
                    color: Global.StatusBarColor,
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(20),
                    child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                GestureDetector(
                                  onTap: () {
                                    uploadFile();
                                  },
                                  child: FutureBuilder(
                                      future: Utils.readData("userAvatar"),
                                      builder: (ctx, shot) {
                                        Widget imageError = const ImageError(
                                          icon: Icons.account_circle,
                                          size: 60,
                                          color: Colors.white,
                                        );
                                        if (shot.connectionState !=
                                            ConnectionState.done) {
                                          return imageError;
                                        } else {
                                          if (shot.hasError ||
                                              !shot.hasData ||
                                              shot.data == null ||
                                              shot.data!.isEmpty) {
                                            return imageError;
                                          }
                                          return UserHeader(
                                            url:
                                                "${Global.ImageUrl}${shot.data!}",
                                            placeHolder: imageError,
                                          );
                                        }
                                      }),
                                ),
                                Text(
                                  '  ${Global.loginPhoneNo}',
                                  style: const TextStyle(
                                      fontSize: 18, color: Colors.white),
                                ),
                              ]),
                          GestureDetector(
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => PatientTalkList()),
                              );
                            },
                            child: const Icon(
                              Icons.message,
                              color: Colors.white,
                            ),
                          ),
                        ]),
                  ),
                ),
                Container(
                  width: double.infinity,
                  height: 100,
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/images/mine_bg.png'),
                      fit: BoxFit.cover,
                    ),
                  ),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        GestureDetector(
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => PatientList()),
                              );
                            },
                            child: const Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                mainAxisSize: MainAxisSize.max,
                                children: [
                                  Icon(
                                    Icons.person,
                                    color: Colors.orange,
                                  ),
                                  Text(
                                    '就诊人管理',
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: Colors.orange,
                                    ),
                                  )
                                ])),
                        GestureDetector(
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => MyDoctor()),
                              );
                            },
                            child: const Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                mainAxisSize: MainAxisSize.max,
                                children: [
                                  Icon(
                                    Icons.data_saver_on_outlined,
                                    color: Colors.green,
                                  ),
                                  Text(
                                    '收藏的医生',
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: Colors.green,
                                    ),
                                  )
                                ])),
                      ]),
                ),
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => RecordRegistration()),
                    );
                  },
                  child: const Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Padding(
                                  padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
                                  child: Icon(
                                    Icons.receipt_long,
                                    color: Colors.green,
                                  )),
                              Text(
                                '预约挂号记录',
                                style: TextStyle(fontSize: 18),
                              ),
                            ]),
                        Padding(
                          padding: EdgeInsets.fromLTRB(10, 20, 20, 20),
                          child: Icon(
                            Icons.keyboard_double_arrow_right,
                            color: Colors.grey,
                          ),
                        ),
                      ]),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                  child: Container(
                    width: double.infinity,
                    height: 1.0,
                    padding: const EdgeInsets.all(50),
                    decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        colors: [Colors.black, Colors.white],
                        begin: Alignment.center,
                        end: Alignment.centerRight,
                        tileMode: TileMode.mirror,
                      ),
                    ),
                    child: const Image(
                      image: AssetImage('assets/images/line.png'),
                    ),
                  ),
                ),
                /*GestureDetector(
                    onTap: () {
                      */ /*Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => MyApp()),
                      );*/ /*
                      if (Platform.isIOS) {
                        platformVersion;
                      } else if (Platform.isAndroid) {
                        launchAndroid();
                      }

                    },
                    child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Padding(
                                    padding: const EdgeInsets.fromLTRB(
                                        20, 20, 20, 20),
                                    child: Icon(
                                      Icons.phone_android_sharp,
                                      color: Colors.lightBlueAccent,
                                    )),
                                Text(
                                  '我的设备',
                                  style: const TextStyle(fontSize: 18),
                                ),
                              ]),
                          Padding(
                            padding:
                                const EdgeInsets.fromLTRB(10, 20, 20, 20),
                            child: Icon(
                              Icons.keyboard_double_arrow_right,
                              color: Colors.grey,
                            ),
                          ),
                        ]),
                  ),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                    child: Container(
                      width: double.infinity,
                      height: 1.0,
                      padding: const EdgeInsets.all(50),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [Colors.black, Colors.white],
                          begin: Alignment.center,
                          end: Alignment.centerRight,
                          tileMode: TileMode.mirror,
                        ),
                      ),
                      child: Image(
                        image: AssetImage('assets/images/line.png'),
                      ),
                    ),
                  ),*/
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => ChangePasswordPage()),
                    );
                  },
                  child: const Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Padding(
                                  padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
                                  child: Icon(
                                    Icons.password_outlined,
                                    color: Colors.deepPurple,
                                  )),
                              Text(
                                '修改密码',
                                style: TextStyle(fontSize: 18),
                              ),
                            ]),
                        Padding(
                          padding: EdgeInsets.fromLTRB(10, 20, 20, 20),
                          child: Icon(
                            Icons.keyboard_double_arrow_right,
                            color: Colors.grey,
                          ),
                        ),
                      ]),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                  child: Container(
                    width: double.infinity,
                    height: 1.0,
                    padding: const EdgeInsets.all(50),
                    decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        colors: [Colors.black, Colors.white],
                        begin: Alignment.center,
                        end: Alignment.centerRight,
                        tileMode: TileMode.mirror,
                      ),
                    ),
                    child: const Image(
                      image: AssetImage('assets/images/line.png'),
                    ),
                  ),
                ),
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => ChangePhoneNo()),
                    );
                  },
                  child: const Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Padding(
                                  padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
                                  child: Icon(
                                    Icons.mobile_screen_share,
                                    color: Colors.red,
                                  )),
                              Text(
                                '修改手机号',
                                style: TextStyle(fontSize: 18),
                              ),
                            ]),
                        Padding(
                          padding: EdgeInsets.fromLTRB(10, 20, 20, 20),
                          child: Icon(
                            Icons.keyboard_double_arrow_right,
                            color: Colors.grey,
                          ),
                        ),
                      ]),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                  child: Container(
                    width: double.infinity,
                    height: 1.0,
                    padding: const EdgeInsets.all(50),
                    decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        colors: [Colors.black, Colors.white],
                        begin: Alignment.center,
                        end: Alignment.centerRight,
                        tileMode: TileMode.mirror,
                      ),
                    ),
                    child: const Image(
                      image: AssetImage('assets/images/line.png'),
                    ),
                  ),
                ),
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () async {
                    PackageInfo packageInfo = await PackageInfo.fromPlatform();
                    showDialog(
                        context: context,
                        builder: (ctx) {
                          return AlertDialog(
                            title: Text(packageInfo.appName),
                            content: Text("版本:${packageInfo.version}"),
                            actions: [
                              TextButton(
                                  onPressed: () => Navigator.pop(ctx),
                                  child: const Text("关闭"))
                            ],
                          );
                        });
                  },
                  child: const Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Padding(
                                  padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
                                  child: Icon(
                                    Icons.info_outline,
                                    color: Colors.red,
                                  )),
                              Text(
                                '关于',
                                style: TextStyle(fontSize: 18),
                              ),
                            ]),
                        Padding(
                          padding: EdgeInsets.fromLTRB(10, 20, 20, 20),
                          child: Icon(
                            Icons.keyboard_double_arrow_right,
                            color: Colors.grey,
                          ),
                        ),
                      ]),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                  child: Container(
                    width: double.infinity,
                    height: 1.0,
                    padding: const EdgeInsets.all(50),
                    decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        colors: [Colors.black, Colors.white],
                        begin: Alignment.center,
                        end: Alignment.centerRight,
                        tileMode: TileMode.mirror,
                      ),
                    ),
                    child: const Image(
                      image: AssetImage('assets/images/line.png'),
                    ),
                  ),
                ),
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.fromLTRB(20, 50, 20, 0),
                  child: ElevatedButton(
                    style: ButtonStyle(
                      backgroundColor:
                          WidgetStateProperty.resolveWith<Color>((states) {
                        return Colors.blue; // Regular color
                      }),
                    ),
                    onPressed: () {
                      logout();
                    },
                    child: const Text("退出",
                        style: TextStyle(color: Colors.white, fontSize: 15)),
                  ),
                )
              ]),
        ));
  }

  Future<String?> logout() async {
    Utils.saveData("token", "");
    Utils.saveData("userId", "");
    Utils.saveData("userAvatar", "");

    Map<String, String> headers = {
      'token': Global.token,
    };
    var response =
        await http.get(Uri.parse('${Global.BaseUrl}logout'), headers: headers);

    if (response.statusCode == 200) {
      final json = decodeBodyToJson(response.bodyBytes);
      logd("登出结果=$json");
      NormalResponse mNormalResponse = new NormalResponse.fromJson(json);
      if (mNormalResponse.code == Global.responseSuccessCode) {
      } else {
        Component.toast(mNormalResponse.msg.toString(), 0);
      }

      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => Login()),
      );

      return response.toString();
    } else {
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => Login()),
      );
      return null;
    }
  }

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

    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),
      });

      Component.toast("正在上传头像，请稍后", 2);
      try {
        Map<String, String> headers = {
          'token': Global.token,
        };
        Response response = await Dio().post('${Global.BaseUrl}common/upload',
            data: formData, options: Options(headers: headers));
        if (response.statusCode == 200) {
          var json = decodeBodyToJson(response.data);
          logd("上传头像文件结果=$json");
          UploadEntity mUploadEntity = UploadEntity.fromJson(json);
          if (mUploadEntity.code == Global.responseSuccessCode) {
            logd("uploaded=${mUploadEntity.toJson()}");
            //保存头像
            bool result = await _saveAvatar(mUploadEntity.fileName ?? "");
            if (result) {
              setState(() {
                Component.toast("上传成功！", 2);
              });
              return;
            }
            Component.toast("出错了，请稍后再试！", 0);
          } else {
            Component.toast(mUploadEntity.msg.toString(), 0);
          }
        } else {
          Component.toast("出错了，请稍后再试！", 0);
          return null;
        }
      } catch (e) {
        logd(e);
      }
    }
  }

  Future<bool> _saveAvatar(String path) async {
    if (path.isEmpty) {
      return Future.value(false);
    }

    Map<String, dynamic> params = {"id": Global.userId, "avatar": path};

    try {
      var response = await http.post(Uri.parse("${Global.BaseUrl}user/edit"),
          body: encodeBody(params), headers: jsonHeaders(withToken: true));
      if (response.statusCode == 200) {
        final json = decodeBodyToJson(response.bodyBytes);
        logd("保存头像结果=$json");
        if (json["code"] != 200) {
          return Future.value(false);
        }
        await Utils.saveData("userAvatar", path);
        return Future.value(true);
      } else {
        return Future.value(false);
      }
    } catch (e) {
      logd("更新头像异常,e=$e");
    }
    return Future.value(false);
  }

  Future<void> launchAndroid() async {
    const platform = MethodChannel('com.example.xcx_dashan_app/channel');
    try {
      var result = await platform.invokeMethod('launchApp');

      //  var result = await platform.invokeMethod('launchAppOne',{'param1': "这是一个参数"});
      // var result =  await platform.invokeMethod('launchAppOne',{'param1': "这是一个参数",'param2': "这是一个参数"});
      logd("结果$result");
    } on PlatformException catch (e) {
      logd("Failed to invoke method: '${e.message}'.");
    }
  }
}
