import 'package:chat/data/WebData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/home/BindCode.dart';
import 'package:chat/home/UserAgreement.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/TokenMgr.dart';
import 'package:chat/utils/app_navigator.dart';
import 'package:chat/utils/local_notification_util.dart';
import 'package:chat/utils/receive_share_file.dart';
import 'package:chat/utils/screen.dart';
import 'package:chat/utils/sound_util.dart';
import 'package:chat/utils/sp_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/FullWithButton.dart';
import '../data/UserData.dart';
import '../utils/HttpUtil.dart';
import '../home/Registerpage.dart';
import '../home/MessagePushPage.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';

import 'PravicySettingPage.dart';

var cardWidth;
Map<String, String> language = {
  "0": "English",
  "1": "Tiếng việt",
  "2": "繁體中文",
  "3": "简体中文",
  "4": "한국어",
  "5": "日本語"
};
BoxDecoration getCardDecoration() {
  return new BoxDecoration(
    color: Colors.white,
  );
}

class SystemEditPage extends StatefulWidget {
  SystemEditPage({Key key}) : super(key: key);

  SystemEditPageState createState() => SystemEditPageState();
}

class SystemEditPageState extends State<SystemEditPage> {
  static const Separate_Size = 15.0;
  String _selectType = UserData().language.toString();
  bool soundPlayMode = false;

  @override
  void initState() {
    super.initState();
    getDefaultSetting();
  }

  void getDefaultSetting() async {
    bool soundPlayMode =
        (await SPUtils.getBool(Constants.SOUND_PLAY_MODE)) ?? false;
    setState(() {
      this.soundPlayMode = soundPlayMode;
    });
  }

  @override
  Widget build(BuildContext context) {
    Size screenSize = MediaQuery.of(context).size;
    cardWidth = screenSize.width;

    return Scaffold(
        appBar: AppBar(
          backgroundColor: AppColors.NewAppbarBgColor,
          title: Text(
            I18n.of(context).setting2,
            style: TextStyle(color: AppColors.NewAppbarTextColor),
            textScaleFactor: 1.0,
          ),
          centerTitle: true,
          leading: CustomUI.buildCustomLeading(context),
        ),
        body: SafeArea(
            child: Container(
                color: AppColors.BackgroundColor,
                height: MediaQuery.of(context).size.height,
                child: SingleChildScrollView(
                  child: _buildBody(),
                ))));
  }

  Widget _buildBody() {
    return Column(
      children: <Widget>[
        SizedBox(height: Separate_Size),
        _buildPravice(),
        SizedBox(height: Separate_Size),
        _buildMsgSetting(),
        SizedBox(height: Separate_Size),
        _buildBasicSetting(),
        SizedBox(height: Separate_Size),
        _clearPictureSetting(),
        _soundPlayModeSetting(),
        SizedBox(height: Separate_Size),
        _buildUserAgreement(),
        _buildBindCode(),
        _buildMyEvaluation(),
        _buildVersion(),
        _buildHelp(),
        SizedBox(height: Separate_Size),
        _buildLogout(),
        SizedBox(height: Separate_Size),
      ],
    );
  }

  //有问题需要帮助
  Widget _buildHelp() {
    return Container(
      margin: EdgeInsets.only(top: Separate_Size),
      padding: EdgeInsets.symmetric(horizontal: 10),
      child: FullWidthButton(
        showRightIcon: false,
        title: I18n.of(context).need_help,
        description: I18n.of(context).need_help2,
        showDivider: false,
        onPressed: () {
          AppNavigator.pushServicePage(context);
        },
      ),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              top: Constants.GreyBorderSide, bottom: Constants.GreyBorderSide)),
    );
  }

  Widget _buildVersion() {
    //版本
    return Container(
      margin: EdgeInsets.only(top: Separate_Size),
      padding: EdgeInsets.symmetric(horizontal: 10),
      child: FullWidthButton(
        showRightIcon: false,
        title: '${I18n.of(context).current_version} ',
        description: Constants.versionName,
        showDivider: false,
        onPressed: () {
//          VersionUtils.versionUpdate(context, fromProfileNeedShow: true);
        },
      ),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              top: Constants.GreyBorderSide, bottom: Constants.GreyBorderSide)),
    );
  }

  Widget _buildMyEvaluation() {
    //版本
    return Container(
      margin: EdgeInsets.only(top: Separate_Size),
      padding: EdgeInsets.symmetric(horizontal: 10),
      child: FullWidthButton(
        showRightIcon: true,
        title: I18n.of(context).my_evaluation,
        showDivider: false,
        onPressed: () async {
          Map data = {
            "userid": UserData().basicInfo.userId,
            "evaluateuserid": UserData().basicInfo.userId,
          };
          data['sign'] = TokenMgr().getSign(data);

          Response res = await HttpUtil()
              .post('evaluate/user/info', data: data, isShowLoading: true);

          Map resData = res.data;
          if (resData['code'] == 0) {
            _buildMyEvaluate(resData['data']);
          }
        },
      ),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              top: Constants.GreyBorderSide, bottom: Constants.GreyBorderSide)),
    );
  }

  void _buildMyEvaluate(data) {
    bool isMan = UserData().isMan();
    var content = Container(
      margin: EdgeInsets.only(top: 10.5),
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              CustomUI.buildBox(
                  data['Friendly'],
                  isMan
                      ? I18n.of(context).courtesy
                      : I18n.of(context).friendly),
              CustomUI.buildBox(
                  data['Interesting'], I18n.of(context).interesting),
              CustomUI.buildBox(data['Refreshing'], I18n.of(context).readily),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              CustomUI.buildBox(data['Patience'],
                  isMan ? I18n.of(context).generous : I18n.of(context).patient),
              CustomUI.buildBox(data['Hello'],
                  isMan ? I18n.of(context).lie : I18n.of(context).indifferent),
              CustomUI.buildBox(
                  data['Unfriendly'],
                  isMan
                      ? I18n.of(context).unfriendly
                      : I18n.of(context).bad_temper),
            ],
          )
        ],
      ),
    );
    CustomUI.buildTip(context, I18n.of(context).your_evaluation, content);
  }

  Widget _buildPravice() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10),
      width: cardWidth,
      child: FullWidthButton(
        title: I18n.of(context).setting,
        showDivider: false,
        onPressed: () {
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (context) {
                return PravicySettingPage();
              },
            ),
          );
        },
      ),
      decoration: getCardDecoration(),
    );
  }

  //消息通知设置
  Widget _buildMsgSetting() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10),
      width: cardWidth,
      child: FullWidthButton(
        title: I18n.of(context).push_setting2,
        showDivider: false,
        onPressed: () {
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (context) {
                return MessagePushPage();
              },
            ),
          );
        },
      ),
      decoration: getCardDecoration(),
    );
  }

  //手机号码·修改密码
  Widget _buildBasicSetting() {
    Widget telePhoneSetting = FullWidthButton(
      title: I18n.of(context).phone_number,
      description: (UserData().mobile == 0 || UserData().mobile == null)
          ? ''
          : UserData().mobile.toString(),
      showDivider: true,
      onPressed: () {
        if (UserData().mobile != null && UserData().mobile != 0) {
          CustomUI.buildOneConfirm(context, I18n.of(context).modify_choose,
              I18n.of(context).determine, () {
            Navigator.of(context).pop();
            Navigator.of(context).push(
              new MaterialPageRoute(
                builder: (context) {
                  return RegisterPage(
                    type: PageType.bindPhone.index,
                  );
                },
              ),
            );
          });
          return;
        }
        Navigator.of(context).push(
          new MaterialPageRoute(
            builder: (context) {
              return RegisterPage(
                type: PageType.bindPhone.index,
              );
            },
          ),
        );
      },
    );

    Widget changePwd = FullWidthButton(
      title: I18n.of(context).change_password,
      showDivider: true,
      onPressed: () {
        if (UserData().mobile == null || UserData().mobile == 0) {
          showToast(I18n.of(context).first_bind);
          return;
        }
        Navigator.of(context).push(
          new MaterialPageRoute(
            builder: (context) {
              return RegisterPage(
                type: PageType.changePWD.index,
              );
            },
          ),
        );
      },
    );

    Widget changeLang = Container(
        padding: EdgeInsets.only(left: 10),
        height: 50,
        child: Row(
          children: <Widget>[
            Text(I18n.of(context).language_set,
                textScaleFactor: 1.0,
                style: TextStyle(fontSize: 14, fontWeight: FontWeight.normal)),
            Expanded(
              child: Container(),
            ),
            Container(
              padding: EdgeInsets.all(0),
              margin: EdgeInsets.all(0),
              child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                items: language.keys.map((key) {
                  return DropdownMenuItem(
                    child: new Text(language[key], textScaleFactor: 1.0),
                    value: key,
                  );
                }).toList(),
                onChanged: (value) {
                  setState(() {
                    _selectType = value;
                    changeLanguage();
                  });
                },
                value: _selectType,
                elevation: 24, //设置阴影的高度
                style: new TextStyle(
                  //设置文本框里面文字的样式
                  color: Constants.BlackTextColor,
                  fontSize: 12,
                ),
                iconSize: 25.0,
              )),
            )
          ],
        ));
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10),
      width: cardWidth,
      child: Column(
        children: <Widget>[
          telePhoneSetting,
          changePwd,
          changeLang,
        ],
      ),
      decoration: getCardDecoration(),
    );
  }

  //修改语言
  void changeLanguage() async {
    HttpUtil().changeLanguage(context, _selectType, () async {
      UserData().language = int.parse(_selectType);
      WebData().changeLoaction(UserData().language);
      //将用户信息存到本地
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setInt(Constants.Language, int.parse(_selectType));
      WebData().getAllData();
      Navigator.of(context)
          .pushNamedAndRemoveUntil('/main', (route) => route == null);
    }, true);

    setStatusBar();

  }

  //清楚图片缓存
  Widget _clearPictureSetting() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10),
      width: cardWidth,
      child: FullWidthButton(
        title: I18n.of(context).clear_cache,
        showDivider: false,
        onPressed: () {
          DefaultCacheManager().emptyCache();
          showToast(I18n.of(context).success);
        },
      ),
      decoration: getCardDecoration(),
    );
  }

  ///切换听筒模式-或外放
  Widget _soundPlayModeSetting() {
    Widget left = new Text(
      I18n.of(context).play_model,
      textScaleFactor: 1.0,
      style: TextStyle(fontSize: 14, fontWeight: FontWeight.normal),
    );
    Widget right = new Expanded(
        child: new Align(
            alignment: Alignment.centerRight,
            child: new Switch(
              value: soundPlayMode,
              activeTrackColor: Colors.blue.withOpacity(0.3),
              onChanged: (bool val) {
                setState(() {
                  soundPlayMode = val;
                });
                SoundUtils.instance.savePlayModeConfig(soundPlayMode);
                print('目前: soundPlayMode $soundPlayMode');
//              setDisableScreenshots();
              },
            )));
    return new Container(
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      margin: EdgeInsets.only(top: 15, bottom: 0),
      padding: EdgeInsets.only(left: 20),
      height: 53,
      child: new Row(
        children: <Widget>[left, right],
      ),
    );
  }

  //用户协议
  Widget _buildUserAgreement() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10),
      width: cardWidth,
      child: FullWidthButton(
        title: I18n.of(context).user_agreement,
        showDivider: false,
        showRightIcon: false,
        onPressed: () async {
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (context) {
                return UserAgreement();
              },
            ),
          );
        },
      ),
      decoration: getCardDecoration(),
    );
  }

  //绑定邀请码
  Widget _buildBindCode() {
    return Container(
      margin: EdgeInsets.only(top: Separate_Size),
      padding: EdgeInsets.symmetric(horizontal: 10),
      width: cardWidth,
      child: FullWidthButton(
        title: I18n.of(context).bind_code,
        description:
            UserData().agentId == 0 ? '' : UserData().agentId.toString(),
        showDivider: false,
        onPressed: UserData().agentId == 0
            ? () {
                if (!UserData().basicInfo.isAttestation) {
                  CustomUI.buildNotTrue(context);
                  return;
                }
                Navigator.of(context).push(
                  new MaterialPageRoute(
                    builder: (context) {
                      return BindCodePage();
                    },
                  ),
                );
              }
            : () {},
      ),
      decoration: getCardDecoration(),
    );
  }

  void _buildConfirmLogout() {
    CustomUI.buildOneConfirm(
        context, I18n.of(context).exit, I18n.of(context).determine, () {
      userLogout();
      HttpUtil().postLoginOut(context);

    });
  }


  static userLogout(){
    LocalNotificationUtil().removeAlias();
    ReceiveShareFile.dispose();
  }


  //退出登陆
  Widget _buildLogout() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10),
      width: cardWidth,
      child: FullWidthButton(
        showRightIcon: false,
        title: I18n.of(context).sign_out,
        showDivider: false,
        onPressed: _buildConfirmLogout,
      ),
      decoration: getCardDecoration(),
    );
  }
}
