import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:project_telephony/constants/api.dart';
import 'package:project_telephony/model/network/api_client.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:project_telephony/ui/exclude/exclude_contacts_page.dart';
import 'package:project_telephony/ui/exclude/exclude_single_page.dart';
import 'package:project_telephony/ui/home/set/phone_num_list/call_records_list.dart';
import 'package:project_telephony/utils/headers.dart';
import 'package:project_telephony/ui/widget/plone_bottom.dart';
import 'package:project_telephony/utils/toast/cloud_toast.dart';
import 'package:project_telephony/utils/user_tool.dart';
import '../../../base/base_style.dart';

import '../../../model/exclude_phone_model.dart';

import '../../widget/scaffold_theme_widget.dart';
import 'func/exclude_contacts_func.dart';

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

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

class _SpecifyPhonePageState extends State<SpecifyPhonePage> {
  final EasyRefreshController _refreshController = EasyRefreshController();
  List<ExcludePhoneModel> findList = [];
   String name="";
   String phone="";
  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ScaffoldThemeWidget(
      wid: 196,
      title: "指定号码",
      bottom: '添加',
      onTap: () {
        showModalBottomSheet(
            builder: (BuildContext context) {
              return Container(
                width: double.infinity,
                height: 750.w,
                padding: EdgeInsets.symmetric(horizontal: 32.w),
                child: Column(
                  children: [
                    48.hb,
                    Text(
                      "添加号码",
                      style: TextStyle(
                          fontSize: 34.w, fontWeight: FontWeight.bold),
                    ),
                    Expanded(
                        child: ListView(
                      children: [
                        _getAddPhone("通话记录添加", "通过本机通话记录添加号码", () {
                          Navigator.of(context)
                              .push(
                                MaterialPageRoute(
                                    builder: (_) => const CallRecordsList()),
                              )
                              .then((val) =>_refreshController.callRefresh());

                          // Get.to(() => const CallRecordsList());
                        }),
                        _getAddPhone("通迅录添加", "通过本机通讯录添加号码", ()  {
                          Navigator.of(context)
                              .push(
                            MaterialPageRoute(
                                builder: (_) => const ExcludeContactsPage()),
                          )
                              .then((val) =>_refreshController.callRefresh());

                        }),
                        _getAddPhone("添加单个或批量号码", "通过输入号码段添加批量号码", () {
                          Navigator.of(context)
                              .push(
                            MaterialPageRoute(
                                builder: (_) => const ExcludeSinglePage()),
                          )
                              .then((val) =>_refreshController.callRefresh());
                        }),
                      ],
                    )),
                    PloneBottom(
                      onTap: () {
                        Navigator.pop(context);
                      },
                      hPadding: 32,
                      border: true,
                      textColor: const Color(0xFF1890FF),
                      color2: const Color(0xFFF9F9F9),
                      color1: const Color(0xFFF9F9F9),
                      text: "取消",
                    ),
                    32.hb
                  ],
                ),
              );
            },
            context: context);

      },
      child: EasyRefresh(
          firstRefresh: true,
          controller: _refreshController,
          header: MaterialHeader(),
          // footer: MaterialFooter(),
          onRefresh: () async {
            findList = await ExcludeFunc.getContacts();
            UserTool.userProvider.viewLoading();
            // await userProvider.updateUserInfo();

            setState(() {});
          },
          child: findList.isEmpty ? _getNullList() : _getNum()

          // ListView(
          //   children: [findList.isEmpty ? _getNullList() : _getNum()],
          // )

          ),
    );
  }

  _getNum() {
    return ListView.builder(
      itemBuilder: (context, index) {
        return _getNumContant(findList[index],findList[index].id);
      },
      itemCount: findList.length,
    );
  }

  _getNumContant(ExcludePhoneModel item,int id) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: ListTile(
        onTap: () {
          showDialog(
              context: context,
              builder: (context) {
                return CupertinoAlertDialog(
                  title: Text(
                    "修改名称",
                    style: TextStyle(
                        color: BaseStyle.color333333, fontSize: 34.sp),
                  ),
                  content: Column(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "名称",
                            style: TextStyle(
                              fontSize: 28.sp,
                              color: BaseStyle.color999999,
                            ),
                          ),
                          24.hb,
                          CupertinoTextField(
                            padding: EdgeInsets.symmetric(
                                horizontal: 24.w, vertical: 20.w),
                            decoration: BoxDecoration(
                                border: Border.all(color: Colors.white),
                                // borderRadius: BorderRadius.all(
                                //   Radius.circular(4.w)
                                // ),
                                color: const Color(0xFFF9F9F9)),
                            placeholderStyle:
                                const TextStyle(color: BaseStyle.color333333),
                            placeholder: item.remark,
                            onChanged: (value) {
                              name=value;
                              setState(() {});
                            },
                          ),
                          20.hb,
                          Text(
                            "号码",
                            style: TextStyle(
                              fontSize: 28.sp,
                              color: BaseStyle.color999999,
                            ),
                          ),
                          24.hb,
                          CupertinoTextField(
                            padding: EdgeInsets.symmetric(
                                horizontal: 24.w, vertical: 20.w),
                            decoration: BoxDecoration(
                                border: Border.all(color: Colors.white),
                                // borderRadius: BorderRadius.all(
                                //   Radius.circular(4.w)
                                // ),
                                color: const Color(0xFFF9F9F9)),
                            placeholder: item.phone,
                            onChanged: (value) {
                              phone=value;
                              setState(() {});
                            },
                          ),
                          82.hb,
                          // _getUpdate("爸爸", "123123123"),
                          PloneBottom(
                            blM: false,
                            border: true,
                            color1: const Color(0xFF1890FF),
                            color2: const Color(0xFF74BCFF),
                            onTap: () async{
                              Navigator.pop(context);
                              var res=await ExcludeFunc.getUpdate(id, phone, item.remark.isEmpty?name:item.remark);
                              _refreshController.callRefresh();
                              print(res);
                            },
                            text: "保存",
                          )
                        ],
                      ),
                    ],
                  ),
                );
              });
        },
        title: Text(
           item.remark.isEmpty?  item.phone:item.remark,
            style: TextStyle(
                fontSize: 32.sp,
                color: BaseStyle.color333333,
                fontWeight: FontWeight.bold)),
        subtitle: Text(
          item.address,
          style: TextStyle(fontSize: 28.sp, color: BaseStyle.color999999),
        ),
        trailing: TextButton(
          style: ButtonStyle(
              side: MaterialStateProperty.all(
                  BorderSide(width: 2.w, color: const Color(0xFFE8E8E8)))),
          onPressed: () async {
            print(id);
            var res =
                await apiClient.request(API.exclude.delete, data: {"id":id});
            if (res.code == 0) {
              _refreshController.callRefresh();
              CloudToast.show(res.msg);
            } else {
              CloudToast.show(res.msg);
            }
          },
          child: Text(
            "删除",
            style: TextStyle(fontSize: 28.sp, color: BaseStyle.color333333),
          ),
        ),
      ),
    );
  }

  _getAddPhone(String title, String text, VoidCallback widget) {
    return GestureDetector(
      onTap: widget,
      child: ListTile(
        title: Text(
          title,
          style: TextStyle(fontSize: 32.sp, fontWeight: FontWeight.bold),
        ),
        subtitle: Text(
          text,
          style: TextStyle(fontSize: 28.sp, color: BaseStyle.color999999),
        ),
        trailing: const Icon(Icons.chevron_right),
      ),
    );
  }

  _getNullList() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      // crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        490.hb,
        Image.asset(
          Assets.icons.nullphonelist.path,
          width: 240.w,
          height: 212.w,
          fit: BoxFit.fill,
        ),
        48.hb,
        Text(
          "这里是空的",
          style: TextStyle(
              color: const Color(0xFF999999),
              fontWeight: FontWeight.bold,
              fontSize: 36.sp),
        ),
        16.hb,
        Text(
          "还没有添加指定号码",
          style: TextStyle(color: const Color(0xFF999999), fontSize: 28.sp),
        ),
        490.hb,
      ],
    );
  }
}
