import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/upload_result.dart';
import 'package:huixiang/retrofit/data/user_info.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/cupertino_date_picker.dart';
import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:intl/intl.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../view_widget/request_permission.dart';

class UserInfoPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _UserInfoPage();
  }
}

class _UserInfoPage extends State<UserInfoPage> {
  ApiService apiService;

  Map<String, dynamic> modifyInfo = {
    "birth": "",
    "headimg": "",
    "nickname": "",
    "sex": "",
    "signature": ""
  };

  @override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((value) => {
          print(value.getString('user')),
          user = UserInfo.fromJson(jsonDecode(value.getString('user'))),
          mobile = user?.phone ?? "",
          modifyInfo["nickname"] = user?.nickname ??"",
          modifyInfo["signature"] = user?.signature ?? "",
          modifyInfo["birth"] = user?.birth ?? "",
          modifyInfo["headimg"] = user?.headimg ?? "",
          modifyInfo["sex"] = user?.sex ?? "",
          age = AppUtils.getAgeByString(user ?.birth ?? ""),
          refresh(),
          apiService = ApiService(Dio(),
              context: context, token: value.getString('token')),
        });
  }

  String age;
  String mobile = "";
  String locale = "zh";
  UserInfo user;
  int selectSexIndex = 0;

  refresh() async {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFFFFFFF),
      appBar: MyAppBar(
        title: S.of(context).gerenxinxi,
        titleColor: Colors.black,
        background: Color(0xFFFFFFFF),
        leadingColor: Colors.black,
      ),
      body: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            userInfo(),
          ],
        ),
      ),
    );
  }

  Widget userInfo() {
    return Container(
      margin: EdgeInsets.only(left: 14.w, right: 14.w),
      child: Column(
        children: [
          InkWell(
            onTap: () {
              showImagePicker();
            },
            child: avatarItem(0, ""),
          ),
          Container(
            margin: EdgeInsets.symmetric(vertical: 12.h),
            width: double.infinity,
            height: 1,
            color: Color(0xFFF2F2F2),
          ),
          InkWell(
            onTap: () {
              editname();
            },
            child: avatarItem(1,
                (modifyInfo["nickname"]) == "" ? "回乡" : modifyInfo["nickname"]),
          ),
          Container(
            margin: EdgeInsets.symmetric(vertical: 12.h),
            width: double.infinity,
            height: 1,
            color: Color(0xFFF2F2F2),
          ),
          InkWell(
            onTap: () {
              editSignature();
            },
            child: avatarItem(
                2,
                (modifyInfo["signature"]) == ""
                    ? "还未编辑个性签名~"
                    : modifyInfo["signature"]),
          ),
          Container(
            margin: EdgeInsets.symmetric(vertical: 12.h),
            width: double.infinity,
            height: 1,
            color: Color(0xFFF2F2F2),
          ),
          InkWell(
            onTap: (modifyInfo["birth"] == "") ? showDateSelector : () {},
            child: avatarItem(
                3,
                (modifyInfo["birth"] != null && modifyInfo["birth"] != "")
                    ? modifyInfo["birth"]
                    : S.of(context).wanshanshengrixinxi_yhq),
          ),
          Container(
            margin: EdgeInsets.symmetric(vertical: 12.h),
            width: double.infinity,
            height: 1,
            color: Color(0xFFF2F2F2),
          ),
          avatarItem(4, mobile),
          Container(
            margin: EdgeInsets.symmetric(vertical: 12.h),
            width: double.infinity,
            height: 1,
            color: Color(0xFFF2F2F2),
          ),
          InkWell(
            onTap: () {
              showSexSelect(selectSexIndex);
            },
            child: avatarItem(
                5, (modifyInfo["sex"] != null && modifyInfo["sex"] != "") ? modifyInfo["sex"]:"还未选择性别"),
          ),
        ],
      ),
    );
  }

  editname() async {
    dynamic name = await Navigator.of(context).pushNamed('/router/edit_name',
        arguments: {"nick": modifyInfo['nickname']});
    if (name != null && name != "") {
      modifyInfo["nickname"] = name;
      setState(() {});
      modifyInfos();
    }
  }

  editSignature() async {
    dynamic signature = await Navigator.of(context).pushNamed(
        '/router/edit_signature',
        arguments: {"signature": modifyInfo['signature']});
    if (signature != null && signature != "") {
      modifyInfo["signature"] = signature;
      setState(() {});
      modifyInfos();
    }
  }

  List<String> itemLefts = [
    S.current.touxiang,
    S.current.yonghuming,
    "个性签名",
    S.current.wodeshengri,
    S.current.shoujihao,
    "性别",
  ];

  ///生日时期选择
  showDateSelector() async {
    DateTime dateTime = await showModalBottomSheet(
        backgroundColor: Colors.transparent,
        context: context,
        builder: (_) {
          return CupertinoDatePickerWidget();
        });
    if (dateTime != null) {
      modifyInfo["birth"] = DateFormat("yyyy-MM-dd").format(dateTime);
      user.birth = modifyInfo["birth"];
      age = AppUtils.getAge(dateTime);
      modifyInfos();
      setState(() {});
    }
  }

  ///性别选择
  showSexSelect(index) {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return StatefulBuilder(builder: (
            context,
            state,
            ) {
          return Container(
            width: double.infinity,
            height: 200.h,
            padding: EdgeInsets.only(top: 12.h),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  topRight: Radius.circular(6),
                  topLeft: Radius.circular(6),
                )),
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 14.w),
                  child: Row(
                    children: [
                      Expanded(
                          child:GestureDetector(
                            behavior:HitTestBehavior.opaque,
                            onTap: (){
                              Navigator.of(context).pop();
                            },
                            child: Text(
                              S.of(context).quxiao,
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 16.sp,
                                fontWeight: MyFontWeight.black,
                              ),
                            ),
                          )),
                      GestureDetector(
                        behavior:HitTestBehavior.opaque,
                        onTap: (){
                          state((){
                            modifyInfo["sex"] = (selectSexIndex == 0)?"男":"女";
                            modifyInfos();
                            Navigator.of(context).pop();
                          });},
                        child: Text(
                          S.of(context).queding,
                          style: TextStyle(
                            color: Color(0xFF32A060),
                            fontSize: 16.sp,
                            fontWeight: MyFontWeight.black,
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                    margin: EdgeInsets.only(top: 12.h, bottom: 13.h),
                    height: 1.h,
                    color: Color(0xFFF2F2F2)),
                GestureDetector(
                  behavior:HitTestBehavior.opaque,
                  onTap: () {
                    state((){
                      selectSexIndex = 0;
                    });
                  },
                  child: Container(
                    width: double.infinity,
                    alignment: Alignment.center,
                    padding:
                    EdgeInsets.only(top:12.h, bottom:12.h, left: 12.w),
                    margin: EdgeInsets.symmetric(horizontal: 14.w),
                    decoration: BoxDecoration(
                      borderRadius:BorderRadius.circular(6),
                      border: Border.all(
                        color: selectSexIndex == 0 ? Color(0xFF32A060):Color(0xFFF7F7F7),
                        width: selectSexIndex == 0 ? 1 :0,
                      ),
                      color: selectSexIndex == 0 ? Color(0xFFF0FAF4) :Color(0xFFF7F7F7),
                    ),
                    child: Text(
                      "男",
                      style: TextStyle(
                        color: selectSexIndex == 0? Color(0xFF32A060):Color(0xFF4D4D4D),
                        fontSize: 18.sp,
                        fontWeight: MyFontWeight.regular,
                      ),
                    ),
                  ),
                ),
                SizedBox(
                  height: 13.h,
                ),
                GestureDetector(
                  behavior:HitTestBehavior.opaque,
                  onTap: () {
                    state((){
                      selectSexIndex = 1;
                    });
                  },
                  child: Container(
                      width: double.infinity,
                      alignment: Alignment.center,
                      padding:
                      EdgeInsets.only(top: 12.h, bottom: 12.h, left: 12.w),
                      margin: EdgeInsets.symmetric(horizontal: 14.w),
                      decoration: BoxDecoration(
                        borderRadius:BorderRadius.circular(6),
                        border: Border.all(
                          color: selectSexIndex == 1 ? Color(0xFF32A060):Color(0xFFF7F7F7),
                          width: selectSexIndex == 1 ? 1 :0,
                        ),
                        color: selectSexIndex == 1 ? Color(0xFFF0FAF4) :Color(0xFFF7F7F7),
                      ),
                      child: Text(
                        "女",
                        style: TextStyle(
                          color: selectSexIndex == 1 ?Color(0xFF32A060):Color(0xFF4D4D4D),
                          fontSize: 18.sp,
                          fontWeight: MyFontWeight.regular,
                        ),
                      )),
                )
              ],
            ),
          );
        });
      },
    );
  }

  ///显示图片选择方式
  showImagePicker() {
    showCupertinoModalPopup(
        context: context,
        builder: (contetx) {
          return CupertinoActionSheet(
            title: Text(S.of(context).genghuantouxiang),
            actions: [
              CupertinoActionSheetAction(
                child: Text(S.of(context).paizhao),
                onPressed: () {
                  openCamera();
                  Navigator.of(context).pop();
                },
                isDefaultAction: true,
                isDestructiveAction: false,
              ),
              CupertinoActionSheetAction(
                child: Text(S.of(context).xiangce),
                onPressed: () {
                  openStorage();
                  Navigator.of(context).pop();
                },
                isDefaultAction: true,
                isDestructiveAction: false,
              ),
            ],
            cancelButton: CupertinoActionSheetAction(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text(S.of(context).quxiao),
              isDestructiveAction: true,
            ),
          );
        });
  }

  ///拍照
  openCamera() async {
    if (await Permission.camera.isPermanentlyDenied) {
      showCupertinoDialog(
          context: context,
          builder: (context) {
            return RequestPermission(
              "assets/image/icon_camera_permission_tips.webp",
              S.of(context).ninxiangjiquanxianweikaiqi,
              S.of(context).weilekaipaizhaoxuanzhetouxiang,
              S.of(context).kaiqiquanxian,
                  (result) async {
                if (result) {
                  await openAppSettings();
                }
              },
              heightRatioWithWidth: 0.82,
            );
          });
    }else if (await Permission.camera.isGranted) {
      if (await Permission.storage.isPermanentlyDenied) {
        showCupertinoDialog(
            context: context,
            builder: (context) {
              return RequestPermission(
                "assets/image/icon_storage_permission_tips.webp",
                "您未开启存储权限,请点击开启",
                "为了您可以在使用过程中访问您设备上的照片、媒体内容和文件,请您开启存储使用权限",
                S.of(context).kaiqiquanxian,
                    (result) async {
                  if (result) {
                    await openAppSettings();
                  }
                },
                heightRatioWithWidth: 0.82,
              );
            });}else if(await Permission.storage.isGranted){
        Media medias = await ImagePickers.openCamera(
          cameraMimeType: CameraMimeType.photo,
          cropConfig: CropConfig(
            enableCrop: true,
            width: 200,
            height: 200,
          ),
          compressSize: 500,
        );
        if (medias == null) return;
        filePath = medias.path;
        fileUpload();
      }else{
        showStorageTipsAlertDialog(context,1);
        return false;
      }
    } else {
      showCameraTipsAlertDialog(context);
      return false;
      // await Permission.camera.request();
      // openCamera();
    }
  }

  String filePath;

  ///打开相册
  openStorage() async {
    if (await Permission.storage.isPermanentlyDenied) {
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return RequestPermission(
            "assets/image/icon_storage_permission_tips.webp",
            "您未开启存储权限,请点击开启",
            "为了您可以在使用过程中访问您设备上的照片、媒体内容和文件,请您开启存储使用权限",
            S.of(context).kaiqiquanxian,
                (result) async {
              if (result) {
                await openAppSettings();
              }
            },
            heightRatioWithWidth: 0.82,
          );
        });
  }else if (await Permission.storage.isGranted) {
      List<Media> medias = await ImagePickers.pickerPaths(
        galleryMode: GalleryMode.image,
        selectCount: 1,
        showGif: true,
        showCamera: false,
        compressSize: 500,
        uiConfig: UIConfig(
          uiThemeColor: Color(0xFFFFFFFF),
        ),
        cropConfig: CropConfig(
          enableCrop: true,
          width: 200,
          height: 200,
        ),
      );
      if (medias == null || medias.length == 0) return;
      filePath = medias[0].path;
      setState(() {});
      fileUpload();
    } else {
      showStorageTipsAlertDialog(context,0);
      return false;
      // await Permission.storage.request();
      // openStorage();
    }
  }

  ///相册权限说明
  showStorageTipsAlertDialog(context,type) async {
    //显示对话框
    showDialog(
      context: context,
      barrierDismissible: false,
      barrierColor: null,
      builder: (BuildContext context) {
        return Column(
          children: [
            Container(
              width: double.infinity,
              padding: EdgeInsets.all(15),
              margin: EdgeInsets.all(15),
              decoration: new BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(padding:EdgeInsets.only(right: 10.w,),
                  child: Icon(
                    Icons.add_photo_alternate_outlined,
                    color: Colors.black,
                    size: 22,
                  )),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          "存储权限使用说明",
                          style: TextStyle(
                            fontSize: 18.sp,
                            fontWeight: MyFontWeight.regular,
                            color: Colors.black,
                          ),
                        ),
                        SizedBox(
                          height: 3.h,
                        ),
                        Text(
                          "为了帮您实现分享照片、保存照片等功能。",
                          style: TextStyle(
                            fontSize: 13.sp,
                            height: 1.2,
                            fontWeight: MyFontWeight.regular,
                            color: Colors.black,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            )
          ],
          mainAxisSize: MainAxisSize.min,
        );
      },
    );
    await Permission.storage.request();
    Navigator.of(context).pop();
    if(await Permission.storage.isGranted){
      if(type == 1){
        openCamera();
      }else{
        openStorage();
      }
    }
  }

  ///拍照权限说明
  showCameraTipsAlertDialog(context) async {
    //显示对话框
    showDialog(
      context: context,
      barrierDismissible: false,
      barrierColor: null,
      builder: (BuildContext context) {
        return Column(
          children: [
            Container(
              width: double.infinity,
              padding: EdgeInsets.all(15),
              margin: EdgeInsets.all(15),
              decoration: new BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(padding:EdgeInsets.only(right: 10.w,),
                      child: Icon(
                        Icons.add_photo_alternate_outlined,
                        color: Colors.black,
                        size: 22,
                      )),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          "相机权限使用说明",
                          style: TextStyle(
                            fontSize: 18.sp,
                            fontWeight: MyFontWeight.regular,
                            color: Colors.black,
                          ),
                        ),
                        SizedBox(
                          height: 3.h,
                        ),
                        Text(
                          "实现您扫码、拍摄等功能。",
                          style: TextStyle(
                            fontSize: 13.sp,
                            height: 1.2,
                            fontWeight: MyFontWeight.regular,
                            color: Colors.black,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            )
          ],
          mainAxisSize: MainAxisSize.min,
        );
      },
    );
    await Permission.camera.request();
    Navigator.of(context).pop();
    if(await Permission.camera.isGranted){
      openCamera();
    }
  }

  // Future<File> cropImage(imagePath) async {
  // File croppedFile = await ImageCropper.cropImage(
  //     sourcePath: imagePath,
  //     aspectRatioPresets: [
  //       CropAspectRatioPreset.square,
  //       // CropAspectRatioPreset.ratio3x2,
  //       // CropAspectRatioPreset.original,
  //       // CropAspectRatioPreset.ratio4x3,
  //       // CropAspectRatioPreset.ratio16x9
  //     ],
  //     aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1),
  //     androidUiSettings: AndroidUiSettings(
  //         toolbarTitle: 'Cropper',
  //         toolbarColor: Colors.black,
  //         toolbarWidgetColor: Colors.white,
  //         initAspectRatio: CropAspectRatioPreset.square,
  //         hideBottomControls: true,
  //         lockAspectRatio: false),
  //     iosUiSettings: IOSUiSettings(
  //       minimumAspectRatio: 1.0,
  //       resetAspectRatioEnabled: false,
  //       aspectRatioPickerButtonHidden: true,
  //       rectWidth: 500.w,
  //       rectHeight: 500.h,
  //     ));
  // return croppedFile;
  // }

  ///调用修改用户信息接口
  modifyInfos() async {
    var info = await apiService.editInfo(modifyInfo).catchError((onError) {});
    if (info.isSuccess) {
      SharedPreferences.getInstance().then((value) {
        value.setString('user', jsonEncode(modifyInfo));
      });
      setState(() {
        SmartDialog.showToast("用户信息修改成功", alignment: Alignment.center);
      });
    }else{
      SmartDialog.showToast("用户信息修改失败  " + info.msg, alignment: Alignment.center);
    }
  }

  ///文件上传
  fileUpload() async {
    if (filePath != null && filePath != "" && await File(filePath).exists()) {
      BaseData<UploadResult> baseData = await apiService
          .upload(File(filePath), 123123123, false)
          .catchError((onError) {});
      if (baseData != null && baseData.isSuccess) {
        UploadResult uploadResult = baseData.data;
        modifyInfo["headimg"] = uploadResult.url;
        modifyInfos();
      }
    }
  }

  Widget avatarItem(type, value) {
    print("object: $value");
    return Container(
      child: Row(
        children: [
          Expanded(
            child: Text(
              itemLefts[type],
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 15.sp,
                color: Color(0xFF1A1A1A),
              ),
            ),
            flex: 1,
          ),
          buildValue(type, value),
          if (type != 5 &&
              type != 4 &&
              type != 3 &&
              (((modifyInfo["birth"] == "")) || type != 3))
            valueEnd(),
        ],
      ),
    );
  }

  Widget valueEnd() {
    return Container(
        child: Icon(
      Icons.keyboard_arrow_right,
      size: 20.sp,
    ));
  }

  Widget buildValue(type, value) {
    if (type == 0) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: filePath == null || filePath == ""
            ? (modifyInfo["headimg"] != null && modifyInfo["headimg"] != ""
                ? MImage(
                    modifyInfo["headimg"],
                    width: 42,
                    height: 42,
                    fit: BoxFit.cover,
                  )
                : Image.asset(
                    "assets/image/default_1.webp",
                    width: 42,
                    height: 42,
                    fit: BoxFit.cover,
                  ))
            : Image.file(
                File(filePath),
                width: 42,
                height: 42,
                fit: BoxFit.cover,
              ),
      );
    } else if (type == 1) {
      return Text(
        value,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          fontWeight: MyFontWeight.regular,
          fontSize: 13.sp,
          color: Color(0xFF4D4D4D),
        ),
      );
    } else {
      return Expanded(
          child: Text(
        value,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        textAlign: TextAlign.right,
        style: TextStyle(
          fontWeight: MyFontWeight.regular,
          fontSize: 13.sp,
          color: Color(0xFF4D4D4D),
        ),
      ));
    }
  }
}