/*
 * @author lsy
 * @date   2019-09-04
 **/

import 'dart:async';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:gmalpha_flutter/NewMessageModel/page/messagePage/common.dart';
import 'package:gmalpha_flutter/commonModel/GMBase.dart';
import 'package:gmalpha_flutter/commonModel/base/BaseBuried.dart';
import 'package:gmalpha_flutter/commonModel/base/BaseComponent.dart';
import 'package:gmalpha_flutter/commonModel/base/BasePage.dart';
import 'package:gmalpha_flutter/commonModel/net/Responce/SimpleResponce.dart';
import 'package:gmalpha_flutter/commonModel/picker/base/BasePickerComponent.dart';
import 'package:gmalpha_flutter/res/GMRes.dart';
import 'package:gmalpha_flutter/userModel/page/userSetting/UserSettingModel.dart';
import 'package:gmalpha_flutter/userModel/service/remote/entity/TestUserEntity.dart';
import 'package:gmalpha_flutter/userModel/service/remote/entity/UserEntity.dart';
import 'package:gmalpha_flutter/userModel/util/JumpUtil.dart';

class UserSettingPage extends StatefulWidget {
  UserSettingModel _model;

  UserSettingPage(String userid, String refer) {
    _model = new UserSettingModel(userid, refer);
  }

  @override
  State<StatefulWidget> createState() => UserState(_model);
}

class UserState extends BasePage<UserSettingPage> {
  final UserSettingModel _model;
  TextEditingController _controller = new TextEditingController();
  BaseCenterPicker logoutPicker;
  BaseLoadingItem baseLoadingItem;
  UserLogoutPicker userLogoutPicker;

  UserState(this._model);

  @override
  void initState() {
    super.initState();
    _model.init(context);
    _controller.addListener(() {
      _model.onNameChange(_controller.text);
    });
    logoutPicker = BaseCenterPicker();
    baseLoadingItem = BaseLoadingItem("加载中");
    userLogoutPicker = UserLogoutPicker(() {
      logoutPicker.setPicker(baseLoadingItem);
      logoutPicker.sync();
      _model.quit(context, pageName(), () {
        logoutPicker.dismiss(context);
      });
    }, () {
      logoutPicker.dismiss(context);
    });
    logoutPicker.setPicker(userLogoutPicker);
  }

  @override
  void dispose() {
    super.dispose();
    _model.dispose();
    _controller?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 375, height: 667)..init(context);
    return Scaffold(
      appBar: baseAppBar(
          backClick: () {
            clickEvent(pageName(), "return");
            Navigator.pop(context);
          },
          action: <Widget>[
            StreamBuilder<bool>(
              stream: _model.saveLive.stream,
              initialData: _model.saveLive.data,
              builder: (context, data) {
                if (data.data == null || !data.data) {
                  return Padding(
                    padding: EdgeInsets.only(
                        right: ScreenUtil.instance.setWidth(30)),
                    child: Center(
                      child: baseText("保存", 14, ALColors.ColorC4C4C4),
                    ),
                  );
                } else {
                  return GestureDetector(
                      onTap: () {
                        var picker = BaseCenterPicker()
                          ..setPicker(BaseLoadingItem("加载中"))
                          ..setCancelOutside(true);
                        picker.show(context);
                        _model.save(context);
                      },
                      child: Padding(
                        padding: EdgeInsets.only(
                            right: ScreenUtil.instance.setWidth(30)),
                        child: Center(
                          child: baseText("保存", 14, ALColors.Color323232),
                        ),
                      ));
                }
              },
            )
          ]),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            margin: EdgeInsets.fromLTRB(ScreenUtil.instance.setWidth(29),
                ScreenUtil.instance.setWidth(25), 0, 0),
            child: baseText('设置', 30, ALColors.Color323232),
          ),
          Container(
              width: ScreenUtil.instance.setWidth(127),
              height: ScreenUtil.instance.setWidth(127),
              margin: EdgeInsets.fromLTRB(
                  ScreenUtil.instance.setWidth(26),
                  ScreenUtil.instance.setWidth(23),
                  0,
                  ScreenUtil.instance.setWidth(23)),
              child: GestureDetector(
                onTap: () {
                  clickEvent("page_setting_up","photograph");
                  _model.jumpToCAM(context, pageName());
                },
                child: Stack(
                  alignment: Alignment.bottomRight,
                  children: <Widget>[
                    StreamBuilder<String>(
                      stream: _model.headImgLive.stream,
                      initialData: _model.headImgLive.data,
                      builder: (con, data) {
                        if (data.data == null || data.data.isEmpty) {
//                          return SvgPicture.asset("images/replace_head.svg");
                          return Container();
                        } else {
                          startTime = DateTime.now().millisecondsSinceEpoch;
                          return Container(
                              alignment: Alignment.center,
                              width: ScreenUtil.instance.setWidth(127),
                              height: ScreenUtil.instance.setWidth(127),
                              child: ClipOval(
                                  child: _model.selectImgPath == null
                                      ? SizedBox(
                                          height: double.maxFinite,
                                          width: double.maxFinite,
                                          child: CachedNetworkImage(
                                            imageUrl: data.data,
                                            fit: BoxFit.cover,
                                            placeholder: (con, str) {
                                              return SvgPicture.asset(
                                                  "images/replace_head.svg");
                                            },
                                          ),
                                        )
                                      : SizedBox(
                                          height: double.maxFinite,
                                          width: double.maxFinite,
                                          child: Image.file(
                                            File(data.data),
                                            fit: BoxFit.cover,
                                          ))));
                        }
                      },
                    ),
                    SvgPicture.asset(
                      "images/small_camera.svg",
                    )
                  ],
                ),
              )),
          Column(
            children: <Widget>[
              baseItem(
                  () {},
                  "昵称",
                  StreamBuilder<String>(
                    stream: _model.nameLive.stream,
                    initialData: _model.nameLive.data,
                    builder: (con, data) {
//                      _controller.text = data.data;
                      return Container(
                          width: screenWidth / 4,
                          height: 60,
                          alignment: Alignment.center,
                          child: TextField(
                            autofocus: false,
                            textInputAction: TextInputAction.done,
                            style: TextStyle(
                                fontSize: 13, color: ALColors.Color323232),
                            controller: _controller,
                            textAlign: TextAlign.right,
                            maxLines: 1,
                            decoration: InputDecoration(
                              hintText: data.data,
//                              hintStyle: TextStyle(
//                                  fontSize: 13, color: ALColors.Color323232),
                              border: InputBorder.none,
                            ),
                          ));
                    },
                  ),
                  false),
              baseDivide(1, 30, ALColors.ColorE4E4E4),
              baseItem(() {
                _model.jumpToCTY(context, pageName());
              },
                  "国家",
                  StreamBuilder<String>(
                    stream: _model.cityLive.stream,
                    initialData: _model.cityLive.data,
                    builder: (con, data) {
                      return Container(
                        margin: EdgeInsets.only(
                            right: ScreenUtil.instance.setWidth(19)),
                        child:
                            baseText(data.data ?? "", 13, ALColors.Color323232),
                      );
                    },
                  ),
                  true),
              baseDivide(1, 30, ALColors.ColorE4E4E4),
              baseItem(() {
                jumpToComment(context, pageName());
              }, "意见与建议", null, true),
              baseDivide(1, 30, ALColors.ColorE4E4E4),
//              baseItem(() {}, "隐私声明", null, true),
//              baseDivide(1, 30, ALColors.ColorE4E4E4),
            ],
          ),
          Expanded(
            child: Container(),
          ),
          Container(
            width: double.maxFinite,
            height: 45,
            margin: EdgeInsets.only(
                bottom: ScreenUtil.instance.setHeight(30),
                left: ScreenUtil.instance.setWidth(30),
                right: ScreenUtil.instance.setWidth(30)),
            child: OutlineButton(
              onPressed: () {
                clickEvent("page_setting_up", "quit");
                logoutPicker.show(context);
              },
              child: baseText("退出登录", 14, ALColors.Color323232),
              borderSide: new BorderSide(color: Color(0xff323232)),
            ),
          )
        ],
      ),
    );
  }

  baseItem(VoidCallback ontap, String left, Widget center, bool needRight) {
    return GestureDetector(
        onTap: () => ontap(),
        child: Container(
          margin: EdgeInsets.only(
              right: ScreenUtil.instance.setWidth(30),
              left: ScreenUtil.instance.setWidth(30)),
          height: 60,
          width: double.maxFinite,
          child: Row(
            children: <Widget>[
              baseText(left, 13, ALColors.Color323232),
              Expanded(
                child: SizedBox(
                  height: double.maxFinite,
                  child: Text(""),
                ),
              ),
              center ?? Container(),
              needRight
                  ? SvgPicture.asset("images/right_arrow.svg")
                  : Container()
            ],
          ),
        ));
  }

  @override
  void reassemble() {
    super.reassemble();
    _model.dispose();
  }

  @override
  String pageName() {
    return "page_setting_up";
  }

  @override
  String referrer() {
    return _model.refere;
  }
}

class UserLogoutPicker implements ICenterPicker {
  VoidCallback sure;
  VoidCallback cancel;

  UserLogoutPicker(this.sure, this.cancel);

  @override
  Widget build(BuildContext context) {
    return Container(
        width: ScreenUtil.instance.setWidth(270),
        height: ScreenUtil.instance.setHeight(200),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10.0),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(
                  top: ScreenUtil.instance.setHeight(20),
                  bottom: ScreenUtil.instance.setHeight(20)),
              child: baseText("提示", 22, ALColors.Color8E8E8E),
            ),
            baseText("确定要退出当前账号", 13, ALColors.Color8E8E8E),
            Expanded(
              child: Container(),
            ),
            baseDivide(1, 0, ALColors.ColorE4E4E4),
            GestureDetector(
                onTap: sure,
                child: Container(
                  alignment: Alignment.center,
                  height: 50,
                  width: double.maxFinite,
                  child: baseText("确定", 16, ALColors.Color0093FF),
                )),
            baseDivide(1, 0, ALColors.ColorE4E4E4),
            GestureDetector(
                onTap: cancel,
                child: Container(
                  height: 50,
                  alignment: Alignment.center,
                  width: double.maxFinite,
                  child: baseText("取消", 16, ALColors.Color999999),
                )),
          ],
        ));
  }
}
