import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterappfuyou/code/base/YSNetWorking.dart';
import 'package:flutterappfuyou/code/version2/YSChangePassWord.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'YSMeans.dart';
import 'package:image_picker/image_picker.dart';
import 'base/YSBase.dart';
import 'base/YSTools.dart';

class YSUserInfo extends StatefulWidget {
  @override
  _YSUserInfoState createState() => _YSUserInfoState();
}

class _YSUserInfoState extends State<YSUserInfo> {
  String name,avatar;
  final ImagePicker _picker = ImagePicker();
  @override
  void initState() {
    _getInfo();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ystitle: '个人信息',
      yschild: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              width: MediaQuery.of(context).size.width-10,
              height: 100,
              margin: EdgeInsets.only(top: 5),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(6))
              ),
              child: ListView.separated(
                padding: EdgeInsets.all(0),
                itemCount: 3,
                itemBuilder: (context,index){
                  return GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: (){
                      if(index==0){
                        showCupertinoModalPopup(
                          context: context,
                          builder: (context) {
                            return CupertinoActionSheet(
                              actions: <Widget>[
                                CupertinoActionSheetAction(
                                  child: Text('相机'),
                                  onPressed: () {
                                    Navigator.pop(context);
                                    _picker.getImage(source: ImageSource.camera).then((value){
                                      _uploadImageData(value);
                                    });
                                  },
                                ),
                                CupertinoActionSheetAction(
                                  child: Text('相册'),
                                  onPressed: () {
                                    Navigator.pop(context);
                                    _picker.getImage(source: ImageSource.gallery).then((value){
                                      _uploadImageData(value);
                                    });
                                  },
                                ),
                              ],
                              cancelButton: CupertinoActionSheetAction(
                                child: Text('取消'),
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                              ),
                            );
                          }
                        );
                      }else{
                        getStringWidget();
                      }
                    },
                    child: Container(
                      height: 50,
                      padding: EdgeInsets.only(left: 18,right: 18),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(index==0?'用户头像':'用户昵称',style: TextStyle(color: Color(0xFF292929),fontSize: 14,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                          index==0?Container(
                            height: 40,
                            width: 40,
                            decoration: avatar!=null?BoxDecoration(
                              borderRadius: BorderRadius.all(Radius.circular(20)),
                              color: Color(0xFFEFEFEF),
                              image: DecorationImage(image: NetworkImage(avatar),fit: BoxFit.fill)
                            ):BoxDecoration(
                                borderRadius: BorderRadius.all(Radius.circular(20)),
                                color: Color(0xFFEFEFEF),
                            ),
                          ):Text(name!=null?name:'',style: TextStyle(color: Color(0xFFAEB3BD),fontSize: 14),)
                        ],
                      ),
                    ),
                  );
                },
                separatorBuilder: (context,index){
                  return Container(
                    height: 1.4,
                    child: Image.asset('lib/images/line.png'),
                  );
                },
                physics: NeverScrollableScrollPhysics(),
              ),
            ),
            // GestureDetector(
            //   onTap: (){
            //     Navigator.of(context).push(
            //       CupertinoPageRoute(
            //         builder: (context){
            //           return YSMeans(isEdit: true,);
            //         },settings: const RouteSettings(name: 'YSMeans')
            //       ),
            //     );
            //   },
            //   child: Container(
            //     width: MediaQuery.of(context).size.width-10,
            //     height: 50,
            //     margin: EdgeInsets.only(top: 5),
            //     padding: EdgeInsets.only(left: 18,right: 18),
            //     decoration: BoxDecoration(
            //         color: Colors.white,
            //         borderRadius: BorderRadius.all(Radius.circular(6))
            //     ),
            //     child: Row(
            //       mainAxisAlignment: MainAxisAlignment.spaceBetween,
            //       children: [
            //         Text('用户资料',style: TextStyle(color: Color(0xFF292929),fontSize: 14,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
            //         Icon(Icons.chevron_right,size: 20,color: Color(0xFFAEB3BD),)
            //       ],
            //     ),
            //   ),
            // ),
          ],
        ),
      ),
    );
  }

  _getInfo() async{
    SharedPreferences prefer = await SharedPreferences.getInstance();
    setState(() {
      avatar = prefer.getString('avatar');
      name = prefer.getString('name');
    });
  }

  _uploadImageData(var image) async{
    ysUploadFile(context,path: image.path,type: 'avatar',setter: (value) async{
      Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'user/upAvatar', {'path':value['path']});
      if(dict!=null){
        SharedPreferences prefer = await SharedPreferences.getInstance();
        prefer.setString('avatar', '${value['url']}');
        setState(() {
          avatar = '${value['url']}';
        });
      }
    });
    // var dict = await ysRequestHttpNoLoading(context, requestType.get, 'upQiniuToken', {'type':'avatar'});
    // if(dict!=null){
    //   var result = await syStorage.upload('${image.path}', '${dict['token']}', '${dict['path']}');
    //   print('$result');
    //   if(result.success==true){
    //     SharedPreferences prefer = await SharedPreferences.getInstance();
    //     prefer.setString('avatar', '${dict['url']}');
    //     setState(() {
    //       avatar = '${dict['url']}';
    //     });
    //   }
    // }
  }


  getStringWidget(){
    TextEditingController textController = TextEditingController(text: name);
    showDialog(context: context,builder: (context){
      return Dialog(
        backgroundColor: Colors.transparent,
        child: Container(
          width: MediaQuery.of(context).size.width,
          padding: EdgeInsets.all(15),
          height: 150,
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('修改昵称',style: TextStyle(fontSize: 14,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
              Container(
                height: 30,
                width: MediaQuery.of(context).size.width-30,
                child: CupertinoTextField(
                  style: TextStyle(fontSize: 13,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                  placeholderStyle: TextStyle(fontSize: 13,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                  placeholder: '请输入昵称',
                  controller: textController,
                  decoration: BoxDecoration(),
                ),
                //Text('chooseDate',style: TextStyle(fontSize: 13,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                decoration: BoxDecoration(
                    border: Border(bottom: BorderSide(width: 0.5,color: Color(0xFFD7D7D7)))
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(),
                  Row(
                    children: [
                      CupertinoButton(
                        padding: EdgeInsets.all(0),
                        child: Text('取消',style: TextStyle(fontSize: 13,color: Color(0xFF8E1B3C),decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                        onPressed: (){
                          Navigator.pop(context);
                        },
                      ),
                      CupertinoButton(
                        padding: EdgeInsets.all(0),
                        child: Text('确定',style: TextStyle(fontSize: 13,color: Color(0xFF8E1B3C),decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                        onPressed: () async{
                          if(textController.text.isEmpty){
                            return;
                          }
                          Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'user/upSimpleName', {'simple_name':textController.text});
                          if(dict!=null){
                            Navigator.pop(context);
                            setState(() {
                              name = textController.value.text;
                            });
                          }
                        },
                      )
                    ],
                  )
                ],
              )
            ],
          ),
        ),
      );
    });
  }

}

