import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:qhd_prevention/customWidget/ItemWidgetFactory.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/picker/CupertinoDatePicker.dart';
import 'package:qhd_prevention/customWidget/single_image_viewer.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/home/tap/item_list_widget.dart';
import 'package:qhd_prevention/pages/mine/mine_sign_page.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';



class WorkShopSafetyCommitmentApply extends StatefulWidget {
  const WorkShopSafetyCommitmentApply({super.key});

  @override
  State<WorkShopSafetyCommitmentApply> createState() => _WorkShopSafetyCommitmentApplyState();
}

class _WorkShopSafetyCommitmentApplyState extends State<WorkShopSafetyCommitmentApply> {


  final TextEditingController _controller1 = TextEditingController();
  final TextEditingController _controller2 = TextEditingController();
  final TextEditingController _controller3 = TextEditingController();
  final TextEditingController _controller4 = TextEditingController();
  final TextEditingController _controller5 = TextEditingController();
  final TextEditingController _controller6 = TextEditingController();
  final TextEditingController _controller7 = TextEditingController();
  final TextEditingController _controller8 = TextEditingController();
  final TextEditingController _controller9 = TextEditingController();
  final TextEditingController _controller10 = TextEditingController();
  final TextEditingController _controller11 = TextEditingController();
  final TextEditingController _controller12 = TextEditingController();
  final TextEditingController _controller13 = TextEditingController();
  final TextEditingController _controller14 = TextEditingController();
  final TextEditingController _controller15 = TextEditingController();
  final TextEditingController _controller16 = TextEditingController();
  final TextEditingController _controller17 = TextEditingController();
  final TextEditingController _controller18 = TextEditingController();
  final TextEditingController _controller19 = TextEditingController();


  bool _isFault1 = true;
  bool _isFault2 = true;
  bool _isFault3 = true;
  bool _isFault4 = true;
  bool _isFault5 = true;
  bool _isFault6 = true;
  bool _isFault7 = true;
  bool _isFault8 = true;
  bool _isFault9 = true;
  bool _isFault10 = true;
  bool _isFault11 = true;
  bool _isFault12 = true;
  bool _isFault13 = true;
  bool _isFault14 = true;
  bool _isFault15 = true;

  DateTime? dataStart;
  String dataTimeStart="";
  DateTime? dataEnd;
  String dataTimeEnd="";

  List<String> signImgList = [];





  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: "安全承诺"),
      body:Container(
        padding: EdgeInsets.only(top: 15,bottom:15,left: 15,right: 15),
        child:  ListView(
          children: [

            ListItemFactory.createBuildSimpleSection('企业状态',horPadding: 0,color: Color(0x00000000)),

            Container(
              padding: EdgeInsets.symmetric(vertical: 5),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(5),
              ),
              child: Column(
                children: [

                  ListItemFactory.createBlueDotSection('高危生产活动及作业的安全风险可控状态',color: 0xffffffff),
                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '特殊作业：',
                    isEditable: true,
                    controller: _controller1,
                    text:  '',
                  ),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: ' 风险辨识、作业许可及管控措施的落实情况',
                    horizontalPadding: 0,
                    groupValue: _isFault1,
                    onChanged: (val) {
                      setState(() {
                        _isFault1 = val;
                      });
                    },
                  ),

                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '动火作业：',
                    isEditable: true,
                    controller: _controller2,
                    text:  '',
                  ),
                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '其中特级：',
                    isEditable: true,
                    controller: _controller3,
                    text:  '',
                  ),
                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '一级：',
                    isEditable: true,
                    controller: _controller4,
                    text:  '',
                  ),

                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '二级：',
                    isEditable: true,
                    controller: _controller5,
                    text:  '',
                  ),

                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '高处作业：',
                    isEditable: true,
                    controller: _controller6,
                    text:  '',
                  ),

                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '受限空间作业：',
                    isEditable: true,
                    controller: _controller7,
                    text:  '',
                  ),
                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '吊装作业：',
                    isEditable: true,
                    controller: _controller8,
                    text:  '',
                  ),

                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '临时用电作业：',
                    isEditable: true,
                    controller: _controller9,
                    text:  '',
                  ),

                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '盲板抽堵作业：',
                    isEditable: true,
                    controller: _controller10,
                    text:  '',
                  ),

                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '动土作业：',
                    isEditable: true,
                    controller: _controller11,
                    text:  '',
                  ),

                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '断路作业：',
                    isEditable: true,
                    controller: _controller12,
                    text:  '',
                  ),
                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '检维修作业：',
                    isEditable: true,
                    controller: _controller13,
                    text:  '',
                  ),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: ' 处于试生产情况',
                    horizontalPadding: 0,
                    groupValue: _isFault2,
                    onChanged: (val) {
                      setState(() {
                        _isFault2 = val;
                      });
                    },
                  ),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: ' 处于开停车情况',
                    horizontalPadding: 0,
                    yesLabel:"开",
                    noLabel:"停",
                    groupValue: _isFault3,
                    onChanged: (val) {
                      setState(() {
                        _isFault3 = val;
                      });
                    },
                  ),
                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '承包商作业：',
                    isEditable: true,
                    controller: _controller14,
                    text:  '',
                  ),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: ' 管控情况',
                    horizontalPadding: 0,
                    yesLabel:"受控",
                    noLabel:"非受控",
                    groupValue: _isFault4,
                    onChanged: (val) {
                      setState(() {
                        _isFault4 = val;
                      });
                    },
                  ),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: ' 变更情况',
                    horizontalPadding: 0,
                    yesLabel:"有",
                    noLabel:"没有",
                    groupValue: _isFault5,
                    onChanged: (val) {
                      setState(() {
                        _isFault5 = val;
                      });
                    },
                  ),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: ' 落实审批程序情况',
                    horizontalPadding: 0,
                    groupValue: _isFault6,
                    onChanged: (val) {
                      setState(() {
                        _isFault6 = val;
                      });
                    },
                  ),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: ' 罐区、仓库等危险源是否处于安全状态',
                    horizontalPadding: 0,
                    groupValue: _isFault7,
                    onChanged: (val) {
                      setState(() {
                        _isFault7 = val;
                      });
                    },
                  ),


                ],
              ),
            ),


            SizedBox(height: 15,),

            Container(
              padding: EdgeInsets.symmetric(vertical: 5),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(5),
              ),
              child: Column(
                children: [
                  ListItemFactory.createBlueDotSection('车间安全状态',color: 0xffffffff),
                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '车间岗位：',
                    isEditable: true,
                    controller: _controller15,
                    text:  '',
                  ),
                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '其中运行：',
                    isEditable: true,
                    controller: _controller16,
                    text:  '',
                  ),
                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '停产：',
                    isEditable: true,
                    controller: _controller17,
                    text:  '',
                  ),
                  const Divider(),
                  ItemListWidget.singleLineTitleText(
                    label: '检修：',
                    isEditable: true,
                    controller: _controller18,
                    text:  '',
                  ),

                ],
              ),
            ),

            SizedBox(height: 15,),

            Container(
              padding: EdgeInsets.symmetric(vertical: 5),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(5),
              ),
              child: Column(
                children: [
                  ListItemFactory.createBlueDotSection('生产装置的安全运行状态',color: 0xffffffff),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: '生产装置的温度、压力、组分液位、流量等主要工艺参数是否处于指标范围',
                    horizontalPadding: 0,
                    groupValue: _isFault8,
                    onChanged: (val) {
                      setState(() {
                        _isFault8 = val;
                      });
                    },
                  ),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: '压力容器、压力管道等特种设备处于安全运行状态',
                    horizontalPadding: 0,
                    groupValue: _isFault9,
                    onChanged: (val) {
                      setState(() {
                        _isFault9 = val;
                      });
                    },
                  ),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: '设备设施的静动密封完好无泄漏',
                    horizontalPadding: 0,
                    groupValue: _isFault10,
                    onChanged: (val) {
                      setState(() {
                        _isFault10 = val;
                      });
                    },
                  ),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: '超限报警、紧急切断、联锁等各类安全设施配备完好投用，并可靠运行',
                    horizontalPadding: 0,
                    groupValue: _isFault11,
                    onChanged: (val) {
                      setState(() {
                        _isFault11 = val;
                      });
                    },
                  ),


                ],
              ),
            ),


            SizedBox(height: 15,),

            Container(
              padding: EdgeInsets.symmetric(vertical: 5),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(5),
              ),
              child: Column(
                children: [
                  ListItemFactory.createBlueDotSection('危险化学品罐区、仓库等重大危险源安全运行状态',color: 0xffffffff),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: '储罐、管道、机泵、阀门及仪表系统完好无泄漏',
                    horizontalPadding: 0,
                    groupValue: _isFault12,
                    onChanged: (val) {
                      setState(() {
                        _isFault12 = val;
                      });
                    },
                  ),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: '储罐的液位、温度、压力、气柜钟罩无超限运行',
                    horizontalPadding: 0,
                    groupValue: _isFault13,
                    onChanged: (val) {
                      setState(() {
                        _isFault13 = val;
                      });
                    },
                  ),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: '手动放脱水、装卸车时确保人员在岗',
                    horizontalPadding: 0,
                    groupValue: _isFault14,
                    onChanged: (val) {
                      setState(() {
                        _isFault14 = val;
                      });
                    },
                  ),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: '可燃及有毒气体报警和联锁处于可靠运行状态',
                    horizontalPadding: 0,
                    groupValue: _isFault15,
                    onChanged: (val) {
                      setState(() {
                        _isFault15 = val;
                      });
                    },
                  ),
                  const Divider(),
                  Padding(
                      padding: EdgeInsets.only(left: 15,right: 15),
                    child:  ListItemFactory.createBuildMultilineInput(
                      "仓库是否按照国家标准分区分类储存危险化学品，是否超量、超品种储存，相互禁配物质是否混放混存。",
                      "请输入...",
                      _controller19,
                      isRequired:true,
                    ),

                  ),


                ],
              ),
            ),

            SizedBox(height: 5,),
            ListItemFactory.createBuildSimpleSection('企业承诺',horPadding: 0,color: Color(0x00000000)),
            SizedBox(height: 5,),

            Container(
              padding: EdgeInsets.symmetric(vertical: 5,horizontal: 15),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(5),
              ),
              child: Column(
                children: [

                  GestureDetector(
                    child: ItemListWidget.selectableLineTitleTextRightButton(label: '今日', text: dataTimeStart.isEmpty?
                    '请选择':dataTimeStart??'', isEditable: true, isRequired: true,horizontalnum: 0),
                    onTap: () async {
                      DateTime? picked = await BottomDateTimePicker.showDate(context,allowFuture: true);
                      if (picked != null) {

                        setState(() {
                          dataStart=picked;
                          if(dataTimeEnd.isNotEmpty) {
                            bool isChao= validateDateRange(dataStart!,dataEnd!);
                            if(!isChao){
                              return;
                            }
                          }
                          dataTimeStart = DateFormat('yyyy-MM-dd HH:mm').format(picked);
                        });
                      }
                    },
                  ),


                  const Divider(),
                  GestureDetector(
                    child:ItemListWidget.selectableLineTitleTextRightButton(label: '至', text: dataTimeEnd.isEmpty?
                    '请选择':dataTimeEnd, isEditable: true, isRequired: true,horizontalnum: 0),
                    onTap: () async {
                      DateTime? picked = await BottomDateTimePicker.showDate(context,allowFuture: true);
                      if (picked != null) {

                        setState(() {
                          dataEnd=picked;
                          if(dataTimeStart.isNotEmpty) {
                            bool isChao= validateDateRange(dataStart!, dataEnd!);
                            if(!isChao){
                              return;
                            }
                          }
                          dataTimeEnd = DateFormat('yyyy-MM-dd HH:mm').format(picked);
                        });
                      }
                    },
                  ),


                  const Divider(),
                  Text("今天我公司已进行安全风险研判，各项安全风险防控措施已落实到位，我承诺所有生产设施处于安全运行状态，罐区、库房等危险源安全风险得到有效控制。",
                    style: TextStyle(color: Colors.black,fontSize: 13),),
                  const Divider(),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('承诺人：', style: TextStyle(fontSize: 16)),
                      CustomButton(
                        text: '手写签字',
                        height: 36,
                        backgroundColor: Colors.green,
                        onPressed: _sign,
                      ),
                    ],
                  ),
                  if (signImgList.isNotEmpty) _signListWidget(),

                ],
              ),
            ),

            SizedBox(height: 15,),

            CustomButton(
                backgroundColor: Colors.green,
                text: "提交",
                onPressed: () {
                  // TODO: 完成回调
                  _upData();
                }
            ),


          ],
        ),
      ) ,

    );
  }



  Future<void> _upData() async {
    try {

      String text1=_controller1.text.trim();
      if(text1.isEmpty){
        ToastUtil.showNormal(context, "请输入特殊作业数");
        return;
      }

      String text2=_controller2.text.trim();
      if(text2.isEmpty){
        ToastUtil.showNormal(context, "请输入动火作业数");
        return;
      }

      String text3=_controller3.text.trim();
      if(text3.isEmpty){
        ToastUtil.showNormal(context, "请输入特级动火作业数");
        return;
      }

      String text4=_controller4.text.trim();
      if(text4.isEmpty){
        ToastUtil.showNormal(context, "请输入一级动火作业数");
        return;
      }

      String text5=_controller5.text.trim();
      if(text5.isEmpty){
        ToastUtil.showNormal(context, "请输入二级动火作业数");
        return;
      }

      String text6=_controller6.text.trim();
      if(text6.isEmpty){
        ToastUtil.showNormal(context, "请输入高处作业数");
        return;
      }

      String text7=_controller7.text.trim();
      if(text7.isEmpty){
        ToastUtil.showNormal(context, "请输入受限空间作业数");
        return;
      }

      String text8=_controller8.text.trim();
      if(text8.isEmpty){
        ToastUtil.showNormal(context, "请输入吊装作业数");
        return;
      }

      String text9=_controller9.text.trim();
      if(text9.isEmpty){
        ToastUtil.showNormal(context, "请输入临时用电作业数");
        return;
      }

      String text10=_controller10.text.trim();
      if(text10.isEmpty){
        ToastUtil.showNormal(context, "请输入盲板抽堵作业数");
        return;
      }

      String text11=_controller11.text.trim();
      if(text11.isEmpty){
        ToastUtil.showNormal(context, "请输入动土作业数");
        return;
      }

      String text12=_controller12.text.trim();
      if(text12.isEmpty){
        ToastUtil.showNormal(context, "请输入断路作业数");
        return;
      }

      String text13=_controller13.text.trim();
      if(text13.isEmpty){
        ToastUtil.showNormal(context, "请输入检维修作业数");
        return;
      }

      String text14=_controller14.text.trim();
      if(text14.isEmpty){
        ToastUtil.showNormal(context, "请输入承包商作业数");
        return;
      }

      String text15=_controller15.text.trim();
      if(text15.isEmpty){
        ToastUtil.showNormal(context, "请输入车间岗位数");
        return;
      }

      String text16=_controller16.text.trim();
      if(text16.isEmpty){
        ToastUtil.showNormal(context, "请输入车间岗位运行数");
        return;
      }

      String text17=_controller17.text.trim();
      if(text17.isEmpty){
        ToastUtil.showNormal(context, "请输入车间岗位停产数");
        return;
      }

      String text18=_controller18.text.trim();
      if(text18.isEmpty){
        ToastUtil.showNormal(context, "请输入车间岗位检修数");
        return;
      }

      String text19=_controller19.text.trim();
      if(text19.isEmpty){
        ToastUtil.showNormal(context, "请输入仓库是否按照国家标准分区分类储存危险化学品，是否超量、超品种储存，相互禁配物质是否混放混存");
        return;
      }








      if(dataTimeStart.isEmpty){
        ToastUtil.showNormal(context, "请选择承诺时间");
        return;
      }

      if(dataTimeEnd.isEmpty){
        ToastUtil.showNormal(context, "请选择承诺时间");
        return;
      }

      if(signImgList.isEmpty){
        ToastUtil.showNormal(context, "请签字");
        return;
      }

      LoadingDialogHelper.show(message: "提交中。。。");

      final formData = {
        'INPUT1': text1,
        'INPUT2': text2,
        'INPUT3': text3,
        'INPUT4': text4,
        'INPUT5': text5,
        'INPUT6': text6,
        'INPUT7': text7,
        'INPUT8': text8,
        'INPUT9': text9,
        'INPUT10': text10,
        'INPUT11': text11,
        'INPUT12': text12,
        'INPUT13': text13,
        'INPUT14': text14,
        'INPUT15': text15,
        'INPUT16': text16,
        'INPUT17': text17,
        'INPUT18': text18,
        'INPUT19': text19,


        'RADIO1': _isFault1?"1":"-1",
        'RADIO2': _isFault2?"1":"-1",
        'RADIO3': _isFault3?"1":"-1",
        'RADIO4': _isFault4?"1":"-1",
        'RADIO5': _isFault5?"1":"-1",
        'RADIO6': _isFault6?"1":"-1",
        'RADIO7': _isFault7?"1":"-1",
        'RADIO8': _isFault8?"1":"-1",
        'RADIO9': _isFault9?"1":"-1",
        'RADIO10': _isFault10?"1":"-1",
        'RADIO11': _isFault11?"1":"-1",
        'RADIO12': _isFault12?"1":"-1",
        'RADIO13': _isFault13?"1":"-1",
        'RADIO14': _isFault14?"1":"-1",
        'RADIO15': _isFault15?"1":"-1",

        'START_TIME':dataTimeStart,
        'END_TIME': dataTimeEnd,


        "SIGNER_TIME":DateFormat('yyyy-MM-dd HH:mm').format(DateTime.now()) ,
        'DEPARTMENT_ID':SessionService.instance.loginUser?["DEPARTMENT_ID"],
        'SIGN_USER': SessionService.instance.loginUserId,
        "CORPINFO_ID": SessionService.instance.corpinfoId,
        'USER_ID': SessionService.instance.loginUserId,
      };


      final Map<String, dynamic>response = await ApiService.upWorkshopSafetyCommitmentApply(formData,signImgList);
      LoadingDialogHelper.hide();
      if (response['result'] == 'success') {
        setState(() {
          Navigator.pop(context);
        });
      }else{
        ToastUtil.showNormal(context, response['msg']);
      }
    } catch (e) {
      LoadingDialogHelper.hide();
      print('Error fetching data: $e');

    }
  }



  Future<void> _sign() async {
    await NativeOrientation.setLandscape();
    final String path = await Navigator.push(
      context,
      MaterialPageRoute(builder: (c) => MineSignPage()),
    );
    if (path != null) {
      setState(() {
        signImgList.add(path);
      });

    }
  }

  Widget _signListWidget() {
    return Column(
      children:
      signImgList.map((imgData) {
        final idx = signImgList.indexOf(imgData);
        return Column(
          children: [
            const SizedBox(height: 10),
            const Divider(),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                GestureDetector(
                  child: ConstrainedBox(
                    constraints: const BoxConstraints(
                      maxWidth: 230,
                      maxHeight: 150,
                    ),
                    child:
                    Image.file(
                      File(signImgList[0] ?? ''),
                      fit: BoxFit.contain,
                    ),
                  ),
                  onTap:
                      () => presentOpaque(
                    SingleImageViewer(imageUrl:signImgList[0] ?? ''),
                    context,
                  ),
                ),
                Column(
                  children: [
                    CustomButton(
                      text: '删除',
                      height: 30,
                      padding: const EdgeInsets.symmetric(horizontal: 10),
                      backgroundColor: Colors.red,
                      onPressed: () {
                        setState(() => signImgList.removeAt(idx));
                      },
                    ),
                    const SizedBox(height: 80),
                  ],
                ),
              ],
            ),
          ],
        );
      }).toList(),
    );
  }


  bool validateDateRange(DateTime startTime, DateTime endTime) {
    const int thirtyDaysInMilliseconds = 30 * 24 * 60 * 60 * 1000; // 30 天的毫秒数
    final int difference = endTime.millisecondsSinceEpoch - startTime.millisecondsSinceEpoch;

    if (difference > thirtyDaysInMilliseconds) {
      ToastUtil.showNormal(context, "只能选择30天内的日期");
      return false;
    }else{
      return true;
    }
  }


}
