// ignore_for_file: library_private_types_in_public_api, must_be_immutable, avoid_print, prefer_typing_uninitialized_variables, use_build_context_synchronously

import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.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/http_utils.dart';
import 'package:special_equipment_flutter/model/day_submit_bo.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/model/system_time.dart';
import 'package:special_equipment_flutter/model/upload_multifile.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_file_screen.dart';
import 'package:special_equipment_flutter/ui/common/text_editing_controller.dart';
import 'package:special_equipment_flutter/utils/baidu_location_util.dart';
import 'package:special_equipment_flutter/utils/log_util.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/app_bar/custom_app_bar.dart';
import 'package:special_equipment_flutter/widgets/dialog/loading_dialog_helper.dart';
import 'package:special_equipment_flutter/widgets/divider_custom.dart';
import 'package:special_equipment_flutter/widgets/number_to_chinese.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

import '../../../../../utils/image_utils.dart';
import '../../../../../widgets/custom_button.dart';
import '../../../../../widgets/dialog/custom_bottom_sheet1.dart';
import '../../../../model/detail/day/child_task_day_list.dart';
import '../../../../model/detail/device_risk.dart';

class RiskControlMeasuresModel {
  String id;
  String name;

  RiskControlMeasuresModel(this.id, this.name);
}

///使用单位
///日管控、周排查、月调度
///检查提交页面
class DayInspectSubmitSyPage extends StatefulWidget {
  ///区分  日管控、周排查、月调度
  var argsBundle = Get.arguments;
  var type;

  DayInspectSubmitSyPage({super.key});

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

class _DayInspectSubmitSyPageState extends State<DayInspectSubmitSyPage> {
  ///检查项默认数据长度
  int acquiesceLength = 0;

  ///选择照片最大数量
  final imageCount = 3;

  ///检查照片
  final List<File>? waterList = [];

  late List<RiskControlMeasuresModel> riskControlMeasuresList = [];

  List<CustomBottomSheetTitleModel> modelList = [
    CustomBottomSheetTitleModel('相册'),
    CustomBottomSheetTitleModel('拍照'),
  ];

  ///type=1（日管控）type=2（周排查）type=3（月调度）
  var type;
  var unitStatus;
  late var taskDayBo;
  List<TaskDayCheckLists> taskDayCheckList = [];
  List<String>? picturesList = [];
  BaiduLocationUtil? baiduLocationUtil = BaiduLocationUtil();

  @override
  void dispose() {
    ///退出页面停止定位
    baiduLocationUtil!.destroy();
    super.dispose();
  }

  // Future<String?> getAddress(latitude, longitude) async {
  //   try {
  //     final placemarks = await placemarkFromCoordinates(latitude, longitude);
  //     if (placemarks.first != null) {
  //       final place = placemarks.first;
  //       var location = place.locality! + place.subLocality! + place.name!;
  //       print('result为定位结果----------$location');
  //       return location;
  //     } else {
  //       return '';
  //     }
  //   } catch (e) {
  //     print(e);
  //     return '';
  //   }
  // }

  @override
  void initState() {
    super.initState();
    baiduLocationUtil!.getCurrentLocation((BaiduLocation baiduLocation) async {
      var locationDetail = '(${baiduLocation.locationDetail})' ?? '';
      var address = '${baiduLocation.address}$locationDetail';
      print('定位返回地址==========$address');
      StorageUtil.getInstance().set(SpKeys.CAMERA_ADDRESS, address);
      // await getAddress(baiduLocation.latitude, baiduLocation.longitude);
    }, once: false).catchError((err) {
      // ToastUtils.showCenter(err);
    });
    type = widget.argsBundle['argsData']['type'];
    taskDayBo = widget.argsBundle['listBo'];
    unitStatus = StorageUtil.getInstance().getUnitStatus();
    getData();
  }

  ///获取数据
  void getData() {
    HttpUtils.getFindTaskDayCheck(context, taskDayBo.id).then((value) {
      DayDetailBo dayDetailBo = value;
      if (mounted) {
        setState(() {
          for (var item in dayDetailBo.taskDayCheckList!) {
            riskControlMeasuresList.add(RiskControlMeasuresModel(
                item.deviceRisk!.id!, item.deviceRisk!.name!));
            if (item.deviceRisk!.isShow != '0') {
              taskDayCheckList.add(item);
            }
          }
          if (taskDayCheckList.isNotEmpty) {
            acquiesceLength = taskDayCheckList.length;
          }
        });
      }
    });
  }

  @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(),

                ///选择照片
                // buildPhotoList(),

                ///基本信息
                buildBasicInformation(),

                ///检查项
                buildCheckItem(),

                ///提交任务
                buildSubmit(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  ///检查项
  Card buildCheckItem() {
    return Card(
        color: Colors.white,
        margin: const EdgeInsets.only(left: 15, top: 0, right: 15, bottom: 0),
        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),

              ///提示
              Container(
                alignment: Alignment.centerLeft,
                margin: const EdgeInsets.only(left: 30),
                child: Text(
                  '注：有风险？请描述风险内容',
                  style: TextStyle(fontSize: 12, color: Colors.grey[500]),
                ),
              ),

              ///分割线
              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);
                    },
                  )),

              ///只有《使用单位-日》才有拍照
              if (unitStatus == '1') ...[
                if (type == '1') ...[
                  ///分割线
                  const DividerCustom(Colors.grey, 15, 15, 0, 0),

                  ///检查照片 标题
                  buildTitle('检查照片', Icons.photo_camera, false),

                  ///检查照片 注意事项
                  Container(
                    alignment: Alignment.centerLeft,
                    margin: const EdgeInsets.only(left: 25),
                    child: const Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          softWrap: true,
                          '注：',
                          style: TextStyle(fontSize: 12, color: Colors.grey),
                        ),
                        Expanded(
                          child: Text.rich(
                              softWrap: true,
                              TextSpan(children: [
                                TextSpan(
                                    text: '1、非必填\n2、请允许《摄像头》《存储》《位置信息》必要权限开启',
                                    style: TextStyle(
                                        fontSize: 12, color: Colors.grey)),
                                TextSpan(
                                  text: '',
                                  style: TextStyle(
                                      fontSize: 12, color: Colors.red),
                                ),
                              ])),
                        ),
                      ],
                    ),
                  ),

                  ///选择照片
                  buildPhotoList(),
                ]
              ],

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

              ///检查人
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  ///标题
                  buildTitle('检查人', Icons.people, true),
                  Text(
                    StorageUtil.getInstance().getName(),
                    style: const TextStyle(fontSize: 14, color: Colors.grey),
                  ),
                ],
              ),
            ],
          ),
        ));
  }

  int num = 100;

  int? getSort() {
    return num++;
  }

  ///检查项item内容
  Column buildItem(int index) {
    return Column(
      children: <Widget>[
        ///补充项 - 判断显示内容
        if (taskDayCheckList[index].deviceRisk!.isCategory!) ...[
          ///检查项-补充项：选择风险管控措施
          buildSeclectRiskControlMeasuresNew(index),
        ] else ...[
          ///设置检查项-默认：风险管控措施标题
          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: BoxDecoration(
                color: taskDayCheckList[index]
                            .childTaskDayList![subIndex]
                            .deviceRisk!
                            .isChecked! ==
                        '2'
                    ? ColorConst.red4BgColor
                    : taskDayCheckList[index]
                                .childTaskDayList![subIndex]
                                .deviceRisk!
                                .isChecked! ==
                            '1'
                        ? ColorConst.green1Color
                        : ColorConst.yellow1Color,
                borderRadius: const BorderRadius.all(Radius.circular(5)),
//                                    border: Border.all(
//                                        width: 0.5,
//                                        color: ColorConst.red1BgColor),
              ),
              child: Padding(
                padding: const EdgeInsets.all(5),
                child: Column(
                  children: [
                    const SizedBox(
                      height: 5,
                    ),

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

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

                    ///单选
                    buildSingleChoice(index, subIndex),

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

                    ///选项有风险显示风险填写内容
                    buildCheckRiskyVisibilityContent(index, subIndex),
                  ],
                ),
              ),
            );
          },
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            if ((index + 1) == acquiesceLength) ...[
              Container(
                margin: const EdgeInsets.only(left: 5, bottom: 5),
                alignment: Alignment.centerLeft,
                child: const Text.rich(
                    softWrap: true,
                    TextSpan(children: [
                      TextSpan(
                          text: '补充项 ',
                          style: TextStyle(
                              fontSize: 14,
                              color: Colors.black54,
                              fontWeight: FontWeight.bold)),
                      TextSpan(
                        text: '(注：检查人可补充的检查项)',
                        style: TextStyle(fontSize: 12, color: Colors.grey),
                      ),
                    ])),
              ),
              InkWell(
                onTap: () {
                  setState(() {
                    ///TODO
                    if (taskDayCheckList.isEmpty) {
                      return;
                    }
                    for (var itemParent in taskDayCheckList) {
                      ///如果是补充项
                      if (itemParent.deviceRisk!.isCategory!) {
                        if (itemParent.deviceRisk!.name!.isEmpty) {
                          ToastUtils.showCenter('请先完善当前《补充项》');
                          return;
                        }
                        for (var itemChild in itemParent.childTaskDayList!) {
                          if (itemChild.deviceRisk!.name!.isEmpty) {
                            ToastUtils.showCenter('请先完善当前《补充项》');
                            return;
                          }
                          if (itemChild.deviceRisk!.isChecked == '2') {
                            if (itemChild.deviceRisk!.riskcontent!.isEmpty) {
                              ToastUtils.showCenter('请先完善当前《补充项》');
                              return;
                            }
                          }
                        }
                      }
                    }

                    List<ChildTaskDayList> childTaskList = [];
                    ChildTaskDayList childTaskDayListBo = ChildTaskDayList(
                        deviceRisk: DeviceRisk(
                            id: '',
                            name: '',
                            sort: getSort(),
                            riskMeasure: '',
                            inspectType: '',
                            isShow: '',
                            parentId: '',
                            isChecked: '1',
                            isEnabled: true,
                            isCategory: true,
                            riskcontent: '',
                            focusNode1: FocusNode(),
                            focusNode2: FocusNode()),
                        sort: getSort());
                    childTaskList.add(childTaskDayListBo);

                    TaskDayCheckLists taskDayCheckListBo = TaskDayCheckLists(
                        deviceRisk: DeviceRisk(
                            id: '',
                            name: '',
                            sort: getSort(),
                            riskMeasure: '',
                            inspectType: '',
                            isShow: '',
                            parentId: '',
                            isChecked: '1',
                            isEnabled: true,
                            isCategory: true,
                            riskcontent: '',
                            focusNode1: FocusNode(),
                            focusNode2: FocusNode()),
                        sort: getSort(),
                        childTaskDayList: childTaskList);
                    taskDayCheckList.add(taskDayCheckListBo);
                  });
                },
                child: const Padding(
                  padding: EdgeInsets.all(10.0),
                  child: Row(
                    children: [
                      Icon(
                        Icons.add_circle_outline,
                        size: 15,
                        color: ColorConst.themeBgColor,
                      ),
                      SizedBox(
                        width: 5,
                      ),
                      Text(
                        '新增',
                        style: TextStyle(
                          fontSize: 14.0,
                          color: ColorConst.themeBgColor,
                        ),
                      )
                    ],
                  ),
                ),
              )
            ],
          ],
        ),
      ],
    );
  }

  ///设置检查项-默认：风险管控措施标题
  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),
      ),
    );
  }

  ///检查项-补充项：选择风险管控措施
  Container buildSeclectRiskControlMeasuresNew(int index) {
    return Container(
      alignment: Alignment.centerLeft,
      width: double.infinity,
      margin: const EdgeInsets.only(top: 5, bottom: 3, left: 0),
      child: PopupMenuButton<int>(
        elevation: 10,
        splashRadius: 55,
        shadowColor: ColorConst.themeBgColor,
        offset: const Offset(-15, 25),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
//                                  side: BorderSide(
//                                    width: 1,
//                                    color: ColorConst.themeBgColor,
//                                    style: BorderStyle.solid,
//                                  ),
        ),
        child: Row(
          children: [
            Container(
              padding:
                  const EdgeInsets.only(left: 5, top: 0, right: 0, bottom: 0),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.black26, width: 0.5),
                borderRadius: BorderRadius.circular(5),
              ),
              child: Row(
                children: [
                  Text(
                      taskDayCheckList[index].deviceRisk!.name!.isEmpty
                          ? '请选择风险类别'
                          : taskDayCheckList[index].deviceRisk!.name!,
                      style:
                          const TextStyle(fontSize: 14, color: Colors.black54)),
                  const Icon(Icons.arrow_drop_down)
                ],
              ),
            ),
          ],
        ),
        itemBuilder: (context) => [
          for (var i = 0; i < riskControlMeasuresList.length; i++) ...[
            PopupMenuItem(
              height: 35,
              padding:
                  const EdgeInsets.only(left: 15, right: 0, top: 5, bottom: 5),
              value: i,
              child: Row(
                children: [
                  Container(
                    alignment: Alignment.center,
                    width: 18,
                    height: 18,
                    decoration: BoxDecoration(
                      color: ColorConst.themeBgColor,
                      borderRadius: BorderRadius.circular(50),
                    ),
                    child: Text(
                      (i + 1).toString(),
                      style: const TextStyle(color: Colors.white, fontSize: 12),
                    ),
                  ),
                  Text('  ${riskControlMeasuresList[i].name}',
                      style: const TextStyle(color: Colors.black, fontSize: 14))
                ],
              ),
            ),
          ],
        ],
        onSelected: (value) {
          setState(() {
            taskDayCheckList[index].deviceRisk!.name =
                riskControlMeasuresList[value].name;
            taskDayCheckList[index].deviceRisk!.id =
                riskControlMeasuresList[value].id;
          });
        },
      ),
    );
  }

  int? index1, index2, subIndex1, subIndex2;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    ///收起键盘后，TextField失去焦点
    if ((WidgetsFlutterBinding.ensureInitialized()
                .platformDispatcher
                .views
                .first
                .viewInsets
                .bottom ??
            0.0) <=
        0.0) {
      if (index1 != null && subIndex1 != null) {
        try {
          taskDayCheckList[index1!]
              .childTaskDayList![subIndex1!]
              .deviceRisk!
              .focusNode1!
              .unfocus();
        } catch (e) {
          e.printError();
        }
      }
      if (index2 != null && subIndex2 != null) {
        try {
          taskDayCheckList[index2!]
              .childTaskDayList![subIndex2!]
              .deviceRisk!
              .focusNode2!
              .unfocus();
        } catch (e) {
          e.printError();
        }
      }
    }
  }

  ///选项有风险显示风险填写内容
  Visibility buildCheckRiskyVisibilityContent(int index, int subIndex) {
    return Visibility(
        visible: taskDayCheckList[index]
                    .childTaskDayList![subIndex]
                    .deviceRisk!
                    .isChecked ==
                '2'
            ? true
            : false,
        child: Column(
          children: [
            const DividerCustom(Colors.white, 10, 0, 0, 0),
            TextField(
              maxLength: 200,
              focusNode: taskDayCheckList[index]
                  .childTaskDayList![subIndex]
                  .deviceRisk!
                  .focusNode1,
              decoration: const InputDecoration(
                hintText: '请描述风险内容...',
                isCollapsed: true,
                hintStyle: TextStyle(color: Colors.red, fontSize: 14),
                border: InputBorder.none,
                contentPadding:
                    EdgeInsets.only(left: 10, top: 15, bottom: 15, right: 5),
              ),
              //动态设置补充项内容
              onChanged: (text) {
                taskDayCheckList[index]
                    .childTaskDayList![subIndex]
                    .deviceRisk!
                    .riskcontent = text;
                index1 = index;
                subIndex1 = subIndex;
              },
              controller: buildController(taskDayCheckList[index]
                      .childTaskDayList![subIndex]
                      .deviceRisk!
                      .riskcontent ??
                  ''),
              maxLines: null,
              style:
                  const TextStyle(fontSize: 14, color: ColorConst.black2Color),
            ),
          ],
        ));
  }

  ///检查项内容、风险管控措施
  Row buildCheckItemContent(int index, int subIndex, BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Flexible(
          flex: 1,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                taskDayCheckList[index]
                        .childTaskDayList![subIndex]
                        .deviceRisk!
                        .isEnabled!
                    ? '\t\t\t\t\t'
                    : '\t${subIndex + 1}、',
                style:
                    const TextStyle(color: ColorConst.blackColor, fontSize: 14),
              ),
              Expanded(
                  child: TextField(
                maxLength: 200,
                focusNode: taskDayCheckList[index]
                    .childTaskDayList![subIndex]
                    .deviceRisk!
                    .focusNode2,
                maxLines: null,
                //动态设置补充项内容
                onChanged: (text) {
                  taskDayCheckList[index]
                      .childTaskDayList![subIndex]
                      .deviceRisk!
                      .name = text;
                  index2 = index;
                  subIndex2 = subIndex;
                },
                //禁止编辑
                enabled: taskDayCheckList[index]
                    .childTaskDayList![subIndex]
                    .deviceRisk!
                    .isEnabled,
                //禁止复制
                enableInteractiveSelection: false,
                controller: buildController(taskDayCheckList[index]
                        .childTaskDayList![subIndex]
                        .deviceRisk!
                        .name ??
                    ''),
                decoration: const InputDecoration(
                  hintText: '请输入检查内容...',
                  isCollapsed: true,
                  hintStyle: TextStyle(color: Colors.grey),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                ),
                style:
                    const TextStyle(fontSize: 14, color: ColorConst.blackColor),
              ))
            ],
          ),
        ),
        InkWell(
          onTap: () {
            if (taskDayCheckList[index]
                .childTaskDayList![subIndex]
                .deviceRisk!
                .isEnabled!) {
              setState(() {
                taskDayCheckList.removeAt(index);
              });
            } else {
              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: Icon(
            taskDayCheckList[index]
                    .childTaskDayList![subIndex]
                    .deviceRisk!
                    .isEnabled!
                ? Icons.do_disturb_on
                : Icons.help,
            color: taskDayCheckList[index]
                    .childTaskDayList![subIndex]
                    .deviceRisk!
                    .isEnabled!
                ? ColorConst.red1BgColor
                : ColorConst.dark9Color,
            size: EdgeInsetsConst.single_choice_icon_size,
          ),
        )
      ],
    );
  }

  ///标题
  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),
                    ),
                  ])),
            )
          ],
        )
      ],
    );
  }

  ///单选
  Row buildSingleChoice(int index, int subIndex) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        ///无风险
        InkWell(
          splashColor: ColorConst.green1Color,
          onTap: () {
            setState(() {
              ///如果选择了有风险填写了风险内容，需要清除内容
              taskDayCheckList[index]
                  .childTaskDayList![subIndex]
                  .deviceRisk!
                  .riskcontent = '';
              taskDayCheckList[index]
                  .childTaskDayList![subIndex]
                  .deviceRisk!
                  .isChecked = '1';
            });
          },
          child: Row(
            children: [
              Icon(
                  taskDayCheckList[index]
                              .childTaskDayList![subIndex]
                              .deviceRisk!
                              .isChecked! ==
                          '1'
                      ? Icons.check_circle
                      : Icons.panorama_fisheye,
                  color: taskDayCheckList[index]
                              .childTaskDayList![subIndex]
                              .deviceRisk!
                              .isChecked! ==
                          '1'
                      ? ColorConst.greenColor
                      : ColorConst.greyC2Color,
                  size: EdgeInsetsConst.single_choice_icon_size),
              const SizedBox(
                width: 5,
              ),
              Text('无风险',
                  style: TextStyle(
                      fontSize: 14,
                      color: taskDayCheckList[index]
                                  .childTaskDayList![subIndex]
                                  .deviceRisk!
                                  .isChecked! ==
                              '1'
                          ? ColorConst.greenColor
                          : Colors.black))
            ],
          ),
        ),

        ///有风险
        InkWell(
          splashColor: ColorConst.blue1Color,
          onTap: () {
            setState(() {
              taskDayCheckList[index]
                  .childTaskDayList![subIndex]
                  .deviceRisk!
                  .isChecked = '2';
            });
          },
          child: Row(
            children: [
              Icon(
                  taskDayCheckList[index]
                              .childTaskDayList![subIndex]
                              .deviceRisk!
                              .isChecked ==
                          '2'
                      ? Icons.cancel
                      : Icons.panorama_fisheye,
                  color: taskDayCheckList[index]
                              .childTaskDayList![subIndex]
                              .deviceRisk!
                              .isChecked ==
                          '2'
                      ? ColorConst.red1BgColor
                      : ColorConst.greyC2Color,
                  size: EdgeInsetsConst.single_choice_icon_size),
              const SizedBox(
                width: 5,
              ),
              Text('有风险',
                  style: TextStyle(
                      fontSize: 14,
                      color: taskDayCheckList[index]
                                  .childTaskDayList![subIndex]
                                  .deviceRisk!
                                  .isChecked ==
                              '2'
                          ? ColorConst.red1BgColor
                          : Colors.black))
            ],
          ),
        ),

        ///无此项
        InkWell(
          splashColor: ColorConst.green1Color,
          onTap: () {
            setState(() {
              taskDayCheckList[index]
                  .childTaskDayList![subIndex]
                  .deviceRisk!
                  .isChecked = '3';
            });
          },
          child: Row(
            children: [
              Icon(
                  taskDayCheckList[index]
                              .childTaskDayList![subIndex]
                              .deviceRisk!
                              .isChecked ==
                          '3'
                      ? Icons.check_circle
                      : Icons.panorama_fisheye,
                  color: taskDayCheckList[index]
                              .childTaskDayList![subIndex]
                              .deviceRisk!
                              .isChecked ==
                          '3'
                      ? ColorConst.yellowColor
                      : ColorConst.greyC2Color,
                  size: EdgeInsetsConst.single_choice_icon_size),
              const SizedBox(
                width: 5,
              ),
              Text('无此项',
                  style: TextStyle(
                      fontSize: 14,
                      color: taskDayCheckList[index]
                                  .childTaskDayList![subIndex]
                                  .deviceRisk!
                                  .isChecked ==
                              '3'
                          ? ColorConst.yellowColor
                          : 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('1', true, 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),
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 4, //每行三个
        childAspectRatio: 1.0, //宽高比1：1
      ),
      itemCount: waterList!.length < imageCount
          ? waterList!.length + 1
          : waterList!.length,
      itemBuilder: (context, index) {
        if (waterList!.length < imageCount) {
          ///没选满
          if (index < waterList!.length) {
            ///需要展示的图片
            return Stack(
              ///层叠布局 图片上面要有一个删除的框
              alignment: Alignment.center,
              children: [
                InkWell(
                  onTap: () {
                    List<String> imageList = [];
                    for (var item in waterList!) {
                      imageList.add(item.path);
                    }
                    Navigator.of(context)
                        .push(MaterialPageRoute(builder: (context) {
                      return PhotoViewGalleryFileScreen(
                          index: index, imageList: imageList);
                    }));
                  },
                  child: Container(
                    margin: const EdgeInsets.all(5),
                    clipBehavior: Clip.antiAlias,
                    decoration:
                        BoxDecoration(borderRadius: BorderRadius.circular(3)),
                    child: Image.file(
                      File(waterList![index].path),
                      fit: BoxFit.cover,
                      width: 200,
                      height: 200,
                    ),
                  ),
                ),
                Positioned(
                  top: 0.0,
                  right: 0.0,
                  width: 20,
                  height: 20,
                  child: GestureDetector(
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(99.0),
                        color: Colors.red,
                      ),
                      padding: const EdgeInsets.all(2.0),
                      child: const Icon(
                        Icons.close,
                        size: 15.0,
                        color: Colors.white,
                      ),
                    ),
                    onTap: () {
                      setState(() {
                        waterList!.removeAt(index);
                      });
                    },
                  ),
                ),
              ],
            );
          } else {
            ///显示添加符号
            return InkWell(
              onTap: () async {
                loadCameraAssets();
              },
              child: Container(
                padding: const EdgeInsets.all(8),
                child: Image.asset('assets/day/add_photo_icon.png'),
              ),
            );
          }
        } else {
          return Stack(
            ///层叠布局 图片上面要有一个删除的框
            alignment: Alignment.center,
            children: [
              InkWell(
                onTap: () {
                  List<String> imageList = [];
                  for (var item in waterList!) {
                    imageList.add(item.path);
                  }
                  Navigator.of(context)
                      .push(MaterialPageRoute(builder: (context) {
                    return PhotoViewGalleryFileScreen(
                        index: index, imageList: imageList);
                  }));
                },
                child: Container(
                  margin: const EdgeInsets.all(5),
                  clipBehavior: Clip.antiAlias,
                  decoration:
                      BoxDecoration(borderRadius: BorderRadius.circular(3)),
                  child: Image.file(
                    File(waterList![index].path),
                    fit: BoxFit.cover,
                    width: 200,
                    height: 200,
                  ),
                ),
              ),
              Positioned(
                top: 0.0,
                right: 0.0,
                width: 20,
                height: 20,
                child: GestureDetector(
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(99.0),
                      color: Colors.red,
                    ),
                    padding: const EdgeInsets.all(2.0),
                    child: const Icon(
                      Icons.close,
                      size: 15.0,
                      color: Colors.white,
                    ),
                  ),
                  onTap: () {
                    setState(() {
                      waterList!.removeAt(index);
                    });
                  },
                ),
              )
            ],
          );
        }
      },
    );
  }

  ///选择照片
//  Future<void> loadAssets() async {
//    final List<AssetEntity>? resultImageList = await AssetPicker.pickAssets(
//        context,
//        pickerConfig: AssetPickerConfig(
//            textDelegate: const AssetPickerTextDelegate(),
//            maxAssets: imageCount - waterList!.length,
//            requestType: RequestType.image,
//            themeColor: Theme.of(context).primaryColor));
//    if (resultImageList == null || resultImageList.isEmpty) return;
//    var imageWaterList = await showImageWaterList(resultImageList);
//    setState(() {
//      waterList!.addAll(imageWaterList);
//      EasyLoading.dismiss();
//    });
//  }

  ///拍照
  Future<void> loadCameraAssets() async {
    final AssetEntity? entity = await CameraPicker.pickFromCamera(
      context,
      pickerConfig: const CameraPickerConfig(
          textDelegate: CameraPickerTextDelegate(),
          shouldDeletePreviewFile: true,
          enableScaledPreview: false,
          resolutionPreset: ResolutionPreset.veryHigh),
    );
    if (entity == null) return;
    Loading.show(showMsg: '正在添加水印');

    ///await getCurrentLocation()
    var variableName = "检查人员：${StorageUtil.getInstance().getName()}\n"
        "设备编号：${taskDayBo.deviceType!.name} - ${taskDayBo.device!.code}\n"
        "拍照时间：${entity.createDateTime.toString().substring(0, 19)}\n"
        "拍照地点：${StorageUtil.getInstance().getCameraAddress() ?? ''}";

    File? imgFile = await entity.file;

    ///压缩图片
    var path = await ImageWaterMarkUtils.compressAndGetFile(imgFile!, 40);

    ///添加水印
    File file = await ImageWaterMarkUtils.imageAddWaterMark(path, variableName);

    setState(() {
      waterList!.add(file);
      Loading.dismiss();
    });
  }

  ///图片上添加水印
  Future<List<File>> showImageWaterList(
      List<AssetEntity> resultImageList) async {
    Loading.show(showMsg: '正在添加水印，请稍等');
    List<File> waterImgFileList = [];
    for (var entity in resultImageList) {
      File? imgFile = await entity.file;
      var variableName = "检查人员：张三\n"
          "设备编号：L33330\n"
          "拍照时间：${entity.createDateTime.toString().substring(0, 19)}\n"
          "拍照地点：：${'太原市小店区xxx小区'}";
      var addImageWaterMark =
          ImageWaterMarkUtils.imageAddWaterMark(imgFile!.path, variableName);
      waterImgFileList.add(await addImageWaterMark);
    }
    return waterImgFileList;
  }

  ///提交任务
  Container buildSubmit() {
    return Container(
      margin: const EdgeInsets.only(top: 20, bottom: 60),
      child: GradientButton(
        tapCallback: () {
          for (var item in taskDayCheckList) {
            var isCategory = item.deviceRisk!.isCategory;
            if (isCategory!) {
              var name = item.deviceRisk!.name;
              var childName = item.childTaskDayList![0].deviceRisk!.name;
              var isChecked = item.childTaskDayList![0].deviceRisk!.isChecked;

              if (name!.isEmpty) {
                ToastUtils.showCenter('(补充项)请选择风险类别');
                return;
              }
              if (childName!.isEmpty) {
                ToastUtils.showCenter('(补充项)请输入检查内容');
                return;
              }

              if (isChecked!.isEmpty) {
                ToastUtils.showCenter('(补充项)请勾选：无风险、有风险、无此项');
                return;
              }
            }
            for (var item1 in item.childTaskDayList!) {
              var isChecked = item1.deviceRisk!.isChecked;
              if (isChecked == '2') {
                var riskcontent = item1.deviceRisk!.riskcontent;
                if (riskcontent!.isEmpty) {
                  if (isCategory) {
                    ToastUtils.showCenter('(补充项)请描述风险内容');
                    return;
                  } else {
                    ToastUtils.showCenter('请描述风险内容');
                    return;
                  }
                }
              }
            }
          }

          List<TaskDayCheckSubmitList> checkLists = [];
          for (var parentItem in taskDayCheckList) {
            var parentId = parentItem.deviceRisk!.id;
            for (var childItem in parentItem.childTaskDayList!) {
              DeviceRiskParents deviceRiskParent =
                  DeviceRiskParents(id: parentId!);
              DeviceRisks deviceRisks =
                  DeviceRisks(id: childItem.deviceRisk!.id!);
              TaskDays taskDays = TaskDays(id: taskDayBo.id!); //列表id
              var isChecked = childItem.deviceRisk!.isChecked;
              String childResults;

              ///选择《有风险》状态为1
              if (isChecked == '1') {
                childResults = '1';
              } else if (isChecked == '2') {
                childResults = "2";
              } else {
                childResults = "3";
              }
              TaskDayCheckSubmitList taskDayCheck = TaskDayCheckSubmitList(
                name: childItem.deviceRisk!.name!,
                result: childResults,
                sort: childItem.deviceRisk!.sort!,
                deviceRiskParent: deviceRiskParent,
                deviceRisk: deviceRisks,
                taskDay: taskDays,
                riskContent: childItem.deviceRisk!.riskcontent ?? "",
                rectHave: '',
                rectContent: '',
                rectUserName: '',
                rectTime: '',
                id: '',
              );
              checkLists.add(taskDayCheck);
            }
          }

          String? results;
          for (var item in taskDayCheckList) {
            for (var item in item.childTaskDayList!) {
              if (item.deviceRisk!.isChecked == '2') {
                results = '2';
                break;
              } else {
                results = '1';
              }
            }
            if (results == '2') {
              break;
            }
          }

          Get.dialog(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),
            shape: const RoundedRectangleBorder(
                // 这里设置shape属性
                borderRadius: BorderRadius.all(Radius.circular(10.0))),
            actions: <Widget>[
              TextButton(
                child: const Text("取消", style: TextStyle(fontSize: 16)),
                onPressed: () {
                  Get.back();
                },
              ),
              TextButton(
                child: const Text("确定", style: TextStyle(fontSize: 16)),
                onPressed: () {
                  buildUpdate(results, checkLists);
                  Get.back();
                },
              ),
            ],
          ));
        },
        width: 180,
        height: 40,
        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),
        ),
      ),
    );
  }

  buildUpdate(String? results, List<TaskDayCheckSubmitList> checkLists) {
    return HttpUtils.doTime(context).then((value) {
      SystemTime systemTime = value;
      if (mounted) {
        ///如果有选择照片
        if (waterList!.isNotEmpty) {
          List<String> imagePaths = [];
          for (var item in waterList!) {
            imagePaths.add(ImageWaterMarkUtils.imageToBase64(item.path));
          }
          HttpUtils.uploadMultifile(context, imagePaths).then((value) {
            UploadMultifile uploadMultifile = value;
            if (mounted) {
              setState(() {
                picturesList = uploadMultifile.pictures;
                print("《日管控-检查》提交服务器返回的照片----->${jsonEncode(picturesList)}");
                DateTime date =
                    DateTime.fromMillisecondsSinceEpoch(systemTime.time!);
                DaySubmitBo daySubmitBo = DaySubmitBo(
                    result: results!,
                    checkTime: date.toString().substring(0, 19),
                    taskState: results,
                    prictures:
                        picturesList!.isNotEmpty ? picturesList!.join(',') : '',
                    checkUser:
                        CheckUser(id: StorageUtil.getInstance().getUserId()),
                    taskDayCheckList: checkLists,
                    id: taskDayBo.id!);
                printLog("《日管控-检查》提交json数据----->${json.encode(daySubmitBo)}");

                ///服务器返回照片，走提交接口
                getDaySubmitData(daySubmitBo);
              });
            }
          });
        } else {
          DateTime date = DateTime.fromMillisecondsSinceEpoch(systemTime.time!);
          DaySubmitBo daySubmitBo = DaySubmitBo(
              result: results!,
              checkTime: date.toString().substring(0, 19),
              taskState: results,
              prictures:
                  picturesList!.isNotEmpty ? picturesList!.join(',') : '',
              checkUser: CheckUser(id: StorageUtil.getInstance().getUserId()),
              taskDayCheckList: checkLists,
              id: taskDayBo.id!);
          printLog("《日管控-检查》提交json数据----->${json.encode(daySubmitBo)}");

          ///没有上传照片，直接走提交接口
          getDaySubmitData(daySubmitBo);
        }
      }
    });
  }

  ///日管控：提交数据
  void getDaySubmitData(DaySubmitBo daySubmitBo) {
    HttpUtils.getDayTaskSave(context, daySubmitBo).then((value) {
      ToastUtils.showCenter('提交成功');
      Get.back(result: true);
    });
  }
}
