import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';

import 'package:eitc_erm_app/bean/normal_response.dart';
import 'package:eitc_erm_app/doctor_talk_list.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/Share.dart';
import 'package:eitc_erm_app/utils/Utils.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/upload_entity.dart';
import 'bean/user_list.dart';
import 'change_password.dart';
import 'change_phoneno.dart';

import 'package:http/http.dart' as http;

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();
    //延迟1秒 直播推流
    Future.delayed(Duration(milliseconds: 1000), () {});
  }

  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: {
      HttpHeaders.contentTypeHeader: "application/json; charset=utf-8",
      'token': '${Global.token}',
    });
    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      print(jsonResponse);
      UserListEntity mUserListEntity =
      new UserListEntity.fromJson(jsonResponse);
      for(int i = 0; i < mUserListEntity.data!.length; i++) {
        print("=================" + mUserListEntity.data![i].isDefault.toString());
        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 MaterialApp(
        home: Scaffold(
            appBar: new AppBar(
              title: new Text('个人中心',
                  style: TextStyle(
                    color: Colors.white,
                  )),
              centerTitle: true,
              elevation: 0.5,
              backgroundColor: Global.StatusBarColor,
            ),
            body: SingleChildScrollView(
    child:Container(
              child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      decoration: 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: Icon(
                                        Icons.account_circle,
                                        color: Colors.white,
                                        size: 60,
                                      ),
                                    ),
                                    Text(
                                      '  ${Global.loginPhoneNo}',
                                      style: const TextStyle(
                                          fontSize: 18, color: Colors.white),
                                    ),
                                  ]),
                              GestureDetector(
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => PatientTalkList()),
                                  );
                                },
                                child: Icon(
                                  Icons.message,
                                  color: Colors.white,
                                ),
                              ),
                            ]),
                      ),
                    ),
                    Container(
                      width: double.infinity,
                      height: 100,
                      decoration: 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: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    mainAxisSize: MainAxisSize.max,
                                    children: [
                                      Icon(
                                        Icons.person,
                                        color: Colors.orange,
                                      ),
                                      Text(
                                        '就诊人管理',
                                        style: const TextStyle(
                                          fontSize: 14,
                                          color: Colors.orange,
                                        ),
                                      )
                                    ])),
                            GestureDetector(
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => MyDoctor()),
                                  );
                                },
                                child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    mainAxisSize: MainAxisSize.max,
                                    children: [
                                      Icon(
                                        Icons.data_saver_on_outlined,
                                        color: Colors.green,
                                      ),
                                      Text(
                                        '收藏的医生',
                                        style: const TextStyle(
                                          fontSize: 14,
                                          color: Colors.green,
                                        ),
                                      )
                                    ])),
                          ]),
                    ),
                    GestureDetector(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => RecordRegistration()),
                        );
                      },
                      child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Padding(
                                      padding: const EdgeInsets.fromLTRB(
                                          20, 20, 20, 20),
                                      child: Icon(
                                        Icons.receipt_long,
                                        color: Colors.green,
                                      )),
                                  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(
                      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(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => ChangePasswordPage()),
                        );
                      },
                      child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Padding(
                                      padding: const EdgeInsets.fromLTRB(
                                          20, 20, 20, 20),
                                      child: Icon(
                                        Icons.password_outlined,
                                        color: Colors.deepPurple,
                                      )),
                                  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(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => ChangePhoneNo()),
                        );
                      },
                      child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Padding(
                                      padding: const EdgeInsets.fromLTRB(
                                          20, 20, 20, 20),
                                      child: Icon(
                                        Icons.mobile_screen_share,
                                        color: Colors.red,
                                      )),
                                  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'),
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(20, 50, 20, 0),
                      child: 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 - 32, 30), // 设置宽度和高度
                          ),
                        ),
                        onPressed: () {
                          logout();
                        },
                      ),
                    )
                  ]),),
            )));
  }

  Future<String?> logout() async {
    Utils.saveData("token", "");
    Map<String, String> headers = {
      'token': '${Global.token}',
    };
    var response = await http
        .get(Uri.parse(Global.BaseUrl + 'logout'), headers: headers);

    if (response.statusCode == 200) {
      final jsonString = utf8.decode(response.bodyBytes);
      final jsonResponse = jsonDecode(jsonString);
      print(jsonResponse);
      NormalResponse mNormalResponse = new NormalResponse.fromJson(jsonResponse);
      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();

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

      try {
        Map<String, String> headers = {
          'token': '${Global.token}',
        };
        Response response = await Dio().post(Global.BaseUrl + 'common/upload', data: formData, options: Options(headers: headers));
        print(response.data);
        if (response.statusCode == 200) {
          UploadEntity mUploadEntity =
          new UploadEntity.fromJson(response.data);
          if (mUploadEntity.code == Global.responseSuccessCode) {
            Component.toast("上传成功！", 2);
            // LocalShare.saveData('touxiang', mUploadEntity.url.toString());
            setState(() {
              
            });
          } else {
            Component.toast(mUploadEntity.msg.toString(), 0);
          }
        } else {
          Component.toast("出错了，请稍后再试！", 0);
          return null;
        }
      } catch (e) {
        print(e);
      }
    }
  }

  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': "这是一个参数"});
      print("结果$result");
    } on PlatformException catch (e) {
      print("Failed to invoke method: '${e.message}'.");
    }
  }
}
