// 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/day_control_list_sy_bo.dart';
import 'package:special_equipment_flutter/model/month_control_list_sy_bo.dart';
import 'package:special_equipment_flutter/model/system_time.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/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 'package:special_equipment_flutter/widgets/number_to_chinese.dart';

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

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

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

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

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

class _InspectListSyPageState extends State<InspectListSyPage>
    with SingleTickerProviderStateMixin {
  final EasyRefreshController _controller = EasyRefreshController();
  List<TaskDayList> listDay = [];
  List<TaskWeekList> listWeek = [];
  List<TaskMonthList> listMonth = [];
  var type, unitStatus;

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

  void getData() {
    ///获取系统时间
    HttpUtils.doTime(context).then((value) {
      SystemTime systemTime = value;
      if (mounted) {
        DateTime date = DateTime.fromMillisecondsSinceEpoch(systemTime.time!);
        switch (type) {
          case '1':
            getDayData(date.toString());
            break;
          case '2':
            getWeekData(date.toString());
            break;
          case '3':
            getMonthData(date.toString());
            break;
        }
      }
    });
  }

  // now.toString().substring(0, 19)
  ///日管控、风险整改、已完成
  void getDayData(date) {
    HttpUtils.getFindUserAllTaskDayList(
            context, '0', date.substring(0, 19), 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(date) {
    HttpUtils.getFindUserAllTaskWeekList(
            context, '0', date.substring(0, 19), 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(date) {
    HttpUtils.getFindUserAllTaskMonthList(
            context, '0', date.substring(0, 19), 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 {
                  // page = 1;
                  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,
            );
          },
        ),
      ],
    );
  }

  // SizeTransition(
  // sizeFactor: animation,
  // child: buildItem(index, context),
  // );

  InkWell buildItem(int index, BuildContext context) {
    return InkWell(
      onTap: () {
        // if (type == '1') {
        //   Get.toNamed(RouteString.DAY_INSPECT_SUBMIT_SY,
        //           arguments: {'argsData': widget.args, 'listBo': list(index)})
        //       ?.then((value) {
        //     if (value != null && value) {
        //       getData();
        //     }
        //   });
        // } else if (type == '2') {
        //   Get.toNamed(RouteString.WEEK_INSPECT_SUBMIT_SY,
        //           arguments: {'argsData': widget.args, 'listBo': list(index)})
        //       ?.then((value) {
        //     if (value != null && value) {
        //       getData();
        //     }
        //   });
        // } else if (type == '3') {
        //   Get.toNamed(RouteString.MONTH_INSPECT_SUBMIT_SY,
        //           arguments: {'argsData': widget.args, 'listBo': list(index)})
        //       ?.then((value) {
        //     if (value != null && value) {
        //       getData();
        //     }
        //   });
        // }
        if (type == '1') {
          Get.toNamed(RouteString.DAY_INSPECT_SUBMIT_SY,
                  arguments: {'argsData': widget.args, 'listBo': list(index)})
              ?.then((value) {
            if (value != null && value) {
              getData();
            }
          });
        } else if (type == '2') {
          if (listWeek[index].allow == '0') {
            Get.toNamed(RouteString.WEEK_INSPECT_SUBMIT_SY,
                    arguments: {'argsData': widget.args, 'listBo': list(index)})
                ?.then((value) {
              if (value != null && value) {
                getData();
              }
            });
          } else {
            ToastUtils.showCenter(
                '任务解锁时间：本周${ConvertNumberToChineseMoneyWords.toChinese(listWeek[index].timeConfig!.weekBeginDay! - 1)}');
          }
        } else if (type == '3') {
          if (listMonth[index].allow == '0') {
            Get.toNamed(RouteString.MONTH_INSPECT_SUBMIT_SY,
                    arguments: {'argsData': widget.args, 'listBo': list(index)})
                ?.then((value) {
              if (value != null && value) {
                getData();
              }
            });
          } else {
            ToastUtils.showCenter(
                '任务解锁时间：本月${listMonth[index].timeConfig!.monthBeginDay}号');
          }
        }
      },
      child: buildCard(context, index),
    );
  }

  Card? buildCard(BuildContext context, int index) {
    if (type == '1') {
      return buildDaysCard(context, index);
    } else if (type == '2') {
      return buildWeekCard(context, index);
    } else if (type == '3') {
      return buildMonthsCard(context, index);
    }
    return null;
  }

  Card buildWeekCard(BuildContext context, int index) {
    return Card(
      margin: const EdgeInsets.only(left: 0, right: 0, top: 15, bottom: 0),
      elevation: listWeek[index].allow == '0' ? 3 : 0,
      color: listWeek[index].allow == '0' ? Colors.white : Colors.grey[300],
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(5)),
      ),
      child: Column(
        children: <Widget>[
          ///任务名称、任务类型
          rowTitle(context, index),

          ///分割线
          DividerCustom(Colors.grey[300], 10, 10, 10, 10),
          //周
          BasicInformationPage(
              informationDataList:
                  DataConfig.syWeekInformationData('1', false, list(index))),
          const SizedBox(
            height: 5,
          )
//                    buildSubmits(context, index),
        ],
      ),
    );
  }

  Card buildMonthsCard(BuildContext context, int index) {
    return Card(
      margin: const EdgeInsets.only(left: 0, right: 0, top: 15, bottom: 0),
      elevation: listMonth[index].allow == '0' ? 3 : 0,
      color: listMonth[index].allow == '0' ? Colors.white : Colors.grey[300],
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(5)),
      ),
      child: Column(
        children: <Widget>[
          ///任务名称、任务类型
          rowTitle(context, index),

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

          //月
          BasicInformationPage(
              informationDataList:
                  DataConfig.syMonthInformationData('1', false, list(index))),
          const SizedBox(
            height: 5,
          )
//                    buildSubmits(context, index),
        ],
      ),
    );
  }

  Card buildDaysCard(BuildContext context, int index) {
    return Card(
      elevation: 3,
      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),
          //日
          BasicInformationPage(
              informationDataList:
                  DataConfig.syDayInformationData('1', false, list(index))),
          const SizedBox(
            height: 5,
          )
//                    buildSubmits(context, index),
        ],
      ),
    );
  }

  //去点检
  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.spaceBetween,
      children: [
        Row(
          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),
                  )
                ],
              ),
            ),
            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)),
              ])),
            ),
          ],
        ),
        if (type == '2') ...[
          if (listWeek[index].allow == '1') ...[
            Container(
              margin: const EdgeInsets.only(right: 10),
              child: const Icon(
                Icons.lock,
              ),
            ),
          ]
        ] else if (type == '3') ...[
          if (listMonth[index].allow == '1') ...[
            Container(
              margin: const EdgeInsets.only(right: 10),
              child: const Icon(
                Icons.lock,
              ),
            ),
          ]
        ]
      ],
    );
  }

  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;
    }
    return listDay[index].beginTime;
  }

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

  dynamic list(index) {
    switch (type) {
      case '1':
        return listDay[index];
      case '2':
        return listWeek[index];
      case '3':
        return listMonth[index];
    }
    return listDay[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;
    }
    return listDay[index].deviceType!.name;
  }
}
