// ignore_for_file: library_private_types_in_public_api, prefer_typing_uninitialized_variables, 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/day_control_list_sy_bo.dart';
import 'package:special_equipment_flutter/model/month_control_list_sy_bo.dart';
import 'package:special_equipment_flutter/model/week_control_list_sy_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/widgets/emptyI_img_widget.dart';
import 'package:special_equipment_flutter/widgets/first_refresh_widget.dart';

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

///使用单位
///日管控、周排查、月调度
///异常整改列表
class RiskListSyPage extends StatefulWidget {
  ///区分  日管控、周排查、月调度
  var args;

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

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

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

class _RiskListSyPageState extends State<RiskListSyPage>
    with SingleTickerProviderStateMixin {
  final EasyRefreshController _controller = EasyRefreshController();

  List<TaskDayList> listDay = [];
  List<TaskWeekList> listWeek = [];
  List<TaskMonthList> listMonth = [];
  var type, unitStatus;

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

  @override
  void initState() {
    super.initState();
    type = widget.args['type'];
    unitStatus = StorageUtil.getInstance().getUnitStatus();
    // animationController = AnimationController(
    //   duration: const Duration(seconds: 1),
    //   vsync: this,
    // )..addListener(() {
    //     setState(() {});
    //   });
    // final curvedAnimation = CurvedAnimation(
    //   parent: animationController,
    //   curve: Curves.bounceOut,
    // );
    // animation = Tween<double>(begin: 0, end: 1).animate(curvedAnimation);
    // animationController.forward();
    getData();
  }

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

  ///日管控、风险整改、已完成列表
  void getDayData() {
    DateTime now = DateTime.now();
    HttpUtils.getFindUserAllTaskDayList(context, '2', '', unitStatus)
        .then((value) {
      DayControlListSyBo listBo = value;
      if (mounted) {
        setState(() {
          var taskDayList = listBo.taskDayList;
          listDay.clear();
          listDay.addAll(taskDayList!);

          ///更新红点数字
          widget.onDataChanged(listDay.length.toString());
          _controller.finishRefresh();
        });
      }
    });
  }

  ///周排查、风险整改、已完成
  void getWeekData() {
    DateTime now = DateTime.now();
    HttpUtils.getFindUserAllTaskWeekList(context, '2', '', unitStatus)
        .then((value) {
      WeekControlListSyBo listBo = value;
      if (mounted) {
        setState(() {
          var taskWeekList = listBo.taskWeekList;
          listWeek.clear();
          listWeek.addAll(taskWeekList!);

          ///更新红点数字
          widget.onDataChanged(listWeek.length.toString());
          _controller.finishRefresh();
        });
      }
    });
  }

  ///月调度、风险整改、已完成
  void getMonthData() {
    DateTime now = DateTime.now();
    HttpUtils.getFindUserAllTaskMonthList(context, '2', '', unitStatus)
        .then((value) {
      MonthControlListSyBo listBo = value;
      if (mounted) {
        setState(() {
          var taskMonthList = listBo.taskMonthList;
          listMonth.clear();
          listMonth.addAll(taskMonthList!);

          ///更新红点数字
          widget.onDataChanged(listMonth.length.toString());
          _controller.finishRefresh();
        });
      }
    });
  }

  @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: listEmpty()
                    ? EmptyImgWidget(
                        title: '暂无数据,点击刷新',
                        onTap: () {
                          getData();
                        })
                    : null,
                controller: _controller,
                onRefresh: () async {
                  getData();
                },
//                onLoad: () async {
//                  page++;
//                  getList();
//                },
                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 buildItem(index, context);
          },
          itemCount: listLength()!,
          separatorBuilder: (BuildContext context, int index) {
            return const SizedBox(
              height: 0,
            );
          },
        ),
      ],
    );
  }

  InkWell buildItem(int index, BuildContext context) {
    return InkWell(
      onTap: () {
        if (type == '1') {
          Get.toNamed(RouteString.DAY_RISK_SUBMIT_SY,
                  arguments: {'argsData': widget.args, 'listBo': list(index)})
              ?.then((value) {
            if (value != null && value) {
              getData();
            }
          });
        } else if (type == '2') {
          Get.toNamed(RouteString.WEEK_RISK_SUBMIT_SY,
                  arguments: {'argsData': widget.args, 'listBo': list(index)})
              ?.then((value) {
            if (value != null && value) {
              getData();
            }
          });
        } else if (type == '3') {
          Get.toNamed(RouteString.MONTH_RISK_SUBMIT_SY,
                  arguments: {'argsData': widget.args, 'listBo': list(index)})
              ?.then((value) {
            if (value != null && value) {
              getData();
            }
          });
        }
      },
      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('2', false, list(index)))
            ] else if (type == '2') ...[
              //周
              BasicInformationPage(
                  informationDataList:
                      DataConfig.syWeekInformationData('2', false, list(index)))
            ] else if (type == '3') ...[
              //月
              BasicInformationPage(
                  informationDataList: DataConfig.syMonthInformationData(
                      '2', false, list(index)))
            ],

            const SizedBox(
              height: 5,
            )
//                    buildSubmits(context, index),
          ],
        ),
      ),
    );
  }

  ///显示任务名称、任务类型
  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(name(index)),
            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(name(index)),
                  width: 18,
                  height: 18,
                ),
              ),
              Text(
                name(index)!,
                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)),
              ])),

//              child: Text(
//                listData[index].num,
//                style: TextStyle(
////                    fontWeight: FontWeight.bold,
//                    color: ColorConst.blackColor,
//                    fontSize: 20,
//                    fontStyle: FontStyle.italic),
//              ),
            ),
          ],
        ),
      ],
    );
  }

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

  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;
    }
    return listDay.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;
    }
  }
}
