import 'package:chat/data/UserData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/FullWithButton.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:oktoast/oktoast.dart';
import '../data/UserData.dart';
import '../utils/TokenMgr.dart';
import 'WhiteAndBlackList.dart';

enum userDetail {
  open,
  pay,
  apply,
}

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

  _PravicySettingPageState createState() => _PravicySettingPageState();
}

class _PravicySettingPageState extends State<PravicySettingPage> {
  int _socialType = 0;
  bool parkHidden = false;
  bool distanceHidden = false;
  bool msgHidden = false;
  bool strangerHidden = false;
  String money;
  bool isLoadingFish = false;
  setUserDetailData(type, statu, mon, callback) async {
    var data = {
      "userid": UserData().basicInfo.userId,
      "type": type,
      "statu": statu,
    };
    data['sign'] = TokenMgr().getSign(data);
    data["price"] = mon;
    try {
      Response res =
          await HttpUtil().post('user/setting/userprivacy', data: data);
      Map resData = res.data;
      if (resData['code'] == 0) {
        callback();
      } else {
        showToast(resData['msg']);
      }
    } catch (e) {}
  }

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

    print('PravicySettingPage initState');

    getSettingInfo();
  }

  void getSettingInfo() async {
    Map data = {
      "userId": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);
    Response res = await HttpUtil().post('user/get/privacy',
        data: data, failback: () => Navigator.of(context).pop());
    Map resData = res.data;
    print(resData);
    if (resData['code'] == 0 && resData['data'] != null) {
      _socialType = resData['data']['Details'];
      parkHidden = resData['data']['Invisible'] == 1;
      distanceHidden = resData['data']['Distance'] == 1;
      msgHidden = resData['data']['Chat'] == 1;
      strangerHidden = resData['data']['StrangerNews'] == 1;
      Future.delayed(Duration(milliseconds: Constants.CloseLoaindTime), () {
        isLoadingFish = true;
        setState(() {});
      });
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget appBar = new AppBar(
      backgroundColor: AppColors.NewAppbarBgColor,
      title: new Text(
        I18n.of(context).setting,
        textScaleFactor: 1.0,
        style: TextStyle(color: AppColors.NewAppbarTextColor),
      ),
      centerTitle: true,
      leading: CustomUI.buildCustomLeading(context),
    );

    Widget content = Scaffold(
      body: SafeArea(
          child: Center(
        child: Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: _buildBody(),
        ),
      )),
      appBar: appBar,
    );
    return CustomUI.buildPageLoading(context, content, !isLoadingFish);
  }

  Widget _buildBody() {
    return new ListView(
      children: <Widget>[
        _userDetail(),
        _buildSwitchButtom(
            I18n.of(context).hide_me, I18n.of(context).hide_me, parkHidden, () {
          setUserDetailData(4, !parkHidden ? 1 : 0, 0, () {
            setState(() {
              parkHidden = !parkHidden;
            });
          });
        }),
        _buildSwitchButtom(I18n.of(context).hide_distance,
            I18n.of(context).hide_distance, distanceHidden, () {
          setUserDetailData(5, !distanceHidden ? 1 : 0, 0, () {
            setState(() {
              distanceHidden = !distanceHidden;
            });
          });
        }),
        _buildSwitchButtom(
            I18n.of(context).chat_setting, I18n.of(context).chat_me, msgHidden,
            () {
          setUserDetailData(7, !msgHidden ? 1 : 0, 0, () {
            setState(() {
              msgHidden = !msgHidden;
            });
          });
        }),
        _buildSwitchButtom(I18n.of(context).stranger,
            I18n.of(context).receive_stranger, strangerHidden, () {
          setUserDetailData(8, !strangerHidden ? 1 : 0, 0, () {
            setState(() {
              strangerHidden = !strangerHidden;
            });
          });
        }),
        _buildBlackList(),
      ],
    );
  }

  Widget _buildBlackList() {
    //版本
    return Container(
      margin: EdgeInsets.only(top: 20, bottom: 20),
      padding: EdgeInsets.symmetric(horizontal: 5),
      child: FullWidthButton(
        showRightIcon: true,
        title: I18n.of(context).blacklist2,
        showDivider: false,
        onPressed: () {
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (context) {
                return WhiteAndBlackPage(
                  isWhite: false,
                );
              },
            ),
          );
        },
      ),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              top: Constants.GreyBorderSide, bottom: Constants.GreyBorderSide)),
    );
  }

  //下划线
  Widget _buildDivider() {
    return new Container(
      margin: EdgeInsets.zero,
      padding: EdgeInsets.zero,
      decoration:
          BoxDecoration(border: Border(bottom: Constants.GreyBorderSide)),
      height: 1,
      width: MediaQuery.of(context).size.width,
    );
  }

  Widget _buildRadioButtom(str, radio, callback) {
    Widget left = new Text(
      str,
      textScaleFactor: 1.0,
      style: TextStyle(fontSize: 13, color: Constants.BlackTextColor),
    );
    Widget right = new Expanded(
        child: new Align(
      alignment: Alignment.centerRight,
      child: radio,
    ));
    return InkWell(
      onTap: () {
        callback();
      },
      child: Container(
        padding: EdgeInsets.only(left: 15),
        child: new Row(
          children: <Widget>[left, right],
        ),
      ),
    );
  }

  //个人详情
  Widget _userDetail() {
    Widget tip = CustomUI.buildTopTip(15, I18n.of(context).personal_details);
    openCallback() {
      setUserDetailData(1, 1, 0, () {
        setState(() {
          _socialType = userDetail.open.index;
        });
      });
    }

    payCallback() {
      if (UserData().picNum == 0) {
        showToast(UserData().haveReview
            ? I18n.of(context).have_picture_view
            : I18n.of(context).first_upload);
        return;
      }

      var callback = () {
        Navigator.of(context).pop();
        int minMoney = 10;
        var confirm =
            CustomUI.buildConfirmBotton(I18n.of(context).determine, () {
          if (money == null || money == "" || int.parse(money) < minMoney) {
            showToast(I18n.of(context)
                .little_min
                .replaceFirst('/s1', minMoney.toString()));
            return;
          }

          setUserDetailData(2, 1, money, () {
            Navigator.of(context).pop();
            money = '';
            setState(() {
              _socialType = userDetail.pay.index;
            });
          });
        });
        var tip = Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(top: 20),
              child: Text(
                I18n.of(context).set_amount1,
                style: TextStyle(color: Constants.BlackTextColor, fontSize: 16),
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 23, bottom: 25),
              decoration: BoxDecoration(
                  color: Colors.grey[200],
                  borderRadius: BorderRadius.all(Radius.circular(8))),
              child: TextField(
                keyboardAppearance: Brightness.light,
                textAlign: TextAlign.center,
                textInputAction: TextInputAction.search,
                style: TextStyle(
                    textBaseline: TextBaseline.alphabetic, fontSize: 14),
                decoration: InputDecoration(
                  hintText: I18n.of(context).enter_amount,
                  filled: true,
                  contentPadding: EdgeInsets.only(top: 10, bottom: 10),
                  fillColor: Colors.transparent,
                  border: InputBorder.none,
                ),
                keyboardType: TextInputType.phone,
                maxLines: 1,
                inputFormatters: [
                  WhitelistingTextInputFormatter(RegExp("^([1-9][0-9]*)\$")),
                  WhitelistingTextInputFormatter.digitsOnly,
                  LengthLimitingTextInputFormatter(3)
                ],
                onChanged: (str) {
                  money = str;
                },
              ),
            )
          ],
        );
        // var tip = Container(
        //     margin: EdgeInsets.only(top: 20, bottom: 10),
        //     child: TextField(
        //       textAlign: TextAlign.center,
        //       style: TextStyle(
        //           textBaseline: TextBaseline.alphabetic, fontSize: 14),
        //       decoration: InputDecoration(
        //         hintText: I18n.of(context).enter_amount,
        //         hintStyle: TextStyle(fontSize: 14),
        //         contentPadding: EdgeInsets.all(10.0),
        //         border: OutlineInputBorder(
        //           borderRadius: BorderRadius.circular(5.0),
        //         ),
        //       ),
        //       keyboardType: TextInputType.phone,
        //       maxLines: 1,
        //       inputFormatters: [
        //         WhitelistingTextInputFormatter(RegExp("^([1-9][0-9]*)\$")),
        //         WhitelistingTextInputFormatter.digitsOnly,
        //         LengthLimitingTextInputFormatter(3)
        //       ],
        //       onChanged: (str) {
        //         money = str;
        //       },
        //     ));
        var content = CustomUI.buildConfirmContent(tip, confirm);
        CustomUI.buildTip(context, '', content);
      };
      CustomUI.buildOneConfirm(context, I18n.of(context).must_pay,
          I18n.of(context).determine, callback);
    }

    applyCallback() {
      var callback = () {
        setUserDetailData(3, 1, 0, () {
          Navigator.of(context).pop();
          setState(() {
            _socialType = userDetail.apply.index;
          });
        });
      };
      CustomUI.buildOneConfirm(context, I18n.of(context).permission_choose,
          I18n.of(context).determine, callback);
    }

    Widget radio1 = new Radio(
        value: userDetail.open.index,
        groupValue: _socialType, //当value和groupValue一致的时候则选中
        onChanged: (T) {
          openCallback();
        });
    Widget radio2 = new Radio(
        value: userDetail.pay.index,
        groupValue: _socialType, //当value和groupValue一致的时候则选中
        onChanged: (T) {
          payCallback();
        });
    Widget radio3 = new Radio(
        value: userDetail.apply.index,
        groupValue: _socialType, //当value和groupValue一致的时候则选中
        onChanged: (T) {
          applyCallback();
        });

    List<Widget> basicList = [
      _buildRadioButtom(I18n.of(context).public, radio1, openCallback),
      _buildDivider(),
      _buildRadioButtom(I18n.of(context).paid_album, radio2, payCallback),
      _buildDivider(),
      _buildRadioButtom(
          I18n.of(context).need_permission, radio3, applyCallback),
    ];
    var socialCard = new Container(
      color: Colors.white,
      child: new Column(
        children: basicList,
      ),
    );
    return new Column(
      children: <Widget>[tip, socialCard],
    );
  }

  Widget _buildSwitchButtom(title, str, value, callback) {
    Widget tip = CustomUI.buildTopTip(15, title);
    Widget left = Expanded(
        child: Text(
      str,
      textScaleFactor: 1.0,
      style: TextStyle(fontSize: 13, color: Constants.BlackTextColor),
    ));
    Widget right = Container(
        child: new Align(
            alignment: Alignment.centerRight,
            child: new Switch(
              value: value,
              activeTrackColor: Constants.ConfrimButtonColor.withOpacity(0.3),
              onChanged: (bool val) {
                callback();
              },
            )));
    var socialCard = new Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 15),
      height: 53,
      child: new Row(
        children: <Widget>[left, right],
      ),
    );
    return new Column(
      children: <Widget>[tip, socialCard],
    );
  }
}
