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/http/HttpManager.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 CompanySafetyCommitmentApply extends StatefulWidget {
  const CompanySafetyCommitmentApply({super.key});

  @override
  State<CompanySafetyCommitmentApply> createState() => _CompanySafetyCommitmentApplyState();
}

class _CompanySafetyCommitmentApplyState extends State<CompanySafetyCommitmentApply> {


  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();

  bool _isFault1 = true;
  bool _isFault2 = true;
  bool _isFault3 = 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: [

                  ItemListWidget.singleLineTitleText(
                    label: '生产装置：',
                    isEditable: true,
                    controller: _controller1,
                    text:  '',
                  ),
                  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:  '',
                  ),


                ],
              ),
            ),


            SizedBox(height: 15,),

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

                  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:  '',
                  ),

                ],
              ),
            ),

            SizedBox(height: 15,),

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

                  ListItemFactory.createYesNoSection(
                    title: '是否处于生产',
                    horizontalPadding: 0,
                    groupValue: _isFault1,
                    onChanged: (val) {
                      setState(() {
                        _isFault1 = val;
                      });
                    },
                  ),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: '是否处于开停车状态',
                    horizontalPadding: 0,
                    groupValue: _isFault2,
                    onChanged: (val) {
                      setState(() {
                        _isFault2 = val;
                      });
                    },
                  ),
                  const Divider(),
                  ListItemFactory.createYesNoSection(
                    title: '罐区、库房等危险源是否处于安全状态',
                    horizontalPadding: 0,
                    groupValue: _isFault3,
                    onChanged: (val) {
                      setState(() {
                        _isFault3 = val;
                      });
                    },
                  ),


                ],
              ),
            ),

            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(text1.isEmpty){
        ToastUtil.showNormal(context, "请输入生产装置运行数");
        return;
      }

      String text3=_controller3.text.trim();
      if(text1.isEmpty){
        ToastUtil.showNormal(context, "请输入生产装置停产数");
        return;
      }

      String text4=_controller4.text.trim();
      if(text1.isEmpty){
        ToastUtil.showNormal(context, "请输入生产装置检修数");
        return;
      }

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

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

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

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

      String text9=_controller9.text.trim();
      if(text1.isEmpty){
        ToastUtil.showNormal(context, "请输入登高作业数");
        return;
      }

      String text10=_controller10.text.trim();
      if(text1.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: "提交中。。。");


     String nowTime= DateFormat('yyyy-MM-dd HH:mm').format(DateTime.now());

      final formData = {
        'INPUT1': text1,
        'INPUT2': text2,
        'INPUT3': text3,
        'INPUT4': text4,
        'INPUT5': text5,
        'INPUT6': text6,
        'INPUT7': text7,
        'INPUT8': text8,
        'INPUT9': text9,
        'INPUT10': text10,

        'RADIO1': _isFault1?"1":"-1",
        'RADIO2': _isFault2?"1":"-1",
        'RADIO3': _isFault3?"1":"-1",

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


        "SIGNER_TIME": nowTime,
        'DEPARTMENT_ID':SessionService.instance.loginUser?["DEPARTMENT_ID"],
        'SIGN_USER': SessionService.instance.loginUserId,
        "CORPINFO_ID": SessionService.instance.corpinfoId,
        'USER_ID': SessionService.instance.loginUserId,
      };

      print(formData.toString());
      final file = File(signImgList[0]);
      if (!await file.exists()) {
        throw ApiException('file_not_found', '图片不存在：${signImgList[0]}');
      }
      final Map<String, dynamic>response = await ApiService.upCompanySafetyCommitmentApply(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;
    }
  }


}
