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/date_picker_dialog.dart';
import 'package:qhd_prevention/customWidget/photo_picker_row.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/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';

class ImmediatelyInspection extends StatefulWidget {
  const ImmediatelyInspection(this.id, {super.key});

  final String id;

  @override
  State<ImmediatelyInspection> createState() => _ImmediatelyInspectionState();
}

class _ImmediatelyInspectionState extends State<ImmediatelyInspection> {
  final TextEditingController _xunController = TextEditingController();
  final TextEditingController _neiRongController = TextEditingController();

  // 是否有故障
  bool _isFault = false;
  String dataTime = "";

  List<String> _guZhangImages = [];
  List<String> _xiuGaiImages = [];
  List<String> _xunJianImages = [];

  List<String> allImagePaths = [];
  List<String> allImageTypes = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: "开始巡检"),
      body: ListView(
        children: [
          Container(
            color: Colors.white,
            child: Column(
              children: [
                ItemListWidget.singleLineTitleText(
                  label: '巡检人：',
                  isEditable: true,
                  isRequired: false,
                  controller: _xunController,
                  hintText: '请输入巡检人',
                  text: '',
                ),
                const Divider(),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                  child: GestureDetector(
                    child: ItemListWidget.selectableLineTitleTextRightButton(
                      label: '巡检日期',
                      text: dataTime.isEmpty ? '请选择' : dataTime ?? '',
                      isEditable: true,
                      isRequired: false,
                      horizontalnum: 0,
                    ),
                    onTap: () async {
                      showDialog(
                        context: context,
                        builder:
                            (_) => HDatePickerDialog(
                              initialDate: DateTime.now(),
                              onCancel: () => Navigator.of(context).pop(),
                              onConfirm: (selected) {
                                Navigator.of(context).pop();
                                setState(() {
                                  dataTime = DateFormat(
                                    'yyyy-MM-dd',
                                  ).format(selected);
                                });
                              },
                            ),
                      );
                    },
                  ),
                  // ListItemFactory.createRowSpaceBetweenItem(
                  //   leftText: "巡检日期",
                  //   rightText: dataTime.isEmpty?"请选择":dataTime,
                  //   isRight: true,
                  // ),
                ),
              ],
            ),
          ),

          SizedBox(height: 15),

          Container(
            color: Colors.white,
            child: ItemListWidget.multiLineTitleTextField(
              label: '巡检内容：',
              isEditable: true,
              isRequired: false,
              controller: _neiRongController,
              hintText: "(必填)",
              text: '',
            ),
          ),

          SizedBox(height: 15),
          ListItemFactory.createYesNoSection(
            title: '是否有故障',
            horizontalPadding: 2,
            groupValue: _isFault,
            onChanged: (val) {
              setState(() {
                _isFault = val;
              });
            },
          ),

          // if(_isFault)
          // SizedBox(height: 15,),
          if (_isFault)
            RepairedPhotoSection(
              horizontalPadding: 15,
              title: "故障照片",
              maxCount: 4,
              mediaType: MediaType.image,
              onMediaAdded: (value) {
                _guZhangImages.add(value);
              },
              onMediaRemoved: (value) {
                _guZhangImages.remove(value);
              },
              onChanged: (files) {},
              onAiIdentify: () {},
            ),

          SizedBox(height: _isFault ? 15 : 0),
          if (_isFault)
            RepairedPhotoSection(
              horizontalPadding: 15,
              title: "故障处理后照片",
              maxCount: 4,
              mediaType: MediaType.image,
              onMediaAdded: (value) {
                _xiuGaiImages.add(value);
              },
              onMediaRemoved: (value) {
                _xiuGaiImages.remove(value);
              },
              onChanged: (files) {},
              onAiIdentify: () {},
            ),

          SizedBox(height: _isFault ? 15 : 0),
          RepairedPhotoSection(
            horizontalPadding: 15,
            title: "巡检照片",
            maxCount: 4,
            mediaType: MediaType.image,
            onMediaAdded: (value) {
              _xunJianImages.add(value);
            },
            onMediaRemoved: (value) {
              _xunJianImages.remove(value);
            },
            onChanged: (files) {},
            onAiIdentify: () {},
          ),

          SizedBox(height: 25),
          CustomButton(
            text: "提交",
            backgroundColor: Colors.blue,
            height: 42,
            onPressed: () {
              _startInspection();
            },
          ),
          SizedBox(height: 25),
        ],
      ),
    );
  }

  Future<void> _startInspection() async {
    try {
      String person = _xunController.text.trim();
      if (person.isEmpty) {
        ToastUtil.showNormal(context, "请填巡检人");
        return;
      }

      if (dataTime.isEmpty) {
        ToastUtil.showNormal(context, "请选择巡检时间");
        return;
      }

      String content = _neiRongController.text.trim();
      if (content.isEmpty) {
        ToastUtil.showNormal(context, "请选巡检内容");
        return;
      }

      if (_isFault && _guZhangImages.isEmpty) {
        ToastUtil.showNormal(context, "请上传故障照片");
        return;
      }

      if (_isFault && _xiuGaiImages.isEmpty) {
        ToastUtil.showNormal(context, "请上传故障处理后照片");
        return;
      }

      if (_xunJianImages.isEmpty) {
        ToastUtil.showNormal(context, "请上传巡检图片");
        return;
      }

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

      for (int i = 0; i < _guZhangImages.length; i++) {
        allImagePaths.add(_guZhangImages[i]);
        allImageTypes.add("24");
      }

      for (int m = 0; m < _xiuGaiImages.length; m++) {
        allImagePaths.add(_xiuGaiImages[m]);
        allImageTypes.add("25");
      }

      for (int n = 0; n < _xunJianImages.length; n++) {
        allImagePaths.add(_xunJianImages[n]);
        allImageTypes.add("26");
      }

      final formData = {
        'SPECIALEQUIPMENT_ID': widget.id,
        'CREATOR': SessionService.instance.username,
        'ISFAULT': _isFault ? "是" : "否",
        'INSPECTOR': person,
        'INSPECTIONCONTENT': content,
        'INSPECTIONTIME': dataTime,

        'TYPES': allImageTypes.join(','),
        "CORPINFO_ID": SessionService.instance.corpinfoId,
        'USER_ID': SessionService.instance.loginUserId,
      };

      final result = await ApiService.startInspection(formData, allImagePaths);
      LoadingDialogHelper.hide();
      if (result['result'] == 'success') {
        setState(() {
          ToastUtil.showNormal(context, "提交成功");
          Navigator.pop(context);
        });
      }
    } catch (e) {
      LoadingDialogHelper.hide();
      print('Error fetching data: $e');
    }
  }
}
