import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:jcs_airport/consts/colors.dart';
import 'package:jcs_airport/consts/styles.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/view/common/image_picker.dart';

class RecordDetail extends StatefulWidget {
  final String equipmentId;
  final String equipmentName;

  const RecordDetail(this.equipmentId, this.equipmentName);

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

class _RecordDetailState extends State<RecordDetail> {
  final Map<String, dynamic> _data = {'facility': {}, 'itemList': [], 'pictures': []};
  final Divider _divider = const Divider(
    height: 15,
  );

  @override
  void initState() {
    super.initState();
    _getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.equipmentName),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Card(
              child: Container(
                padding: const EdgeInsets.all(15),
                child: Stack(
                  children: [
                    Column(
                      children: [
                        Row(
                          children: [
                            const Expanded(child: Text('设施编号:')),
                            Expanded(flex: 3, child: Text((_data['facility']['pointNo'] ?? '').toString())),
                          ],
                        ),
                        const SizedBox(
                          height: 5,
                        ),
                        Row(
                          children: [
                            const Expanded(child: Text('维保设施:')),
                            Expanded(flex: 3, child: Text(_data['facility']['pointName'] ?? '')),
                          ],
                        ),
                        const SizedBox(
                          height: 5,
                        ),
                        Row(
                          children: [
                            const Expanded(child: Text('设施位置:')),
                            Expanded(flex: 3, child: Text(_data['facility']['address'] ?? '')),
                          ],
                        ),
                        const SizedBox(
                          height: 5,
                        ),
                        Row(
                          children: [
                            const Expanded(child: Text('执  行  人:')),
                            Expanded(flex: 3, child: Text(_data['facility']['userName'] ?? '')),
                          ],
                        ),
                        const SizedBox(
                          height: 5,
                        ),
                        Row(
                          children: [
                            const Expanded(child: Text('计划名称:')),
                            Expanded(
                                flex: 3,
                                child: Text(
                                  _data['facility']['planName'] ?? '',
                                  style: const TextStyle(color: Colors.blueAccent),
                                )),
                          ],
                        ),
                        const SizedBox(
                          height: 5,
                        ),
                        Row(
                          children: [
                            const Expanded(child: Text('计划类型:')),
                            Expanded(flex: 3, child: Text(_data['facility']['planTypeDesc'] ?? '')),
                          ],
                        ),
                        const SizedBox(
                          height: 5,
                        ),
                        Row(
                          children: [
                            const Expanded(child: Text('业主单位:')),
                            Expanded(flex: 3, child: Text(_data['facility']['ownerName'] ?? '')),
                          ],
                        ),
                        const SizedBox(
                          height: 5,
                        ),
                        Row(
                          children: [
                            const Expanded(child: Text('计划日期:')),
                            Expanded(
                                flex: 3,
                                child: Text((_data['facility']['beginTime'] ?? '') +
                                    ' - ' +
                                    (_data['facility']['beginTime'] ?? ''))),
                          ],
                        ),
                        const SizedBox(
                          height: 5,
                        ),
                        Row(
                          children: [
                            const Expanded(child: Text('维保时间:')),
                            Expanded(flex: 3, child: Text(_data['facility']['checkTime'] ?? '')),
                          ],
                        ),
                        const SizedBox(
                          height: 5,
                        ),
                        Row(
                          children: [
                            const Expanded(child: Text('风险辨识与管控措施:')),
                            InkWell(
                              onTap: () {
                                showDialog(
                                  context: context,
                                  child: AlertDialog(
                                    title: const Text(
                                      '风险辨识与管控措施：',
                                      style: TextStyle(fontSize: CoreStyles.textSizeMid),
                                    ),
                                    content: SingleChildScrollView(
                                      child: Text(
                                        _data['facility']['riskAndManage'] ?? '无',
                                        style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                                      ),
                                    ),
                                    actions: [
                                      FlatButton(
                                          onPressed: () {
                                            Get.back();
                                          },
                                          child: const Text('确认'))
                                    ],
                                  ),
                                );
                              },
                              child: const Text(
                                '查看',
                                style: TextStyle(color: Colors.blueAccent),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                    Positioned(
                      top: 0,
                      right: 10,
                      child: ClipOval(
                        child: Container(
                          width: 50,
                          height: 50,
                          child: Center(
                            child: Text(
                              _data['facility']['isOkDesc'] ?? '',
                              style: const TextStyle(color: Colors.white, fontSize: 12),
                            ),
                          ),
                          padding: const EdgeInsets.all(5),
                          decoration: BoxDecoration(
                              color:
                                  AMOSColors.maintenanceRecordStatusColor(int.parse(_data['facility']['isOk'] ?? '0'))),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Card(
              child: Container(
                padding: const EdgeInsets.all(15),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Text(
                          widget.equipmentName,
                          style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
                        )
                      ],
                    ),
                    const SizedBox(
                      height: 5,
                    ),
                    Column(
                      children: _data['itemList']
                          .asMap()
                          .map((index, element) => MapEntry(index, _buildItem(context, index, element)))
                          .values
                          .cast<Widget>()
                          .toList(),
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  ///子项标题
  Widget _buildItem(BuildContext context, index, element) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text('${index + 1}.'),
            Expanded(
                child: Text(
              '${element['inputName']}:',
              style: const TextStyle(fontWeight: FontWeight.bold),
            )),
            InkWell(
              onTap: () {
                showDialog(
                  context: context,
                  child: AlertDialog(
                    content: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text(
                            '测试要求：',
                            style: TextStyle(fontSize: CoreStyles.textSizeMid),
                          ),
                          const SizedBox(
                            height: 5,
                          ),
                          Text(
                            element['testRequirement'] ?? '无',
                            style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                          ),
                          const SizedBox(
                            height: 10,
                          ),
                          const Text(
                            '法规依据：',
                            style: TextStyle(fontSize: CoreStyles.textSizeMid),
                          ),
                          const SizedBox(
                            height: 5,
                          ),
                          Text(
                            element['basisJson'] ?? '无',
                            style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                          ),
                        ],
                      ),
                    ),
                    actions: [
                      FlatButton(
                          onPressed: () {
                            Get.back();
                          },
                          child: const Text('确认'))
                    ],
                  ),
                );
              },
              child: const Icon(
                Icons.info_outline,
                color: Colors.grey,
              ),
            ),
          ],
        ),
        Column(
          children: [
            const SizedBox(
              height: 3,
            ),
            Row(
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 20),
                  child: Text(
                    element['inputValue'] ?? '无',
                  ),
                ),
              ],
            ),
          ],
        ),
        const SizedBox(
          height: 10,
        ),
        Row(
          children: const [
            Padding(
              padding: EdgeInsets.only(left: 11),
              child: Text('维保项结论:', style: TextStyle(fontWeight: FontWeight.bold)),
            ),
          ],
        ),
        const SizedBox(
          height: 3,
        ),
        Row(
          children: [
            Padding(
              padding: const EdgeInsets.only(left: 20),
              child: Text(
                element['isOkDesc'] ?? '无',
                style: TextStyle(color: AMOSColors.maintenanceRecordStatusColor(int.parse(element['isOk'] ?? '0'))),
              ),
            ),
          ],
        ),
        const SizedBox(
          height: 10,
        ),
        element['pictures'].length > 0
            ? Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: const [
                      Padding(
                        padding: EdgeInsets.only(left: 11),
                        child: Text('照片:', style: TextStyle(fontWeight: FontWeight.bold)),
                      ),
                    ],
                  ),
                  const SizedBox(
                    height: 3,
                  ),
                  const SizedBox(
                    height: 5,
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 20),
                    child: ImagePickerAndRemove(
                      element['pictures'],
                      readOnly: true,
                    ),
                  )
                ],
              )
            : Container(),
        const SizedBox(
          height: 10,
        ),
        (element['remark'] != null && element['remark'] != '')
            ? Column(
                children: [
                  const Padding(
                    padding: EdgeInsets.only(left: 11),
                    child: Text(
                      '问题描述:',
                      style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
                    ),
                  ),
                  const SizedBox(
                    height: 3,
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 11),
                    child: Text(
                      element['remark'] ?? '无',
                    ),
                  ),
                  const SizedBox(
                    height: 10,
                  ),
                ],
              )
            : Container(),
        (element['issuePictures'] != null && element['issuePictures'].length > 0)
            ? Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Padding(
                    padding: EdgeInsets.only(left: 11),
                    child: Text(
                      '问题照片:',
                      style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
                    ),
                  ),
                  const SizedBox(
                    height: 3,
                  ),
                  const SizedBox(
                    height: 5,
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 20),
                    child: ImagePickerAndRemove(
                      element['issuePictures'],
                      readOnly: true,
                    ),
                  )
                ],
              )
            : Container(),
        _divider
      ],
    );
  }

  Future<void> _getData() async {
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      var data = await API.maintenanceRecordDetail(widget.equipmentId);
      Get.back();
      if (data != null) {
        data['itemList'].forEach((element) {
          var checkInputShot = element['checkInputShot'];
          List<ChooseFileInfo> pictures = [];
          List<ChooseFileInfo> issuePictures = [];
          if (checkInputShot != null && checkInputShot.length > 0) {
            checkInputShot.forEach((element) {
              if (element['shotType'] == '1') {
                //动态表单照片
                pictures.add(ChooseFileInfo(null, isPhoto: true, isVideo: false, url: element['fileUrl']));
              } else if (element['shotType'] == '2') {
                //不合格表单照片
                issuePictures.add(ChooseFileInfo(null, isPhoto: true, isVideo: false, url: element['fileUrl']));
              }
            });
          }
          element.addAll({'pictures': pictures, 'issuePictures': issuePictures});
        });
        setState(() {
          _data.addAll(data);
        });
      }
    });
  }
}
