import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:zhiying_base_widget/dialog/global_dialog/intellect_search_goods_dialog/model/Intellect_search_set_model.dart';
import 'package:zhiying_base_widget/dialog/global_dialog/intellect_search_goods_dialog/model/intellect_dialog_data_model.dart';
import 'package:zhiying_base_widget/utils/contants.dart';
import 'package:zhiying_comm/util/shared_prefe_util.dart';

import 'intellect_search_goods_dialog.dart';
import 'intellect_search_no_goods_dialog.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:string_validator/string_validator.dart';

class IntellectCreate {
  static IntellectSearchSetModel _setModel;
  static bool isRequest = false;

  ///判断规则
  static checkAndCreate(AppLifecycleState state, BuildContext context) async {
    if (state == AppLifecycleState.resumed && !isRequest) {
      isRequest = true;
      _requestSetData(context);
    }
    // Timer(Duration(milliseconds: 500), () async {
    //   if (!Constants.isShowIntellectDialog) {
    //     Constants.isShowIntellectDialog = true;
    //     await showDialog(
    //         context: context, child: IntellectSearchGoodsDialog());
    //   Constants.isShowIntellectDialog = false;
    // }
    // });
  }

  ///请求设置参数
  static _requestSetData(BuildContext context) async {
    if (_setModel == null) {
      var param = {"webId": ""};

      //请求参数
      await NetUtil.request('/api/v1/cfg/clipboard_base', params: param,
          onSuccess: (data) async {
        print("设置参数" + data.toString());

        ///检查是否已缓存过设置信息
        String result = await SharedPreferencesUtil.getStringValue(
            Constants.spIsCacheSetModel);
        _setModel = IntellectSearchSetModel.fromJson(
            json.decode(data['clipboard_base']));
        if (result.isEmpty) {
          validate(context, _setModel);
        }
        SharedPreferencesUtil.setNetCacheResult(
            Constants.spIsCacheSetModel, data['clipboard_base']);
      });

      isRequest = false;

      ///拿缓存数据
      var cacheData = await SharedPreferencesUtil.getNetCacheResult(
          Constants.spIsCacheSetModel);

      ///如果存在缓存直接进入验证阶段
      if (cacheData != null) {
        _setModel = IntellectSearchSetModel.fromJson(cacheData);
        validate(context, _setModel);
      }
    } else {
      validate(context, _setModel);
      isRequest = false;
    }
  }

  static checkAndCreateFirst(BuildContext context) async {
    ///检查规则
    IntellectCreate.checkAndCreate(AppLifecycleState.resumed, context);
  }

  ///请求数据打开弹窗
  static requestDialog(BuildContext context, String content) async {
    content =
        "6緮置内容 Http:/T¢ZKkjceixTjW¢转移至ta0寶【URBANISTA/爱班Stockholm斯德哥尔摩 真无线蓝牙运动耳机半入耳式】";
    var params = {"content": content};
     NetUtil.request("/api/v1/clipboard/parse",
        params: params, method: NetMethod.POST, onSuccess: (data) async {
      isRequest = false;
      if (data == null || data.toString().length == 0) {
        if (!Constants.isShowIntellectDialog) {
          Constants.isShowIntellectDialog = true;
          await showDialog(
              context: context, child: IntellectSearchNoGoodsDialog());
          Constants.isShowIntellectDialog = false;
        }
      } else {
        IntellectDialogDataModel model =
            IntellectDialogDataModel.fromJson(data);
        if (!Constants.isShowIntellectDialog) {
          Constants.isShowIntellectDialog = true;
          await showDialog(
              context: context,
              child: IntellectSearchGoodsDialog(
                model: model,
              ));
          Constants.isShowIntellectDialog = false;
        }
      }
    });
  }

  ///检查字段是否被监听
  static void validate(
      BuildContext context, IntellectSearchSetModel setModel) async {
    ClipboardData data = await Clipboard.getData(Clipboard.kTextPlain);
    String content = data?.text ?? "";
    // //是否监听
    // if (setModel.isListen != "1") {
    //   return;
    // }
    //
    // if(content==null||content.length==0){
    //   return;
    // }
    // ///长度大小限制
    // if (setModel.isKeyLength == "1" &&
    //         (int.tryParse(setModel.keyLengthMin) > content.length) ||
    //     (int.tryParse(setModel.keyLengthMax) < content.length)) {
    //   return;
    // }
    //
    // //是否纯数字
    // if (setModel.isNumber == "1" && isNumeric(content)) {
    //   return;
    // }
    //
    // ///是否纯字母
    // if (setModel.isLetter == "1" && isAlpha(content)) {
    //   return;
    // }
    //
    // ///是否仅包含数字和字母
    // if (setModel.isNumAndLet == "1" && isAlphanumeric(content)) {
    //   return;
    // }

    ///是否包含某个排除词
    if (setModel.banWords != null && setModel.banWords.length > 0) {
      for (var item in setModel.banWords) {
        if (contains(content, item)) {
          return;
        }
      }
    }
    requestDialog(context, content);
  }
}
