import 'dart:io';
import 'package:flutter/material.dart';
import 'package:liftmanager/res/gaps.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/internal/search/search_router.dart';
import 'package:liftmanager/widgets/app_search_bar.dart';
import 'package:liftmanager/utils/image_utils.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'package:liftmanager/widgets/click_item.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/internal/account/provider/user_provider.dart';
import 'package:liftmanager/internal/account/model/user_info_entity.dart';
import 'package:liftmanager/internal/team/team_router.dart';
import 'package:liftmanager/common/user_db.dart';
import 'package:liftmanager/internal/wode/page/edit_text_page.dart';
import 'package:image_picker/image_picker.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:liftmanager/internal/wode/wode_router.dart';
import 'package:flustars/flustars.dart' as FlutterStars;

class PersonalPage extends StatefulWidget {
  // BuyService(this.id);

  // final String id;

  @override
  State<StatefulWidget> createState() {
    return PersonalPageState();
  }
}

class PersonalPageState extends State<PersonalPage>
    with AutomaticKeepAliveClientMixin {
  // PersonalPageState({Key key}) : super(key: key);
  UserProvider provider = UserProvider();
  var _unameController = new TextEditingController();

  FocusNode blankNode = FocusNode();

  @override
  void initState() {
    super.initState();
    //  User().getCurrentUser().then((res){
    //    setUser(res);
    //  });
    getUserInfo();
  }

  ///获取用户信息
  void getUserInfo() {
    ApiService().userInfo(
        onSuccess: (data) {
          print(data);
          setUser(data);
          _unameController.text = provider.user?.signature;
        },
        onError: (code, msg) {});
  }

  void setUser(UserInfoEntity user) {
    print(user.userName);
    print(user.avatarUrl);
    print("8653555------------");
    provider.setUser(user); 
    FlutterStars.SpUtil.putString('username', user.nickName);
    FlutterStars.SpUtil.putString('avatarUrl', user.avatarUrl);
  }

  ///选择图片
  void selectPicker() {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return SimpleDialog(
              title: Text("修改头像"),
              children: ["拍照", '从手机相册选择'].map((String value) {
                print("$value");
                return SimpleDialogOption(
                  child: Text(
                    "${value}",
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                  ),
                  onPressed: () {
                    _getImage(value == '拍照' ? 1 : 0);
                    Navigator.of(context).pop();
                  },
                );
              }).toList());
        });
  }

  void _getImage(int key) async {
    try {
      var _imageFile = await ImagePicker.pickImage(
          source: key == 1 ? ImageSource.camera : ImageSource.gallery,
          maxWidth: 800,
          imageQuality: 95);
      if (_imageFile != null) {
        updateAvatar(_imageFile);
        setState(() {});
      }
    } catch (e) {
      toasts("没有权限，无法打开相册！");
    }
  }

  void updateAvatar(File imageFile) {
    List<File> list = [imageFile];
    ApiService(context: context).uploadMore(list, onSuccess: (imgs) {
      ApiService(context: context).modifyAvatar(imgs[0], onSuccess: (res) {
        if (res != null) {
          getUserInfo();
        }
      }, onError: (code, msg) {
        toasts(msg);
      });
    });
  }

  // 修改用户昵称
  void _modifyName(value) {
    ApiService(context: context).userUpdate(value, onSuccess: (res) {
      // if (res != null) {
      getUserInfo();
      // }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  // 修改用户名
  void _modifyNames(value) {
    ApiService(context: context).userUpdates(value, onSuccess: (res) {
      // if (res != null) {
      getUserInfo();
      // }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  // 修改简介
  void _submit(value) {
    ApiService(context: context).userUpdateJj(value, onSuccess: (res) {
      // if (res != null) {
      toasts("保存成功");
      getUserInfo();
      // }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  @override
  void dispose() {
    // provider.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;

    return ChangeNotifierProvider<UserProvider>(
        create: (_) => provider,
        child: Container(
          child: Scaffold(
            resizeToAvoidBottomPadding: false,
            appBar: MyAppBar(
              centerTitle: "个人资料",
              actions: <Widget>[
                Utils.getAuthByRouter('people_nearby', false) && FlutterStars.SpUtil.getInt("expertFlag") != 1
                    ? FlatButton(
                        child: Text("申请为专家"),
                        textColor: Colours.dark_text,
                        highlightColor: Colors.transparent,
                        onPressed: () {
                          NavigatorUtils.push(context, WodeRouter.masterBecome);
                        },
                      )
                    : Container()
              ],
            ),
            body: GestureDetector(
              onTap: () {
                // 点击空白页面关闭键盘
                FocusScope.of(context).requestFocus(blankNode);
              },
              child: Consumer<UserProvider>(builder: (_, provider, __) {
                return ListView(
                    padding: EdgeInsets.all(0.0),
                    children: <Widget>[
                      ClickItem(
                        title: "头像",
                        hasPicRight: "${provider.user?.avatarUrl ?? ""}",
                        onTap: () {
                          selectPicker();
                          // NavigatorUtils.push(context, BbsRouter.videoDetail);
                        },
                      ),
                      ClickItem(
                        title: "昵称",
                        content: "${provider.user?.nickName ?? ""}",
                        onTap: () {
                          // NavigatorUtils.push(context, BbsRouter.videoDetail);
                          Navigator.of(context).push(
                            MaterialPageRoute(
                              builder: (context) {
                                return EditTextPage(
                                  title: "编辑昵称",
                                  value: provider.user?.nickName ?? "",
                                  mType: 0,
                                );
                              },
                            ),
                          ).then(
                            (value) {
                              print(value);
                              print(123333);
                              if (value != null) {
                                _modifyName(value);
                              }
                            },
                          );
                        },
                      ),
                      ClickItem(
                        title: "名称",
                        content: "${provider.user?.userName ?? ""}",
                        onTap: () {
                          // NavigatorUtils.push(context, BbsRouter.videoDetail);
                          Navigator.of(context).push(
                            MaterialPageRoute(
                              builder: (context) {
                                return EditTextPage(
                                  title: "编辑名称",
                                  value: provider.user?.userName ?? "",
                                  mType: 0,
                                );
                              },
                            ),
                          ).then(
                            (value) {
                              if (value != null) {
                                _modifyNames(value);
                              }
                            },
                          );
                        },
                      ),
                      ClickItem(
                        title: "手机号",
                        content: "${provider.user?.mobile ?? ""}",
                        onTap: () {
                          // NavigatorUtils.push(context, BbsRouter.videoDetail);
                        },
                      ),
                      ClickItem(
                        title: "我的团队",
                        content: "${provider.user?.companyName ?? ""}",
                        onTap: () {
                          // NavigatorUtils.push(context, BbsRouter.videoDetail);
                        },
                      ),
                      ClickItem(
                          title: "团队角色",
                          content: "${provider.user?.roleName ?? ""}"),
                      ClickItem(
                        title: "操作证",
                        content: Constant.certificateStatus[
                            provider.user?.certificateStatus ?? 0],
                        onTap: () {
                          NavigatorUtils.push(
                              context, AccountRouter.certificatePage);
                        },
                      ),
                      ClickItem(
                        title: "团队管理",
                        content: "",
                        onTap: () {
                          NavigatorUtils.push(context, TeamRouter.teamListPage);
                        },
                      ),
                      Container(
                        margin: EdgeInsets.only(bottom: 8),
                        child: ClickItem(
                          title: "团队名片",
                          content: "",
                          onTap: () {
                            NavigatorUtils.push(
                                context, "${TeamRouter.teamUserPage}");
                          },
                        ),
                      ),
                      ClickItem(
                        title: "企业",
                        content: "${provider.user?.companyName ?? ""}",
                        onTap: () {
                          // NavigatorUtils.push(context, BbsRouter.videoDetail);
                        },
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(15),
                                top: ScreenUtil().setWidth(10),
                                bottom: ScreenUtil().setWidth(5)),
                            child: Text(
                              "简介",
                              style: TextStyle(
                                  // fontSize:ScreenUtil().setSp(14),

                                  ),
                              textAlign: TextAlign.left,
                            ),
                          ),
                        ],
                      ),
                      Container(
                        height: 120,
                        // color:Colors.red,
                        decoration: BoxDecoration(
                          border: Border(
                            bottom: BorderSide(width: 0.5, color: Colours.line),
                          ),
                        ),
                        padding: EdgeInsets.only(
                            left: ScreenUtil().setWidth(15),
                            right: ScreenUtil().setWidth(15),
                            bottom: ScreenUtil().setWidth(20)),
                        child: TextFormField(
                            // autofocus: true,
                            // maxLength: 500,
                            cursorColor: Color(0xffcccccc),
                            controller: _unameController,
                            maxLines: 5,
                            decoration: InputDecoration(
                              contentPadding: EdgeInsets.all(0),

                              hintText: '请输入您的简介',
                              hintStyle: TextStyle(color: Color(0xffcccccc)),
                              focusedBorder: InputBorder.none,
                              border: InputBorder.none,
                              // filled: true, // 背景色
                              // fillColor: Colors.cyan.withAlpha(35),
                              // icon: Icon(Icons.person)
                            ),

                            // 校验
                            validator: (val) {
                              return val.trim().length > 0 ? null : "不能为空";
                            }),
                      ),
                      Container(
                        margin: EdgeInsets.only(
                          top: ScreenUtil().setWidth(15),
                          bottom: ScreenUtil().setWidth(15),
                          left: ScreenUtil().setWidth(25),
                          right: ScreenUtil().setWidth(25),
                        ),
                        height: ScreenUtil().setWidth(44),
                        decoration: BoxDecoration(
                          borderRadius:
                              BorderRadius.circular(ScreenUtil().setWidth(22)),
                          gradient: const LinearGradient(
                            colors: [Color(0xFF00D9FF), Color(0xFF0287FF)],
                          ),
                        ),
                        child: FlatButton(
                          // padding: EdgeInsets.all(15.0),
                          child: Text("保存"),
                          textColor: Colors.white,
                          onPressed: () {
                            print(_unameController.text == "");
                            if (_unameController.text == "") {
                              toasts('请输入您上传视频的简介');
                            } else {
                              _submit(_unameController.text);
                            }
                            // if ((_formKey.currentState as FormState).validate()) {
                            //   submit();
                            // }
                          },
                        ),
                      ),
                    ]);
              }),
            ),
          ),
        ));
  }

  @override
  bool get wantKeepAlive => true;
}
