import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/message.dart';
import 'package:huixiang/retrofit/data/msg_stats.dart';
import 'package:huixiang/retrofit/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/classic_header.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/no_data_view.dart';
import 'package:huixiang/view_widget/round_button.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class SystemMessagePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _SystemMessagePage();
  }
}

class _SystemMessagePage extends State<SystemMessagePage> {
  ApiService apiService;
  int pageNum = 1;
  List<Message> messages = [];
  Map<String, int> msgNumber = {
    "1": 0,
    "2": 0,
    "3": 0,
    "4": 0,
    "5": 0,
    "6": 0,
  };
  int state = 0;

  @override
  void initState() {
    super.initState();

    SharedPreferences.getInstance().then((value) {
      apiService =
          ApiService(Dio(), token: value.getString("token"), context: context);
      queryMessage();
      queryMsgStats();
    });
  }

  _refresh() {
    pageNum = 1;
    queryMessage();
    queryMsgStats();
  }

  queryMessage() async {
    BaseData<PageInfo<Message>> baseData = await apiService.msgList({
      "pageNum": pageNum,
      "pageSize": 10,
      "searchKey": "",
      "state": "",
      "typed": ""
    }).catchError((onError) {
      _refreshController.loadFailed();
      _refreshController.refreshFailed();
    });

    if (baseData != null && baseData.isSuccess) {
      if (pageNum == 1) {
        messages.clear();
      }
      List<Message> message = [];
      message.addAll(baseData.data.list);
      message.forEach((element) {
        if (element.typed == 2 || element.typed == 3) {
          messages.add(element);
        }
      });
      _refreshController.loadComplete();
      _refreshController.refreshCompleted();
      if (mounted) setState(() {});
      if (pageNum * 10 > int.tryParse(baseData.data.total)) {
        _refreshController.loadNoData();
      } else {
        pageNum += 1;
      }
    } else {
      _refreshController.loadFailed();
      _refreshController.refreshFailed();
    }
  }

  queryMsgStats() async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString("token"),
      );
    }
    BaseData<List<MsgStats>> baseData =
        await apiService.stats().catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      setState(() {
        msgNumber.forEach((key, value) {
          msgNumber[key] = 0;
        });
        baseData.data.forEach((element) {
          if (msgNumber.containsKey(element.name)) {
            msgNumber[element.name] = element.number;
          }
        });
      });
      _refreshController.loadComplete();
      _refreshController.refreshCompleted();
    }
    EasyLoading.dismiss();
  }

  RefreshController _refreshController = RefreshController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: MyAppBar(
      //   background: Colors.white,
      //   leadingColor: Colors.black,
      //   title: S.of(context).xiaoxi,
      //   titleSize: 18.sp,
      //   titleColor: Colors.black,
      //   actions: [
      //     Container(
      //       margin: EdgeInsets.only(right: 16.w),
      //       alignment: Alignment.centerRight,
      //       child: GestureDetector(
      //         onTap: () {
      //           setState(() {
      //             queryMsgStats();
      //           });
      //         },
      //         child: Text(
      //           S.of(context).biaoweiyidu,
      //           style: TextStyle(
      //             fontSize: 16.sp,
      //             fontWeight:MyFontWeight.semi_bold,
      //             color: Color(0xFF353535),
      //           ),
      //         ),
      //       ),
      //     ),
      //   ],
      // ),
      backgroundColor: Colors.white,
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: MyHeader(),
        physics: BouncingScrollPhysics(),
        footer: CustomFooter(
          loadStyle: LoadStyle.ShowWhenLoading,
          builder: (BuildContext context, LoadStatus mode) {
            return (messages.length == 0) ? Container() : MyFooter(mode);
          },
        ),
        controller: _refreshController,
        onRefresh: _refresh,
        onLoading: () {
          setState(() {
            _refresh();
          });
        },
        child: Container(
          child: SingleChildScrollView(
            physics: BouncingScrollPhysics(),
            child: Container(
              padding: EdgeInsets.only(bottom: 30.h),
              child: Column(
                children: [
                  Container(
                    color: Colors.white,
                    padding: EdgeInsets.only(
                        top: MediaQuery.of(context).padding.top + 10.h,
                        bottom: 15.h,right: 16.w),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.of(context).pop();
                          },
                          child: Container(
                            alignment: Alignment.centerRight,
                            margin: EdgeInsets.only(left: 12,),
                            padding: EdgeInsets.all(6),
                            child: Icon(
                              Icons.arrow_back_ios,
                              color: Colors.black,
                              size: 24,
                            ),
                          ),
                        ),
                        Expanded(
                            child: Text(
                          S.of(context).xiaoxi,
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 18.sp,
                            fontWeight: MyFontWeight.bold,
                          ),
                        )),
                        GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            setState(() {
                              queryMsgStats();
                            });
                          },
                          child: Container(
                            padding: EdgeInsets.symmetric(horizontal: 10.w),
                            child: Text(
                              S.of(context).biaoweiyidu,
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 16.sp,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: (){
                      Navigator.of(context).pushNamed('/router/system_details',
                          arguments: {"msgType": 6}).then((value) {
                        setState(() {
                          msgNumber["6"] = 0;
                        });
                      });
                    },
                    child:messageItem("assets/image/icon_pl.webp", S.of(context).pinglun, msgNumber["6"].toString()),
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: (){
                      Navigator.of(context).pushNamed('/router/system_details',
                          arguments: {"msgType": 5}).then((value) {
                        setState(() {
                          msgNumber["5"] = 0;
                        });
                      });
                    },
                    child: messageItem("assets/image/icon_z.webp", S.of(context).dianzan, msgNumber["5"].toString()),
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: (){
                      Navigator.of(context).pushNamed('/router/system_details',
                          arguments: {"msgType": 4}).then((value) {
                        setState(() {
                          msgNumber["4"] = 0;
                        });
                      });
                    },
                    child:messageItem("assets/image/icon_gz.webp", S.of(context).guanzhu,msgNumber["4"].toString()),
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: (){
                      Navigator.of(context).pushNamed('/router/system_notice').then((value) {
                        setState(() {
                          msgNumber["2"] = 0;
                          msgNumber["3"] = 0;
                        });
                      });
                    },
                    child:messageItem("assets/image/icon_system_message.webp", S.of(context).xitongxiaoxi, (msgNumber["2"]+msgNumber["3"]).toString()),
                  ),
                  // newsSurvey(),
                  // SizedBox(
                  //   height: 16.h,
                  // ),
                  // buildMessage(),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget messageItem(img, title, messageNum) {
    return Container(
      padding: EdgeInsets.only(top:14.h, left:14.w, bottom:10.h, right:14.w),
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      child: Column(
        children: [
          Row(
            children: [
              Image.asset(
                img,
                fit: BoxFit.fill,
              ),
              SizedBox(
                width: 12.w,
              ),
              Text(
                title,
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Color(0xFF060606),
                  fontWeight: MyFontWeight.semi_bold,
                ),
              ),
              SizedBox(
                width: 9.w,
              ),
              if(messageNum != "0")
                ((double.tryParse(messageNum) < 100)?
                Container(
                    width: 16,
                    height: 16,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(100),
                      color: Color(0xFFFF441A),
                    ),
                    child: RoundButton(
                      text:messageNum,
                      textColor: Colors.white,
                      fontWeight: MyFontWeight.regular,
                      backgroup: Color(0xFFFF441A),
                      fontSize: 10.sp,
                      radius: 100,
                    )):
                Container(
                    padding: EdgeInsets.symmetric(horizontal:4.w,vertical:2.h),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(100),
                      color: Color(0xFFFF441A),
                    ),
                    child: RoundButton(
                      text:"99+",
                      textColor: Colors.white,
                      fontWeight: MyFontWeight.regular,
                      backgroup: Color(0xFFFF441A),
                      fontSize: 10.sp,
                      radius: 100,
                    ))),
              Spacer(),
              Icon(
                Icons.keyboard_arrow_right,
                size: 24,
              ),
            ],
          ),
          if(title != S.of(context).xitongxiaoxi)
          Container(
            margin: EdgeInsets.only(top: 12.h),
            width: double.infinity,
            height: 1.h,
            color: Color(0xFFF7F7F7),
          )
        ],
      ),
    );
  }

  Widget newsSurvey() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(top: 16.h, bottom: 16.h),
      child: Row(
        children: [
          Expanded(
              child: GestureDetector(
                  onTap: () {
                    Navigator.of(context).pushNamed('/router/system_details',
                        arguments: {"msgType": 5}).then((value) {
                      setState(() {
                        msgNumber["5"] = 0;
                      });
                    });
                  },
                  child: Column(
                    children: [
                      Stack(
                        children: [
                          Image.asset(
                            "assets/image/icon_z.webp",
                            width: 40,
                            height: 40,
                          ),
                          if (msgNumber["5"].toString() != "0")
                            Container(
                              width: 48,
                              alignment: Alignment.topRight,
                              child: Container(
                                  width: 20,
                                  height: 17,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(100),
                                    border: Border.all(
                                      width: 1,
                                      color: Colors.white,
                                      style: BorderStyle.solid,
                                    ),
                                    color: Color(0xFFFF441A),
                                  ),
                                  child: RoundButton(
                                    text: msgNumber["5"].toString(),
                                    textColor: Colors.white,
                                    fontWeight: MyFontWeight.regular,
                                    backgroup: Color(0xFFFF441A),
                                    fontSize: 8.sp,
                                    radius: 100,
                                  )),
                            )
                        ],
                      ),
                      SizedBox(height: 6.h),
                      Text(
                        S.of(context).dianzan,
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: MyFontWeight.medium,
                          color: Color(0xFF060606),
                        ),
                      )
                    ],
                  ))),
          Expanded(
              child: GestureDetector(
                  onTap: () {
                    Navigator.of(context).pushNamed('/router/system_details',
                        arguments: {"msgType": 6}).then((value) {
                      setState(() {
                        msgNumber["6"] = 0;
                      });
                    });
                  },
                  child: Column(
                    children: [
                      Stack(
                        children: [
                          Image.asset(
                            "assets/image/icon_pl.webp",
                            width: 40,
                            height: 40,
                          ),
                          if (msgNumber["6"].toString() != "0")
                            Container(
                              width: 48,
                              alignment: Alignment.topRight,
                              child: Container(
                                  width: 16,
                                  height: 16,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(100),
                                    border: Border.all(
                                      width: 1,
                                      color: Colors.white,
                                      style: BorderStyle.solid,
                                    ),
                                    color: Color(0xFFFF441A),
                                  ),
                                  child: RoundButton(
                                    text: msgNumber["6"].toString(),
                                    textColor: Colors.white,
                                    fontWeight: MyFontWeight.regular,
                                    backgroup: Color(0xFFFF441A),
                                    fontSize: 8.sp,
                                    radius: 100,
                                  )),
                            )
                        ],
                      ),
                      SizedBox(height: 6.h),
                      Text(
                        S.of(context).pinglun,
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: MyFontWeight.medium,
                          color: Color(0xFF060606),
                        ),
                      ),
                    ],
                  ))),
          Expanded(
              child: GestureDetector(
                  onTap: () {
                    Navigator.of(context).pushNamed('/router/system_details',
                        arguments: {"msgType": 4}).then((value) {
                      setState(() {
                        msgNumber["4"] = 0;
                      });
                    });
                  },
                  child: Column(
                    children: [
                      Stack(
                        children: [
                          Image.asset(
                            "assets/image/icon_gz.webp",
                            width: 40,
                            height: 40,
                          ),
                          if (msgNumber["4"].toString() != "0")
                            Container(
                              width: 48,
                              alignment: Alignment.topRight,
                              child: Container(
                                  width: 16,
                                  height: 16,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(100),
                                    border: Border.all(
                                      width: 1,
                                      color: Colors.white,
                                      style: BorderStyle.solid,
                                    ),
                                    color: Color(0xFFFF441A),
                                  ),
                                  child: RoundButton(
                                    text: msgNumber["4"].toString(),
                                    textColor: Colors.white,
                                    fontWeight: MyFontWeight.regular,
                                    backgroup: Color(0xFFFF441A),
                                    fontSize: 8.sp,
                                    radius: 100,
                                  )),
                            )
                        ],
                      ),
                      SizedBox(height: 6.h),
                      Text(
                        S.of(context).guanzhu,
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: MyFontWeight.medium,
                          color: Color(0xFF060606),
                        ),
                      ),
                    ],
                  ))),
        ],
      ),
    );
  }

  Widget buildMessage() {
    return Container(
        color: Colors.white,
        width: double.infinity,
        padding: EdgeInsets.all(20.w),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              S.of(context).xitongxiaoxi,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: MyFontWeight.semi_bold,
                color: Colors.black,
              ),
            ),
            (messages == null || messages.length == 0)
                ? NoDataView(
                    src: "assets/image/icon_empty.webp",
                    isShowBtn: false,
                    text: S.of(context).haimeiyouxiaoxi,
                    fontSize: 16.sp,
                    margin: EdgeInsets.only(top: 120.h),
                  )
                : ListView.builder(
                    padding: EdgeInsets.only(top: 16),
                    itemCount: messages.length,
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    itemBuilder: (context, position) {
                      return GestureDetector(
                        onTap: () {
                          if (messages[position].typed == 2)
                            Navigator.of(context).pushNamed(
                                '/router/system_details',
                                arguments: {"msgType": 2}).then((value) {
                              setState(() {
                                msgNumber["2"] = 0;
                              });
                            });
                          else if (messages[position].typed == 3)
                            Navigator.of(context).pushNamed(
                                '/router/system_details',
                                arguments: {"msgType": 3}).then((value) {
                              setState(() {
                                msgNumber["3"] = 0;
                              });
                            });
                        },
                        child: buildMessageItem(messages[position]),
                      );
                    }),
          ],
        ));
  }

  Widget buildMessageItem(Message message) {
    return Container(
      margin: EdgeInsets.only(top: 8.h, bottom: 8.h),
      // margin: EdgeInsets.only(left: 16.w, right: 16.w, top: 8.h, bottom: 8.h),
      // padding: EdgeInsets.all(20.w),
      // decoration: BoxDecoration(
      //   color: Colors.white,
      //   boxShadow: [
      //     BoxShadow(
      //       color: Colors.black.withAlpha(12),
      //       offset: Offset(0, 3),
      //       blurRadius: 14,
      //       spreadRadius: 0,
      //     )
      //   ],
      //   borderRadius: BorderRadius.circular(8),
      // ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Image.asset(
                (message.typed == 1)
                    ? "assets/image/icon_system_message.webp"
                    : (message.typed == 2)
                        ? "assets/image/icon_system_message.webp"
                        : "assets/image/icon_cz.webp",
                width: 40.w,
                height: 40.h,
              ),
              SizedBox(
                width: 12.w,
              ),
              Expanded(
                  child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Expanded(
                          child: Text(
                        (message.typed == 1)
                            ? S.of(context).xitongtongzhi
                            : (message.typed == 2)
                                ? S.of(context).dingdanxiaoxi
                                : S.of(context).chongzhixiaoxi,
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: MyFontWeight.semi_bold,
                          color: Color(0xFF060606),
                        ),
                      )),
                      Text(
                        message.updateTime,
                        style: TextStyle(
                          fontSize: 10.sp,
                          color: Color(0xFFA29E9E),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 4.h,
                  ),
                  (message.typed != 3)
                      ? Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          // crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Expanded(
                              child: Text(
                                S.of(context).ninyouyigexindedingdan,
                                style: TextStyle(
                                  fontSize: 10.sp,
                                  color: Color(0xFF353535),
                                ),
                              ),
                            ),
                            if (msgNumber["2"].toString() != "0")
                              RoundButton(
                                width: 16,
                                height: 16,
                                text: msgNumber["2"].toString(),
                                textColor: Colors.white,
                                fontWeight: MyFontWeight.regular,
                                backgroup: Color(0xFFFF441A),
                                fontSize: 10.sp,
                                radius: 100,
                              ),
                          ],
                        )
                      : Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          // crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Expanded(
                                child: Text(
                              message.content,
                              style: TextStyle(
                                fontSize: 10.sp,
                                color: Color(0xFF353535),
                              ),
                            )),
                            if (msgNumber["3"].toString() != "0")
                              RoundButton(
                                width: 16,
                                height: 16,
                                text: msgNumber["3"].toString(),
                                textColor: Colors.white,
                                fontWeight: MyFontWeight.regular,
                                backgroup: Color(0xFFFF441A),
                                fontSize: 10.sp,
                                radius: 100,
                              ),
                          ],
                        ),
                ],
              )),
            ],
          ),
          Container(
            margin: EdgeInsets.only(top: 16.h, bottom: 8.h),
            height: 1.h,
            width: double.infinity,
            color: Color(0xFFF7F7F7),
          ),
        ],
      ),
      // Column(
      //   mainAxisAlignment: MainAxisAlignment.center,
      //   crossAxisAlignment: CrossAxisAlignment.start,
      //   children: [
      //     Row(
      //       mainAxisAlignment: MainAxisAlignment.spaceBetween,
      //       crossAxisAlignment: CrossAxisAlignment.center,
      //       children: [
      //         Row(
      //           children: [
      //             Image.asset(
      //               (message.typed == 1)
      //                   ? "assets/image/icon_system_notices.webp"
      //                   : (message.typed == 2)
      //                       ? "assets/image/icon_system_order.webp"
      //                       : "assets/image/icon_system_recharge.webp",
      //               width: 24.w,
      //               height: 24.h,
      //             ),
      //             SizedBox(
      //               width: 4.w,
      //             ),
      //             Text(
      //               (message.typed == 1)
      //                   ? S.of(context).xitongtongzhi
      //                   : (message.typed == 2)
      //                       ? S.of(context).dingdanxiaoxi
      //                       : S.of(context).chongzhixiaoxi,
      //               style: TextStyle(
      //                 fontSize: 14.sp,
      //                 fontWeight: FontWeight.bold,
      //                 color: Color(0xFF060606),
      //               ),
      //             )
      //           ],
      //         ),
      //         Text(
      //           message.updateTime,
      //           style: TextStyle(
      //             fontSize: 10.sp,
      //             color: Color(0xFFA29E9E),
      //           ),
      //         ),
      //       ],
      //     ),
      //     if (message.typed != 3)
      //       Container(
      //         margin: EdgeInsets.only(left: 28.w, top: 12.h),
      //         child: Text(
      //           S.of(context).ninyouyigexindedingdan,
      //           style: TextStyle(
      //             fontSize: 10.sp,
      //             color: Color(0xFF353535),
      //           ),
      //         ),
      //       )
      //     else
      //       Container(
      //         margin: EdgeInsets.only(left: 28.w, top: 18.h),
      //         child: Text(
      //           message.title,
      //           style: TextStyle(
      //             fontSize: 20.sp,
      //             fontWeight: MyFontWeight.semi_bold,
      //             color: Color(0xFF353535),
      //           ),
      //         ),
      //       ),
      //     if (message.typed != 3)
      //       Container(
      //         margin: EdgeInsets.only(left: 28.w, top: 22.h),
      //         child: Row(
      //           mainAxisAlignment: MainAxisAlignment.spaceBetween,
      //           crossAxisAlignment: CrossAxisAlignment.center,
      //           children: [
      //             Text(
      //               S.of(context).chakangengduo,
      //               style: TextStyle(
      //                 fontSize: 12.sp,
      //                 fontWeight: FontWeight.bold,
      //                 color: Color(0xFF353535),
      //               ),
      //             ),
      //             Icon(
      //               Icons.keyboard_arrow_right,
      //               color: Colors.black,
      //             )
      //           ],
      //         ),
      //       )
      //     else
      //       Container(
      //         margin: EdgeInsets.only(left: 28.w, top: 22.h),
      //         child: Text(
      //           message.content,
      //           style: TextStyle(
      //             fontSize: 10.sp,
      //             color: Color(0xFF353535),
      //           ),
      //         ),
      //       ),
      //   ],
      // ),
    );
  }
}