// ignore_for_file: avoid_print, must_be_immutable, library_private_types_in_public_api, prefer_typing_uninitialized_variables

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.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/dio/api.dart';
import 'package:special_equipment_flutter/dio/http_utils.dart';
import 'package:special_equipment_flutter/model/detail/day/day_detail_bo.dart';
import 'package:special_equipment_flutter/model/detail/day/task_day_check_list.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/ui/common/photoview_gallery_screen.dart';
import 'package:special_equipment_flutter/utils/storage_util.dart';
import 'package:special_equipment_flutter/widgets/app_bar/custom_app_bar.dart';
import 'package:special_equipment_flutter/widgets/divider_custom.dart';
import 'package:special_equipment_flutter/widgets/number_to_chinese.dart';

class RadioModel {
  bool isSelected;
  final String text;

  RadioModel(this.isSelected, this.text);
}

///使用单位
///日管控、周排查、月调度
///已完成详情
class DayCompletedDetailSyPage extends StatefulWidget {
  ///区分  日管控、周排查、月调度
  var argsBundle = Get.arguments;

  DayCompletedDetailSyPage({super.key});

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

class _DayCompletedDetailSyPageState extends State<DayCompletedDetailSyPage> {
  ///type=1（日管控）type=2（周排查）type=3（月调度）
  var type, unitStatus;
  late var taskDayBo;

  List<TaskDayCheckLists> taskDayCheckList = [];
  List<String> imageList = [];

  @override
  void initState() {
    super.initState();
    type = widget.argsBundle['argsData']['type'];
    taskDayBo = widget.argsBundle['listBo'];
    unitStatus = StorageUtil.getInstance().getUnitStatus();
    if (taskDayBo.prictures != null && taskDayBo.prictures!.isNotEmpty) {
      var pricturesStr = taskDayBo.prictures!.split(',');
      for (var item in pricturesStr) {
        imageList.add('${Api.URL}special$item');
      }
    }
    getData();
  }

  ///获取数据
  void getData() {
    HttpUtils.getFindCompletedTaskDayCheck(context, taskDayBo.id, type)
        .then((value) {
      DayDetailBo dayDetailBo = value;
      if (mounted) {
        setState(() {
          taskDayCheckList.addAll(dayDetailBo.taskDayCheckList!);
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBarCustom(text: '详情', height: 50),
      body: CustomScrollView(
        shrinkWrap: true,
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: Column(
              children: [
                ///注：请整改人员按要求认真整改
//                buildNote(),

                ///基本信息
                buildBasicInformation(),

                ///检查项
                buildCheckItem(),

                const SizedBox(height: 30)
              ],
            ),
          ),
        ],
      ),
    );
  }

  List<RadioModel> sampleData = <RadioModel>[];

  ///检查项
  Card buildCheckItem() {
    return Card(
        color: Colors.white,
        margin: const EdgeInsets.only(left: 15, top: 0, right: 15, bottom: 0),
//          shadowColor: ColorConst.blueColor,
        elevation: 0,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(10)),
        ),
        child: Container(
          padding:
              const EdgeInsets.only(left: 10, top: 10, right: 10, bottom: 20),
          child: Column(
            children: <Widget>[
              ///标题
              buildTitle('检查项', Icons.event_note, true),

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

              ///ListView在苹果手机顶部\底部出现空白间距的解决方案
              MediaQuery.removePadding(
                  context: context,
                  removeBottom: true,
                  removeTop: true,

                  ///检查项
                  child: ListView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    padding: const EdgeInsets.only(top: 0, left: 25, bottom: 0),
                    itemCount: taskDayCheckList.length,
                    itemBuilder: (BuildContext context, int index) {
                      ///检查项item内容
                      return buildItem(index);
                    },
                  )),

              ///分割线
              const DividerCustom(Colors.grey, 15, 15, 0, 0),

              ///只有《使用单位-日》才有拍照
              if (unitStatus == '1') ...[
                if (type == '1') ...[
                  if (taskDayBo.prictures!.isNotEmpty) ...[
                    ///检查照片 标题
                    buildTitle('检查照片', Icons.photo_camera, false),

                    ///选择照片
                    buildPhotoList(),

                    ///分割线
                    const DividerCustom(Colors.grey, 15, 15, 0, 0)
                  ]
                ]
              ],

              ///检查人
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  ///标题
                  buildTitle('检查人', Icons.people, true),
                  Text(
                    taskDayBo.checkUser != null
                        ? taskDayBo.checkUser.name ?? '---'
                        : '---',
                    style: const TextStyle(fontSize: 14, color: Colors.grey),
                  ),
                ],
              ),
            ],
          ),
        ));
  }

  ///检查项item内容
  Column buildItem(int index) {
    return Column(
      children: <Widget>[
        ///风险管控措施标题
        buildSeclectRiskControlMeasuresAcquiesce(index),

        ///二级列表
        ListView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemCount: taskDayCheckList[index].childTaskDayList!.length,
          itemBuilder: (context, subIndex) {
            return Container(
              margin: const EdgeInsets.only(bottom: 5),
              decoration: const BoxDecoration(
                color: ColorConst.green1Color,
                borderRadius: BorderRadius.all(Radius.circular(5)),
              ),
              child: Padding(
                padding: const EdgeInsets.all(5),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const SizedBox(
                      height: 5,
                    ),

                    ///检查项内容、风险管控措施
                    buildCheckItemContent(index, subIndex, context),

                    ///间距
                    const SizedBox(height: 5),

                    if (taskDayCheckList[index]
                            .childTaskDayList![subIndex]
                            .taskDayCheck!
                            .result ==
                        '4') ...[
                      const DividerCustom(ColorConst.whiteColor, 5, 5, 20, 20),
                      Padding(
                        padding: const EdgeInsets.only(left: 20),
                        child: Text.rich(
                            softWrap: true,
                            TextSpan(children: [
                              const TextSpan(
                                  text: '风险内容: ',
                                  style: TextStyle(
                                      fontSize: 14, color: Colors.black87)),
                              TextSpan(
                                text: taskDayCheckList[index]
                                    .childTaskDayList![subIndex]
                                    .taskDayCheck!
                                    .riskContent,
                                style: const TextStyle(
                                    fontSize: 14, color: Colors.black54),
                              ),
                            ])),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 20, top: 5),
                        child: Text.rich(
                            softWrap: true,
                            TextSpan(children: [
                              const TextSpan(
                                  text: '整改内容: ',
                                  style: TextStyle(
                                      fontSize: 14, color: Colors.black87)),
                              TextSpan(
                                text: taskDayCheckList[index]
                                    .childTaskDayList![subIndex]
                                    .taskDayCheck!
                                    .rectContent,
                                style: const TextStyle(
                                    fontSize: 14, color: Colors.black54),
                              ),
                            ])),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 20, top: 5),
                        child: Text.rich(
                            softWrap: true,
                            TextSpan(children: [
                              const TextSpan(
                                  text: '整改人: ',
                                  style: TextStyle(
                                      fontSize: 14, color: Colors.black87)),
                              TextSpan(
                                text: taskDayCheckList[index]
                                    .childTaskDayList![subIndex]
                                    .taskDayCheck!
                                    .rectUserName,
                                style: const TextStyle(
                                    fontSize: 14, color: Colors.black54),
                              ),
                            ])),
                      ),
                      Padding(
                        padding:
                            const EdgeInsets.only(left: 20, top: 5, bottom: 5),
                        child: Text.rich(
                            softWrap: true,
                            TextSpan(children: [
                              const TextSpan(
                                  text: '整改时间: ',
                                  style: TextStyle(
                                      fontSize: 14, color: Colors.black87)),
                              TextSpan(
                                text: taskDayCheckList[index]
                                    .childTaskDayList![subIndex]
                                    .taskDayCheck!
                                    .rectTime,
                                style: const TextStyle(
                                    fontSize: 14, color: Colors.black54),
                              ),
                            ])),
                      ),
                    ]
                  ],
                ),
              ),
            );
          },
        ),
      ],
    );
  }

  var status = '1';

  ///设置检查项-默认：风险管控措施标题
  Container buildSeclectRiskControlMeasuresAcquiesce(int index) {
    return Container(
      alignment: Alignment.centerLeft,
      margin: const EdgeInsets.only(top: 8, bottom: 5),
      child: Text(
        '${ConvertNumberToChineseMoneyWords.toChinese(index)}、${taskDayCheckList[index].deviceRisk!.name ?? ''}',
        style: const TextStyle(
            fontSize: 14, color: Colors.black54, fontWeight: FontWeight.bold),
      ),
    );
  }

  String deviceRiskName(int index, int subIndex) {
    var childTaskDayList = taskDayCheckList[index].childTaskDayList![subIndex];
    if (childTaskDayList.deviceRisk!.id!.isNotEmpty) {
      return taskDayCheckList[index]
          .childTaskDayList![subIndex]
          .deviceRisk!
          .name!;
    } else {
      return taskDayCheckList[index]
          .childTaskDayList![subIndex]
          .taskDayCheck!
          .name!;
    }
  }

  ///检查项内容、风险管控措施
  Row buildCheckItemContent(int index, int subIndex, BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Flexible(
          flex: 1,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '\t${subIndex + 1}、',
                style:
                    const TextStyle(color: ColorConst.blackColor, fontSize: 14),
              ),
              Expanded(
                child: Text.rich(
                    softWrap: true,
                    TextSpan(children: [
                      TextSpan(
                          text: deviceRiskName(index, subIndex),
                          style: const TextStyle(
                              fontSize: 14, color: Colors.black)),
                      TextSpan(
                        text:
                            '(${resultStatusDay(taskDayCheckList[index].childTaskDayList![subIndex].taskDayCheck!.result)})',
                        style: TextStyle(
                            fontSize: 14,
                            color: resultColorDay(taskDayCheckList[index]
                                .childTaskDayList![subIndex]
                                .taskDayCheck!
                                .result),
                            fontWeight: FontWeight.bold),
                      ),
                    ])),
              ),
            ],
          ),
        ),
        InkWell(
          onTap: () {
            showDialog(
              context: context,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: const Text('风险管控措施'),
                  content: Text(taskDayCheckList[index]
                      .childTaskDayList![subIndex]
                      .deviceRisk!
                      .riskMeasure!),
                  actions: <Widget>[
                    MaterialButton(
                      child: const Text(
                        '我知道了',
                        style: TextStyle(color: ColorConst.blueColor),
                      ),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                  ],
                );
              },
            );
          },
          child: taskDayCheckList[index]
                      .childTaskDayList![subIndex]
                      .deviceRisk!
                      .riskMeasure !=
                  null
              ? const Icon(
                  Icons.help,
                  color: ColorConst.dark9Color,
                  size: EdgeInsetsConst.single_choice_icon_size,
                )
              : const SizedBox(),
        )
      ],
    );
  }

  ///标题
  Stack buildTitle(text, image, isVis) {
    return Stack(
      alignment: Alignment.bottomLeft,
      children: [
        Container(
          color: ColorConst.blue3Color,
          width: text.toString().length == 3
              ? 83
              : isVis
                  ? 97
                  : 93,
          height: 10,
        ),
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Icon(
              image,
              size: 18,
              color: ColorConst.blueColor,
            ),
            Container(
              margin: const EdgeInsets.only(left: 5),
              child: Text.rich(
                  softWrap: true,
                  TextSpan(children: [
                    if (isVis) ...[
                      const TextSpan(
                          text: '*',
                          style: TextStyle(
                              fontSize: 14, color: ColorConst.red1BgColor)),
                    ],
                    TextSpan(
                      text: text,
                      style: const TextStyle(fontSize: 16, color: Colors.black),
                    ),
                  ])),
            )
          ],
        )
      ],
    );
  }

  ///基本信息
  Card buildBasicInformation() {
    return Card(
        color: Colors.white,
        margin: const EdgeInsets.only(left: 15, top: 10, right: 15, bottom: 10),
        elevation: 0,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(10)),
        ),
        child: Container(
          padding: const EdgeInsets.all(10),
          child: Stack(
            children: [
              Column(
                children: <Widget>[
                  ///基本信息
                  buildTitle('基本信息', Icons.message_rounded, false),

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

                  //日
                  BasicInformationPage(
                      informationDataList: DataConfig.syDayInformationData(
                          '3', true, null, taskDayBo))
                ],
              )
            ],
          ),
        ));
  }

  //item布局
  Container buildBasicInformationItem(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 buildNote() {
    return Container(
      alignment: Alignment.centerLeft,
      margin: const EdgeInsets.only(left: 15, top: 10),
      child: const Text(
        "注：请整改人员按要求认真整改",
        style: TextStyle(fontSize: 12, color: Colors.black54),
      ),
    );
  }

  ///选择照片布局
  Widget buildPhotoList() {
    return GridView.builder(
      shrinkWrap: true,
      padding: const EdgeInsets.only(left: 25, top: 10),
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 4, // 每行四列
        childAspectRatio: 1.0, // 宽高比为1
        crossAxisSpacing: 10.0, //水平子Widget之间间距
        mainAxisSpacing: 10.0, //垂直子Widget之间间距
      ),
      itemCount: imageList.length,
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => PhotoViewGalleryScreen(
                        index: index, imageList: imageList)));
          },
          child: Container(
            clipBehavior: Clip.antiAlias,
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(3)),
            child: CachedNetworkImage(
              imageUrl: imageList[index],
              fit: BoxFit.cover,
            ),
          ),
        );
      },
    );
  }
}
