// ignore_for_file: prefer_typing_uninitialized_variables, library_private_types_in_public_api, avoid_print, must_be_immutable

import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.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/completed_list_bo.dart';
import 'package:special_equipment_flutter/ui/common/basic_information_page.dart';
import 'package:special_equipment_flutter/ui/common/data.dart';
import 'package:special_equipment_flutter/utils/storage_util.dart';
import 'package:special_equipment_flutter/utils/toast_utils.dart';
import 'package:special_equipment_flutter/widgets/emptyI_img_widget.dart';
import 'package:special_equipment_flutter/widgets/first_refresh_widget.dart';

import '../../../../common/color_const.dart';
import '../../../../widgets/custom_button.dart';
import '../../../../widgets/divider_custom.dart';

///使用单位
///日管控、周排查、月调度
///已完成列表
class CompletedListSyPage extends StatefulWidget {
  ///区分  日管控、周排查、月调度
  var args;

  /// 定义一个Function属性 ，父页面回调子页面数据
  final Function onDataChanged;

  CompletedListSyPage(this.args, {super.key, required this.onDataChanged});

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

class _CompletedListSyPageState extends State<CompletedListSyPage>
    with SingleTickerProviderStateMixin {
  final EasyRefreshController _controller = EasyRefreshController();
  int page = 1;
  bool isLastPage = true;
  List<Rows> listRow = [];
  var type, unitStatus;

  // late AnimationController animationController;
  // late Animation<double> animation;

  @override
  void initState() {
    super.initState();
    type = widget.args['type'];
    unitStatus = StorageUtil.getInstance().getUnitStatus();
    getData();
  }

  void getData() {
    switch (type) {
      case '1':
        getDayData();
        break;
      case '2':
        getWeekData();
        break;
      case '3':
        getMonthData();
        break;
    }
  }

  ///日管控、风险整改、已完成
  void getDayData() {
    HttpUtils.getTaskDayListPage(context, '1,3,6', '',
            StorageUtil.getInstance().getUnitStatus(), 10, page)
        .then((value) {
      CompletedListBo listBo = value;
      if (mounted) {
        setState(() {
          if (page == 1) {
            listRow.clear();
          }
          List<Rows>? rows = listBo.date?.rows;
          listRow.addAll(rows!);
          int? totalPage = listBo.date!.last;
          print('$totalPage==== $page');
          if (totalPage == page) {
            isLastPage = true;
          } else {
            isLastPage = false;
          }
        });
        _controller.finishRefresh();
        _controller.finishLoad(noMore: isLastPage);
      }
    });
  }

  ///周排查、风险整改、已完成
  ///now.toString().substring(0, 19)
  void getWeekData() {
    HttpUtils.getTaskWeekListPage(context, '1,3,6', '',
            StorageUtil.getInstance().getUnitStatus(), 10, page)
        .then((value) {
      CompletedListBo listBo = value;
      if (mounted) {
        setState(() {
          if (page == 1) {
            listRow.clear();
          }
          List<Rows>? rows = listBo.date?.rows;
          listRow.addAll(rows!);
          int? totalPage = listBo.date!.last;
          // var totalPage2 = StringUtils.totalPage(totalPage, 10);
          if (totalPage == page) {
            isLastPage = true;
          } else {
            isLastPage = false;
          }
        });
        _controller.finishRefresh();
        _controller.finishLoad(noMore: isLastPage);
      }
    });
  }

  ///月调度、风险整改、已完成
  void getMonthData() {
    HttpUtils.getTaskMonthListPage(context, '1,3,6', '',
            StorageUtil.getInstance().getUnitStatus(), 10, page)
        .then((value) {
      CompletedListBo listBo = value;
      if (mounted) {
        setState(() {
          if (page == 1) {
            listRow.clear();
          }
          List<Rows>? rows = listBo.date?.rows;
          listRow.addAll(rows!);
          int? totalPage = listBo.date!.last;
          // var totalPage2 = StringUtils.totalPage(totalPage, 10);
          if (totalPage == page) {
            isLastPage = true;
          } else {
            isLastPage = false;
          }
        });
        _controller.finishRefresh();
        _controller.finishLoad(noMore: isLastPage);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      body: Column(
        children: [
          Expanded(
              flex: 1,
              child: EasyRefresh(
                firstRefresh: true,
                enableControlFinishRefresh: true,
                enableControlFinishLoad: true,
                firstRefreshWidget: const FirstRefreshWidget(),
                emptyWidget: listRow.isEmpty
                    ? EmptyImgWidget(
                        title: '暂无数据,点击刷新',
                        onTap: () {
                          getData();
                        })
                    : null,
                controller: _controller,
                onRefresh: () async {
                  page = 1;
                  getData();
                },
                onLoad: () async {
                  page++;
                  getData();
                },
                child: buildBody(),
              )),
        ],
      ),
    );
  }

  Column buildBody() {
    return Column(
      children: [
        //文章列表
        ListView.separated(
          shrinkWrap: true,
          padding: const EdgeInsets.symmetric(
              horizontal: EdgeInsetsConst.padding_horizontal),
          physics: const NeverScrollableScrollPhysics(),
          itemBuilder: (BuildContext context, int index) {
            return InkWell(
              onTap: () {
                if (listRow[index].taskState == '6') {
                  ToastUtils.showCenter('未检查');
                  return;
                }
                if (type == '1') {
                  Get.toNamed(RouteString.DAY_COMPLETED_DETAIL_SY, arguments: {
                    'argsData': widget.args,
                    'listBo': listRow[index]
                  });
                } else if (type == '2') {
                  Get.toNamed(RouteString.WEEK_COMPLETED_DETAIL_SY, arguments: {
                    'argsData': widget.args,
                    'listBo': listRow[index]
                  });
                } else if (type == '3') {
                  Get.toNamed(RouteString.MONTH_COMPLETED_DETAIL_SY,
                      arguments: {
                        'argsData': widget.args,
                        'listBo': listRow[index]
                      });
                }
              },
              child: Card(
                elevation: 3,
//                shadowColor:
//                    index == 1 ? ColorConst.blueColor : ColorConst.orangeColor,
                margin: const EdgeInsets.only(
                    left: 0, right: 0, top: 15, bottom: 0),
                color: Colors.white,
                shape: const RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(5)),
                ),
                child: Column(
                  children: <Widget>[
                    ///任务名称、任务类型
                    rowTitle(context, index),

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

                    if (type == '1') ...[
                      //日
                      BasicInformationPage(
                          informationDataList: DataConfig.syDayInformationData(
                              '3', false, null, listRow[index])),
                    ] else if (type == '2') ...[
                      //周
                      //日
                      BasicInformationPage(
                          informationDataList: DataConfig.syWeekInformationData(
                              '3', false, null, listRow[index])),
                    ] else if (type == '3') ...[
                      //月
                      BasicInformationPage(
                          informationDataList:
                              DataConfig.syMonthInformationData(
                                  '3', false, null, listRow[index]))
                    ],
                    const SizedBox(
                      height: 5,
                    )
//                    buildSubmits(context, index),
                  ],
                ),
              ),
            );
          },
          itemCount: listRow.length,
          separatorBuilder: (BuildContext context, int index) {
            return const SizedBox(
              height: 0,
            );
          },
        ),
      ],
    );
  }

  //item布局
  Container buildItem(var asset, var title, var content, [content2]) {
    return Container(
      alignment: Alignment.centerLeft,
      margin: const EdgeInsets.fromLTRB(10, 0, 0, 7),
      child: Stack(
        alignment: Alignment.centerLeft,
        children: [
          Image.asset(asset,
              height: EdgeInsetsConst.icon_size12,
              width: EdgeInsetsConst.icon_size12),
          Container(
              margin: const EdgeInsets.fromLTRB(18, 0, 0, 0),
              child: Text.rich(
                  softWrap: true,
                  TextSpan(children: [
                    TextSpan(
                        text: title,
                        style: const TextStyle(
                            fontSize: 12, color: Colors.black87)),
                    TextSpan(
                      text: content,
                      style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                    ),
                    if (content2 != null && content2 != "") ...[
                      TextSpan(
                        text: content2,
                        style: const TextStyle(
                            fontSize: 12, color: ColorConst.greenColor),
                      )
                    ]
                  ])))
        ],
      ),
    );
  }

  ///去点检
  Container buildSubmits(BuildContext context, int index) {
    return Container(
        alignment: Alignment.centerRight,
        margin: const EdgeInsets.only(top: 0, right: 10, bottom: 10),
        child: GradientButton(
          tapCallback: () => print("Button Clicked 6"),
          width: 75,
          height: 25,
          borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(10),
              topRight: Radius.circular(20),
              bottomLeft: Radius.circular(20),
              bottomRight: Radius.circular(10)),
          disable: false,
          colors: [
            index == 1 ? ColorConst.blueColor : ColorConst.orangeColor,
            index == 1 ? ColorConst.blue1Color : ColorConst.orange1Color
          ],
          child: const Text(
            "去检查",
            style: TextStyle(fontSize: 12, color: ColorConst.whiteColor),
          ),
        ));
  }

  //显示任务名称、任务类型
  Row rowTitle(BuildContext context, int index) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
//      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          margin: const EdgeInsets.fromLTRB(0, 10, 0, 0),
          padding: const EdgeInsets.fromLTRB(5, 2, 10, 2),
          decoration: BoxDecoration(
            color: typeColor(listRow[index].deviceType!.name),
            borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(0),
                topRight: Radius.circular(0),
                bottomLeft: Radius.circular(0),
                bottomRight: Radius.circular(10)),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                margin: const EdgeInsets.only(left: 3, right: 3, top: 2),
                child: Image.asset(
                  typeImage(listRow[index].deviceType!.name),
                  width: 18,
                  height: 18,
                ),
              ),
              Text(
                listRow[index].deviceType!.name!,
                style: const TextStyle(
                    fontSize: 14,
                    color: Colors.white,
                    fontWeight: FontWeight.bold),
              )
            ],
          ),
        ),
        Stack(
          alignment: Alignment.bottomLeft,
          children: [
            Container(
              margin: const EdgeInsets.only(left: 5),
              // color: ColorConst.blue3Color,
              width: 85,
              height: 10,
            ),
            Container(
              margin: const EdgeInsets.fromLTRB(8, 8, 0, 0),
              child: Text.rich(TextSpan(children: [
                TextSpan(
                    text: titles(index),
                    style: const TextStyle(
                        color: ColorConst.blackColor,
                        fontSize: 20,
                        fontStyle: FontStyle.italic)),
              ])),
//              ),
            ),
          ],
        ),
      ],
    );
  }

  String? titles(index) {
    ///使用单位
    if (unitStatus == '1') {
      ///日(日显示编码，周、月显示周期、月份)
      if (type == '1') {
        return listRow[index].device!.code;
      } else {
        return setBeginTime(type, listRow[index].beginTime);
      }
    } else {
      ///生产单位
      return setBeginTime(type, listRow[index].beginTime);
    }
  }

// dynamic beginTime(index) {
//   switch (type) {
//     case '1':
//       return listDay[index].beginTime;
//     case '2':
//       return listWeek[index].beginTime;
//     case '3':
//       return listMonth[index].beginTime;
//   }
// }

// dynamic listEmpty() {
//   switch (type) {
//     case '1':
//       return listDay.isEmpty;
//     case '2':
//       return listWeek.isEmpty;
//     case '3':
//       return listMonth.isEmpty;
//   }
// }

// dynamic? list[index] {
//   switch (type) {
//     case '1':
//       return listDay[index];
//     case '2':
//       return listWeek[index];
//     case '3':
//       return listMonth[index];
//   }
// }

// int? listLength() {
//   switch (type) {
//     case '1':
//       return listDay.length;
//     case '2':
//       return listWeek.length;
//     case '3':
//       return listMonth.length;
//   }
// }

// dynamic name(index) {
//   switch (type) {
//     case '1':
//       return listDay[index].deviceType!.name;
//     case '2':
//       return listWeek[index].deviceType!.name;
//     case '3':
//       return listMonth[index].deviceType!.name;
//   }
// }
}
