import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:zhiying_base_widget/dialog/global_dialog/policy_dialog/policy_confirm_dialog.dart';
import 'package:zhiying_base_widget/dialog/global_dialog/policy_dialog/policy_dialog_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class PolicyDialog extends StatefulWidget {
  final PolicyDialogModel model;

  const PolicyDialog(this.model, {Key key}) : super(key: key);

  static Future<bool> show(BuildContext context) async {
    Map json =
    await NetUtil.post('/api/v1/app/permissions', method: NetMethod.GET);
    PolicyDialogModel model =
    PolicyDialogModel.fromJson(Map<String, dynamic>.from(json['data']));
    bool agree = null;
    while (agree == null) {
      agree = await showCupertinoDialog(
          context: context, builder: (_) => PolicyDialog(model));
    }
    if (agree) {
      return agree;
    }
    bool accept = null;
    while (accept == null) {
      accept = await showCupertinoDialog(
          context: context,
          builder: (_) => PolicyConfirmDialog(model.subDialog));
    }
    return accept;
  }

  @override
  _PolicyDialogState createState() => _PolicyDialogState();
}

class _PolicyDialogState extends State<PolicyDialog> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Center(
        child: Container(
          padding: EdgeInsets.all(15),
          width: 290,
          height: 360,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(13), color: Colors.white),
          child: Column(
            children: <Widget>[
              Text(
                widget.model?.title ?? '',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.only(top: 8.0, bottom: 8.0),
                  child: SingleChildScrollView(
                    child: _createText(),
                  ),
                ),
              ),
              Row(
                children: <Widget>[
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        Navigator.pop(context, false);
                      },
                      child: Container(
                        height: 36,
                        child: Center(
                          child: Text(
                            widget.model?.leftBfnText ?? '',
                            style: TextStyle(
                                color: HexColor.fromHex(
                                    widget.model?.leftBfnTextColor ?? '')),
                          ),
                        ),
                        decoration: BoxDecoration(
                            color: HexColor.fromHex(
                                widget.model?.leftBfnBgColor ?? '#ffffff'),
                            borderRadius: BorderRadius.circular(18),
                            border:
                            Border.all(color: Color(0xffd8d8d8), width: 1)),
                      ),
                    ),
                  ),
                  Container(
                    width: 30,
                  ),
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        Navigator.pop(context, true);
                      },
                      child: Container(
                        height: 36,
                        child: Center(
                          child: Text(
                            widget.model?.rightBfnText ?? '',
                            style: TextStyle(
                                color: HexColor.fromHex(
                                    widget.model?.rightBfnTextColor ?? '')),
                          ),
                        ),
                        decoration: BoxDecoration(
                          color: HexColor.fromHex(
                              widget.model?.rightBfnBgColor ?? ''),
                          borderRadius: BorderRadius.circular(18),
                        ),
                      ),
                    ),
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _createText() {
    String content = widget.model?.content ?? '';
    Map<int, PolicyItemModel> replaces = Map();
    List<int> indexs = List();
    widget.model?.selectedText?.forEach((replace) {
      int index = content.indexOf(replace.key);
      indexs.add(index);
      replaces[index] = replace;
      // Logger.debug(replace.key);
    });
    // 倒序，从后面开始替换
    indexs.sort((a, b) {
      return b.compareTo(a);
    });
    List<TextSpan> texts = List();
    int end = content.length - 1;
    for (int index in indexs) {
      // Logger.debug(index);
      PolicyItemModel replace = replaces[index];
      texts.insert(0,
        TextSpan(
          text: content.substring(index + replace.key.length, end),
        ),
      );
      texts.insert(0,
        TextSpan(
          text: replace?.text ?? '',
          recognizer: TapGestureRecognizer()
            ..onTap = () {
              NativeUtil.openUrl(context, replace?.url ?? '');
            },
          style: TextStyle(
            color: HexColor.fromHex(widget.model?.selectedColor ?? '#FF4242'),
          ),
        ),
      );
      end = index;
    }
    if (end != 0) {
      texts.insert(0,
        TextSpan(
          text: content.substring(0, end),
        ),
      );
    }

    return RichText(
      textAlign: TextAlign.left,
      text: TextSpan(
        text: '',
        style: TextStyle(
          height: 1.2,
          fontSize: 12,
          color: HexColor.fromHex('#555555'),
        ),
        children: texts,
      ),
    );
  }
}
