import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:special_equipment_flutter/common/color_const.dart';
import 'package:special_equipment_flutter/common/edgeInsets_const.dart';
import 'package:special_equipment_flutter/common/route_string.dart';
import 'package:special_equipment_flutter/dio/http_utils.dart';
import 'package:special_equipment_flutter/model/exam/overseer_history_list_bo.dart';
import 'package:special_equipment_flutter/utils/eventbus_utils.dart';
import 'package:special_equipment_flutter/utils/storage_util.dart';
import 'package:special_equipment_flutter/utils/string_utils.dart';
import 'package:special_equipment_flutter/utils/time_util.dart';
import 'package:special_equipment_flutter/utils/toast_utils.dart';
import 'package:special_equipment_flutter/widgets/app_bar/custom_app_bar.dart';
import 'package:special_equipment_flutter/widgets/custom_button.dart';
import 'package:special_equipment_flutter/widgets/divider_custom.dart';
import 'package:special_equipment_flutter/widgets/emptyI_img_widget.dart';
import 'package:special_equipment_flutter/widgets/first_refresh_widget.dart';

///考核记录列表
class OverseerHistoryListPage extends StatefulWidget {
  const OverseerHistoryListPage({super.key});

  @override
  State<OverseerHistoryListPage> createState() =>
      _OverseerHistoryListPageState();
}

class _OverseerHistoryListPageState extends State<OverseerHistoryListPage> {
  final EasyRefreshController _controller = EasyRefreshController();

  // List<TaskDayList> list = [];
  // OverseerHistoryListBo? mOverseerHistoryListBo = OverseerHistoryListBo();
  List<HistoryListData>? mHistoryListData = [];
  int page = 1;
  bool isLastPage = true;
  OverseerHistoryListBo? mOverseerHistoryListBo = OverseerHistoryListBo();
  int mOverseerHistoryCount = 0;

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

  ///获取监察记录列表
  void getOverseerHistoryList() {
    HttpUtils.getPapers(context, StorageUtil.getInstance().getUserId(), 1, 10)
        .then((value) {
      mOverseerHistoryListBo = value;
      if (mounted) {
        setState(() {
          mOverseerHistoryCount = mOverseerHistoryListBo!.count!;

          if (page == 1) {
            mHistoryListData!.clear();
          }
          List<HistoryListData>? rows = mOverseerHistoryListBo!.data;
          mHistoryListData!.addAll(rows!);
          int totalPage =
              StringUtils.totalPage(mOverseerHistoryListBo!.count, 10);
          print('$totalPage==== $page');
          if (totalPage == page) {
            isLastPage = true;
          } else {
            isLastPage = false;
          }
        });
        _controller.finishRefresh();
        _controller.finishLoad(noMore: isLastPage);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Get.back(result: true);
        return true; // 控制是否可以侧滑返回，true为允许，false为不允许
      },
      child: Scaffold(
        appBar: AppBarCustom(text: '考核列表', height: 50),
        backgroundColor: Colors.grey[100],
        body: Column(
          children: [
            Expanded(
                flex: 1,
                child: EasyRefresh(
                  firstRefresh: true,
                  enableControlFinishRefresh: true,
                  enableControlFinishLoad: true,
                  firstRefreshWidget: const FirstRefreshWidget(),
                  emptyWidget: mHistoryListData!.isEmpty
                      ? EmptyImgWidget(
                          title: '暂无数据,点击刷新',
                          onTap: () {
                            getOverseerHistoryList();
                          })
                      : null,
                  controller: _controller,
                  onRefresh: () async {
                    page = 1;
                    getOverseerHistoryList();
                  },
                  onLoad: () async {
                    page++;
                    getOverseerHistoryList();
                  },
                  child: buildBody(),
                )),
          ],
        ),
      ),
    );
  }

  Column buildBody() {
    return Column(
      children: [
        Container(
          width: double.infinity,
          margin:
              const EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 0),
          padding: const EdgeInsets.only(left: 10, right: 5, top: 3, bottom: 3),
          decoration: BoxDecoration(
            color: Colors.orange[50],
            borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(5),
                topRight: Radius.circular(5),
                bottomLeft: Radius.circular(5),
                bottomRight: Radius.circular(5)),
          ),
          child: Text.rich(
              softWrap: true,
              TextSpan(children: [
                const TextSpan(
                    text: "历史监察记录共 ",
                    style: TextStyle(fontSize: 14, color: Colors.orange)),
                TextSpan(
                    text: mOverseerHistoryListBo != null
                        ? mOverseerHistoryCount.toString()
                        : '0',
                    style: const TextStyle(
                        fontSize: 18,
                        color: Colors.orange,
                        fontWeight: FontWeight.bold)),
                const TextSpan(
                    text: " 条",
                    style: TextStyle(fontSize: 14, color: Colors.orange))
              ])),
        ),
        //文章列表
        ListView.separated(
          shrinkWrap: true,
          padding: const EdgeInsets.symmetric(
              horizontal: EdgeInsetsConst.padding_horizontal),
          physics: const NeverScrollableScrollPhysics(),
          itemBuilder: (BuildContext context, int index) {
            return buildItem(index, context);
          },
          itemCount: mHistoryListData!.length,
          separatorBuilder: (BuildContext context, int index) {
            return const SizedBox(
              height: 0,
            );
          },
        ),
      ],
    );
  }

  InkWell buildItem(int index, BuildContext context) {
    return InkWell(
      onTap: () {
        Get.toNamed(RouteString.OVERSEER_HISTROY_DETAILS_PAGE, arguments: {
          'id': mHistoryListData![index].id,
        })?.then((value) {
          if (value != null && value) {
            getOverseerHistoryList();
          }
        });
      },
      child: Card(
        elevation: 10,
        shadowColor: mHistoryListData![index].incomplete != 0
            ? ColorConst.orangeColor
            : ColorConst.greenColor,
        margin: const EdgeInsets.only(left: 0, right: 0, top: 10, bottom: 0),
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(10)),
        ),
        child: Container(
          padding:
              const EdgeInsets.only(left: 15, right: 15, top: 10, bottom: 10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(mHistoryListData![index].officeName!,
                  style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                      color: Colors.black54)),

              ///分割线
              DividerCustom(Colors.grey[300], 8, 8, 0, 0),

              Row(children: [
                const Text('设备类型：',
                    style: TextStyle(fontSize: 14, color: Colors.black54)),
                Text(mHistoryListData![index].typeName!,
                    style:
                        const TextStyle(fontSize: 14, color: Colors.black54)),
              ]),
              const SizedBox(height: 5),
              Text.rich(
                  softWrap: true,
                  TextSpan(children: [
                    const TextSpan(
                        text: "考核人数：",
                        style: TextStyle(fontSize: 14, color: Colors.black54)),
                    TextSpan(
                        text: mHistoryListData![index].count!.toString(),
                        style: const TextStyle(
                            fontSize: 18,
                            color: ColorConst.greenColor,
                            fontWeight: FontWeight.bold)),
                    const TextSpan(
                        text: "人",
                        style: TextStyle(fontSize: 14, color: Colors.black54)),
                  ])),
              const SizedBox(height: 5),
              Text.rich(
                  softWrap: true,
                  TextSpan(children: [
                    const TextSpan(
                        text: "考核状态：",
                        style: TextStyle(fontSize: 14, color: Colors.black54)),
                    const TextSpan(
                        text: "已完成 ",
                        style: TextStyle(color: ColorConst.greenColor)),
                    TextSpan(
                        text: mHistoryListData![index].complete!.toString(),
                        style: const TextStyle(
                            color: ColorConst.greenColor,
                            fontSize: 18,
                            fontWeight: FontWeight.bold)),
                    const TextSpan(
                        text: " 人",
                        style: TextStyle(color: ColorConst.greenColor)),
                    if (mHistoryListData![index].incomplete != 0) ...[
                      const TextSpan(
                          text: "  |  ",
                          style: TextStyle(color: ColorConst.greyD2Color)),
                      const TextSpan(
                          text: "进行中 ",
                          style: TextStyle(color: ColorConst.red1BgColor)),
                      TextSpan(
                          text: mHistoryListData![index].incomplete!.toString(),
                          style: const TextStyle(
                              color: ColorConst.red1BgColor,
                              fontSize: 18,
                              fontWeight: FontWeight.bold)),
                      const TextSpan(
                          text: " 人",
                          style: TextStyle(color: ColorConst.red1BgColor)),
                    ]
                  ])),
              const SizedBox(height: 5),
              Text.rich(
                  softWrap: true,
                  TextSpan(children: [
                    const TextSpan(
                        text: "考核时间：",
                        style: TextStyle(fontSize: 14, color: Colors.black54)),
                    TextSpan(
                        text: timestampToDate(
                            mHistoryListData![index].createDate!),
                        style: const TextStyle(
                            fontSize: 14, color: Colors.black54)),
                  ])),
              const SizedBox(height: 10),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  if (mHistoryListData![index].incomplete != 0) ...[
                    GradientButton(
                        tapCallback: () {
                          showDialog(
                              context: context,
                              builder: (context) {
                                return AlertDialog(
                                  title: const Text("温馨提示"),
                                  content: const Text("您确定要删除该监察记录吗？"),
                                  actionsPadding: const EdgeInsets.only(
                                      left: 0, top: 0, bottom: 10, right: 20),
                                  contentPadding: const EdgeInsets.only(
                                      left: 20, top: 0, bottom: 10, right: 20),
                                  titlePadding: const EdgeInsets.only(
                                      left: 20, top: 20, bottom: 10, right: 20),
                                  actions: [
                                    TextButton(
                                      child: const Text("取消"),
                                      onPressed: () {
                                        Get.back();
                                      },
                                    ),
                                    TextButton(
                                        child: const Text("确定"),
                                        onPressed: () {
                                          ///删除监察记录
                                          HttpUtils.getExamSetupDelete(context,
                                                  mHistoryListData![index].id!)
                                              .then((value) {
                                            if (mounted) {
                                              setState(() {
                                                mHistoryListData!
                                                    .removeAt(index);
                                                //发出通知
                                                // EventBusUtils.getInstance()
                                                //     ?.fire("2");
                                                mOverseerHistoryCount--;
                                                ToastUtils.showCenter('删除成功');
                                                Get.back();
                                              });
                                            }
                                          });
                                        })
                                  ],
                                );
                              });
                        },
                        width: 60,
                        height: 23,
                        borderRadius: const BorderRadius.only(
                            topLeft: Radius.circular(10),
                            topRight: Radius.circular(20),
                            bottomLeft: Radius.circular(20),
                            bottomRight: Radius.circular(10)),
                        disable: false,
                        colors: const [
                          ColorConst.red1BgColor,
                          ColorConst.red3BgColor
                        ],
                        child: const Text(
                          "删除",
                          style: TextStyle(
                              fontSize: 14, color: ColorConst.whiteColor),
                        )),
                  ],
                  Container(
                    margin: const EdgeInsets.only(left: 20),
                    child: GradientButton(
                        tapCallback: () {
                          Get.toNamed(RouteString.OVERSEER_HISTROY_DETAILS_PAGE,
                              arguments: {
                                'id': mHistoryListData![index].id,
                              })?.then((value) {
                            if (value != null && value) {}
                          });
                        },
                        width: 60,
                        height: 23,
                        borderRadius: const BorderRadius.only(
                            topLeft: Radius.circular(10),
                            topRight: Radius.circular(20),
                            bottomLeft: Radius.circular(20),
                            bottomRight: Radius.circular(10)),
                        disable: false,
                        colors: const [
                          ColorConst.blueColor,
                          ColorConst.blue1Color
                        ],
                        child: const Text(
                          "详情",
                          style: TextStyle(
                              fontSize: 14, color: ColorConst.whiteColor),
                        )),
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}
