import 'package:bot_toast/bot_toast.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:project_telephony/base/base_style.dart';
import 'package:project_telephony/ui/login/login_page.dart';
import 'package:project_telephony/ui/tab_navigator.dart';
import 'package:project_telephony/ui/user/content_authority_page.dart';
import 'package:project_telephony/ui/user/members_page.dart';
import 'package:project_telephony/ui/user/privacy_rights_page.dart';
import 'package:project_telephony/ui/widget/image_scaffold.dart';
import 'package:project_telephony/ui/widget/plone_bottom.dart';
import 'package:project_telephony/utils/headers.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:telephony/telephony.dart';
import '../../constants/api.dart';
import '../../model/network/api_client.dart';
import '../../providers/user_provider.dart';
import '../../utils/hive_store.dart';
import '../../utils/toast/cloud_toast.dart';
import '../../utils/user_tool.dart';
import '../home/call.dart';
import '../widget/appdialog.dart';
import 'content_details_page.dart';

import '../home/home_page.dart';

class UserPage extends StatefulWidget {
  const UserPage({Key? key}) : super(key: key);

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

final Telephony telephony = Telephony.instance;

class _UserPageState extends State<UserPage> {
  // bool vle = PermissionStatus.denied.isGranted;
  //bool vle =PermissionStatus.denied.isGranted;
  final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

  final userProvider = Provider.of<UserProvider>(Get.context!, listen: false);
  bool isVip = false;
  DateTime? _lastTap;
  late bool vle = false;
  final service = FlutterBackgroundService();
  final EasyRefreshController _easyRefreshController = EasyRefreshController();
  String? endDate;

  @override
  void dispose() {
    _easyRefreshController.dispose();
    super.dispose();
  }
  // _load() async {
  //   // print("123123131313131231231231231313123131232311313131231231");
  //   vle = await service.isRunning();
  // }
  @override
  void initState() {
    super.initState();
    // showDialog(context: context, builder: (context){
    //   return const AppDialog();
    // });
    // _easyRefreshController.callRefresh();
    // UserTool.userProvider.updateUserInfo();
    // if (UserTool.userProvider.isLogin) {
    //
    //   // print(UserTool.userProvider.userInfo.end * 1000);
    //   // print(DateTime.now().millisecondsSinceEpoch);
    //   // if (UserTool.userProvider.userInfo.isVip != 1) {
    //   //   isVip = false;
    //   //   vle = false;
    //   // } else {
    //   //   isVip = true;
    //   //   vle = await service.isRunning();
    //   // }
    //   //service.isRunning() as bool;
    //   // endDate = DateUtil.formatDateMs(
    //   //     UserTool.userProvider.userInfo.end * 1000,
    //   //     format: DateFormats.y_mo_d);
    // }
    // else {
    //   vle = false;
    // }
  }
  // getRes() async{
  //   var res=await apiClient.request(API.app.trialVip);
  //   if(res.code==0){
  //     showDialog(context: context, builder: (context){
  //       return const AppDialog();
  //     });
  //   }
  // }
  @override
  Widget build(BuildContext context) {

    return CloudScaffold(
      systemStyle: const SystemUiOverlayStyle(
        statusBarIconBrightness: Brightness.dark,
        // systemNavigationBarColor: Colors.white,
      ),
      path: Assets.images.bg.path,
      bodyColor: Colors.white,
      extendBody: true,
      body: Expanded(child:  Column(
        children: [
      Expanded(
      child:EasyRefresh(
            firstRefresh: true,
            header: MaterialHeader(),
            onRefresh: () async {
              // _load();
              _getRequests();
              // await UserTool.userProvider.updateUserInfo();
                    if (UserTool.userProvider.isLogin) {
                    // var res=await apiClient.request(API.app.trialVip);
                      if(UserTool.userProvider.userInfo.isTrial!=0){
                        showDialog(context: context, builder: (context){
                          return const AppDialog();
                        });
                      }
                      // print(UserTool.userProvider.userInfo.end * 1000);
                      // print(DateTime.now().millisecondsSinceEpoch);

                      if (UserTool.userProvider.userInfo.isVip != 1) {
                        isVip = false;
                        vle = false;
                      } else {
                        isVip = true;
                        vle = await service.isRunning();
                      }
                      //service.isRunning() as bool;
                      // endDate = DateUtil.formatDateMs(
                      //     UserTool.userProvider.userInfo.end * 1000,
                      //     format: DateFormats.y_mo_d);
                    } else {
                      vle = false;
                    }
              setState(() {});
            },child:ListView(children: [
          _getUser(),
          72.hb,
          _getBanner(),
          120.hb,
          _getSwitch2(),
          _getSwitch(Assets.icons.privacy.path, "隐私政策", false),
          _getSwitch(Assets.icons.permissions.path, "权限说明", false),
          _getSwitch(Assets.icons.sms.path, "短信标签", false),
          // const Spacer(),
          182.hb,
          UserTool.userProvider.isLogin
              ? PloneBottom(
            border: false,
            onTap: () async {
              var cancel = CloudToast.loading;
              var base = await apiClient.request(API.app.logout,
                  showMessage: true);
              if (base.code == 0) {
                UserTool.userProvider.logout();
                Get.offAll(const TabNavigator());
              }
              cancel();
            },
            textColor: const Color(0xFF1890FF),
            color1: const Color(0xFFEBF5FF),
            color2: const Color(0xFFEBF5FF),
            text: "退出登录",
          )
              : const SizedBox()],) )


      ),],
      ),)


    );
  }

  //头像
  _getUser() {
    return Container(
      margin: EdgeInsets.only(left: 64.w, right: 64.w, top: 216.w),
      child: Row(
        children: [
          GestureDetector(
            onTap: () {
              if (!userProvider.isLogin) {
                Get.to(() => const LoginPage());
              }
            },
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  UserTool.userProvider.isLogin
                      ? UserTool.userProvider.userInfo.name
                      : "登录/注册",
                  // UserTool.userProvider.userInfo.name ,
                  style: TextStyle(
                      fontSize: BaseStyle.fontSize48,
                      color: BaseStyle.color333333,
                      fontWeight: FontWeight.bold),
                ),
                24.hb,
                Text(
                  UserTool.userProvider.isLogin ? "欢迎您登录短信帮手" : "登录获取更多信息",
                  style: TextStyle(
                      fontSize: BaseStyle.fontSize28,
                      color: BaseStyle.color333333),
                )
              ],
            ),
          ),
          const Spacer(),
          GestureDetector(
            onTap: () async {
              // var value = await CloudImagePicker.pickSingleImage(title: '选择图片');
              // if (value != null) {
              //   BotToast.showText(text: '头像成功');
              //   setState(() {});
              // }//暂时不开放头像更改
            },
            child: ClipOval(
              child: Image.asset(
                UserTool.userProvider.isLogin
                    ? Assets.images.portraitDeep.path
                    : Assets.images.portrait.path,
                height: 128.w,
                width: 128.w,
                fit: BoxFit.cover,
              ),
            ),
          )
        ],
      ),
    );
  }

//banner
  _getBanner() {
    return SizedBox(
      // margin: EdgeInsets.symmetric(horizontal: 32.w),
      height: 144.w,
      child: Stack(
        children: [
          Align(
              child: SizedBox(
            width: 622.w,
            child: Image.asset(
              Assets.images.banner.path,
              fit: BoxFit.fill,
            ),
          )),
          Positioned(
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 112.w, vertical: 24.w),
              // margin: EdgeInsets.symmetric(horizontal: 64.w, vertical: 16.w),
              // padding: EdgeInsets.symmetric(),
              child: Row(
                children: [_getText(), const Spacer(), _getBotton()],
              ),
            ),
          ),
        ],
      ),
    );
  }

  _getRequests() async {
    endDate = DateUtil.formatDateMs(
        UserTool.userProvider.userInfo.end * 1000,
        format: DateFormats.y_mo_d);
    UserTool.userProvider.updateUserInfo();
    if (UserTool.userProvider.isLogin) {
      // print(UserTool.userProvider.userInfo.end * 1000);
      // print(DateTime.now().millisecondsSinceEpoch);
      if (UserTool.userProvider.userInfo.isVip != 1) {
        isVip = false;
        vle = false;
      } else {
        isVip = true;
        vle = await service.isRunning();
      }
      //service.isRunning() as bool;
      // endDate = DateUtil.formatDateMs(
      //     UserTool.userProvider.userInfo.end * 1000,
      //     format: DateFormats.y_mo_d);
    } else {
      vle = false;
    }
    setState(() {});
  }

//banner botton
  _getBotton() {
    return GestureDetector(
      onTap: () {
        if (userProvider.isLogin) {
          Navigator.of(context)
              .push(
                MaterialPageRoute(builder: (_) => const MembersPage()),
              )
              .then((val) => _getRequests());
        } else {
          BotToast.showText(text: '您还未登录,请先登录!');
        }
      },
      child: Container(
          padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 16.w),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(30.w),
              gradient: const LinearGradient(
                  colors: [Color(0xFFFFF6D8), Color(0xFFFFEAB0)],
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight)),
          child: Text(
            isVip ? "立即续费" : "立即购买",
            style: TextStyle(
                color: const Color(0xFF001F3F), fontSize: BaseStyle.fontSize24),
          )),
    );
  }

//banner 文字
  _getText() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _getVip(),
        16.hb,
        Text(
          isVip ? "${DateUtil.formatDateMs(UserTool.userProvider.userInfo.end * 1000, format: DateFormats.y_mo_d)}到期" : "解锁全部功能",
          style: TextStyle(color: Colors.white, fontSize: BaseStyle.fontSize24),
        )
      ],
    );
  }

  _getVip() {
    return Row(
      children: [
        Text(
          "VIP",
          style: TextStyle(
              color: const Color(0xFFFFEAB0),
              fontFamily: "BlackItalic",
              fontSize: 32.sp),
        ),
        Container(
          width: 8.w,
          height: 8.w,
          alignment: Alignment.center,
          margin: EdgeInsets.symmetric(horizontal: 8.w),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(4),
            color: const Color(0xFFFFEAB0),
          ),
        ),
        Text(
          isVip ? "已成为会员" : "未开通会员",
          style: const TextStyle(
              color: Color(
                0xFFFFEAB0,
              ),
              fontWeight: FontWeight.w700),
        )
      ],
    );
  }
//内容
  _getSwitch2() {
    return Container(
        padding: EdgeInsets.symmetric(horizontal: 32.w),
        child: ListTile(
          // onTap: (() {}),
          leading: Image.asset(
            Assets.icons.switch1.path,
            height: 54.w,
            width: 56.w,
            fit: BoxFit.fill,
          ),
          title: Text(
            "功能开关",
            style: TextStyle(
                color: BaseStyle.color333333,
                fontSize: BaseStyle.fontSize34,
                fontWeight: FontWeight.bold),
          ),
          trailing: Switch(
              value: vle,
              onChanged: (value) async {
                final SharedPreferences prefs = await _prefs;
                // if(!value){
                //
                // }
                // await prefs.setBool("kg", value);
                // print("这是数据${prefs.getBool("kg")}");
                setState(() {

                  if (isVip) {
                    vle = value;
                    // prefs.setBool("kg", vle);
                    //  initializeService();
                    if (vle) {
                      print("true");
                      prefs.remove("kg");
                      prefs.setBool("kg", vle);
                      service.startService();
                      // WidgetsFlutterBinding.ensureInitialized();
                      // initializeService();
                      // UserTool.userProvider.setKg(vle)
                      // initializeService();
                      initializeService();
                      BotToast.showText(text: " 你开启了该功能");
                      // initializeService();
                      // print("这是数据${prefs.getBool("kg")}");
                    } else {
                      prefs.remove("kg");
                      prefs.setBool("kg", vle);
                      service.invoke("stopService");
                      ///有问题??
                      // exit(0);
                      // UserTool.userProvider.setKg(vle);
                      // prefs.setBool("kg", false);
                      // initializeService();

                      BotToast.showText(text: "你已经关闭该功能");
                      // print("这是数据${prefs.getBool("kg")}");
                    }
                  } else {
                    BotToast.showText(text: "还没有开通会员,不可使用该功能");
                  }
                }
                  );
              }),
        ));
  }

  _getSwitch(String url, String name, bool pd) {
    return GestureDetector(
      onTap: () async {
        if (!pd) {
          switch (name) {
            case "短信标签":
              Get.to(() => ContentDetailsPage(
                    content: UserTool.userProvider.isLogin
                        ? UserTool.userProvider.userInfo.tag
                        : "",
                    ploneBack: (String textContent) {
                      // print("这是数据" + textContent);
                      // textList.setAll(index, {textContent});
                    },
                  ));
              break;
            case "隐私政策":
              Get.to(() => const ContentAuthorityPage());
              break;
            case "权限说明":
              Get.to(() => PrivacyRightsPage(
                    name: name,
                  ));
              break;
            default:
              break;
          }
        }
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 32.w),
        child: ListTile(
            // onTap: (() {}),
            leading: Image.asset(
              url,
              height: 54.w,
              width: 56.w,
              fit: BoxFit.fill,
            ),
            title: Text(
              name,
              style: TextStyle(
                  color: BaseStyle.color333333,
                  fontSize: BaseStyle.fontSize34,
                  fontWeight: FontWeight.bold),
            ),
            trailing: const Icon(Icons.keyboard_arrow_right)),
      ),
    );
  }
}