import 'package:flutter/cupertino.dart';
import 'package:zhiying_base_widget/pages/privacy_settings_page/bloc/privacy_settings_bloc.dart';
import 'package:zhiying_base_widget/pages/privacy_settings_page/bloc/privacy_settings_repository.dart';
import 'package:zhiying_base_widget/pages/privacy_settings_page/model/privacy_settings_data_model.dart';
import 'package:zhiying_base_widget/pages/privacy_settings_page/model/privacy_settings_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'bloc/privacy_settings_bloc.dart';
import 'bloc/privacy_settings_event.dart';
import 'bloc/privacy_settings_state.dart';

///
/// 隐私设置
///
class PrivacySettingsPage extends StatelessWidget {
  final Map<String, dynamic> data;

  PrivacySettingsPage(this.data);

  @override
  Widget build(BuildContext context) {
    return BlocProvider<PrivacySettingsBloc>(
      create: (_) => PrivacySettingsBloc(PrivacySettingsRepository())..add(PrivacySettingsInitEvent(data)),
      child: _PrivacySettingsContainer(),
    );
  }
}

class _PrivacySettingsContainer extends StatefulWidget {
  @override
  _PrivacySettingsContainerState createState() => _PrivacySettingsContainerState();
}

class _PrivacySettingsContainerState extends State<_PrivacySettingsContainer> {
  /// 列表点击
  void _onClickListItem(Settings model, PrivacySettingsDataModel dataModel) {
    /// 跳转查看隐私协议
    if (model.type == 'hid_url') {
      RouterUtil.openWebview(dataModel.data[model.dataKeys[0]], context);
    }
  }

  /// 隐私开关
  void _switchOnChange(String key, bool value) {
    BlocProvider.of<PrivacySettingsBloc>(context).add(PrivacySettingsUpdateEvent(value: value, key: key));
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<PrivacySettingsBloc, PrivacySettingsState>(
      listener: (context, state) {},
      buildWhen: (prev, current) {
        if (current is PrivacySettingsUpdateErrorState) {
          return false;
        }
        return true;
      },
      builder: (context, state) {
        if (state is PrivacySettingsLoadedState) {
          return _buildMainWidget(state?.model, state.dataModel);
        }
        return _buildEmptyWidget();
      },
    );
  }

  /// 空数据
  Widget _buildEmptyWidget() {
    return Scaffold(
      backgroundColor: HexColor.fromHex('#F9F9F9'),
      appBar: _buildAppBarWidget(null),
      body: Container(),
    );
  }

  /// 有数据
  Widget _buildMainWidget(PrivacySettingsModel model, PrivacySettingsDataModel dataModel) {
    return Scaffold(
      backgroundColor: HexColor.fromHex(model?.bgColor ?? '#F9F9F9'),
      appBar: _buildAppBarWidget(model),
      body: Column(
        children: <Widget>[
          /// 隐私订单
          Container(
            margin: const EdgeInsets.only(top: 5),
            padding: const EdgeInsets.symmetric(horizontal: 12.5),
            color: HexColor.fromHex(model?.settingsBgColor ?? '#FFFFFF'),
            child: _buildHeadWidge(model?.settings, dataModel),
          ),

          /// 隐私协议
          Container(
            margin: const EdgeInsets.only(top: 5),
            padding: const EdgeInsets.symmetric(horizontal: 12.5),
            color: HexColor.fromHex(model?.settingsBgColor ?? '#FFFFFF'),
            child: _buildListWidget(model?.otherSettings, dataModel),
          )
        ],
      ),
    );
  }

  /// 根据列表生成list集合
  Widget _buildHeadWidge(List<Settings> model, PrivacySettingsDataModel dataModel) {
    List<Widget> lists = [];

    int length = model?.length ?? 0;
    if (length == 0) {
      lists.add(Container());
    } else {
      model.forEach((element) {
        lists.add(GestureDetector(
          onTap: () => _onClickListItem(element, dataModel),
          behavior: HitTestBehavior.opaque,
          child: Container(
            margin: const EdgeInsets.symmetric(vertical: 15),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      element?.name ?? '',
                      style: TextStyle(color: HexColor.fromHex(element?.nameColor ?? '#333333'), fontSize: 13, fontWeight: FontWeight.bold),
                    ),
                    Visibility(
                      visible: !EmptyUtil.isEmpty(element?.subName),
                      child: Text(
                        element?.subName ?? '',
                        style: TextStyle(color: HexColor.fromHex(element?.subNameColor ?? '#999999'), fontSize: 11),
                      ),
                    )
                  ],
                ),
                Container(
                  width: 60,
                  height: 15,
                  child: Switch(
                    value: dataModel.data[element.dataKeys[0]] == '1',
                    activeColor: HexColor.fromHex('#FF4B4B'),
                    // trackColor: HexColor.fromHex('#F9F9F9') ,
                    onChanged: (bool value) {
                      _switchOnChange(element.dataKeys[0], value);
                    },
                  ),
                ),
              ],
            ),
          ),
        ));
      });
    }

    return Column(
      children: lists,
    );
  }

  /// 根据列表根据列表生成List集合
  Widget _buildListWidget(List<Settings> model, PrivacySettingsDataModel dataModel) {
    List<Widget> lists = [];

    int length = model?.length ?? 0;
    if (length == 0) {
      lists.add(Container());
    } else {
      model.forEach((element) {
        lists.add(GestureDetector(
          onTap: () => _onClickListItem(element, dataModel),
          behavior: HitTestBehavior.opaque,
          child: Container(
            margin: const EdgeInsets.symmetric(vertical: 15),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  element?.name ?? '',
                  style: TextStyle(color: HexColor.fromHex(element?.nameColor ?? '#333333'), fontSize: 13, fontWeight: FontWeight.bold),
                ),
                Row(
                  children: <Widget>[
                    Text(
                      element?.descText ?? '',
                      style: TextStyle(color: HexColor.fromHex(element?.descColor ?? '#999999'), fontSize: 13),
                    ),
                    const SizedBox(width: 7.5),
                    Icon(
                      Icons.arrow_forward_ios,
                      color: HexColor.fromHex(element?.descColor ?? '#999999'),
                      size: 14,
                    ),
                  ],
                )
              ],
            ),
          ),
        ));
      });
    }

    return Column(
      children: lists,
    );
  }

  /// appBar
  Widget _buildAppBarWidget(PrivacySettingsModel model) {
    return AppBar(
      backgroundColor: HexColor.fromHex(model?.appBarBgColor ?? '#FFFFFF'),
      brightness: Brightness.light,
      leading: IconButton(
        icon: Icon(
          Icons.arrow_back_ios,
          size: 22,
          color: HexColor.fromHex('#333333'),
        ),
        onPressed: () => Navigator.maybePop(context),
      ),
      title: Text(
        model?.appBarName ?? '隐私设置',
        style: TextStyle(color: HexColor.fromHex(model?.appBarNameColor ?? '#333333'), fontSize: 15, fontWeight: FontWeight.bold),
      ),
      centerTitle: true,
      elevation: 0,
    );
  }
}
