import 'dart:convert';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_iot_login_tpl/amos_iot_login_tpl.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart' hide MultipartFile, FormData;
import 'package:jcs_airport/consts/styles.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/view/common/image_picker.dart';
import 'package:jcs_airport/view/workBench/fireproofSupervision/common/choose_fireproof_Supervision_accompany_person.dart';

import 'add_hidden_danger.dart';

///@Description     计划检查详情
///@author          helinlin
///@create          2021-09-02 10:43
class PlanCheckDetail extends StatefulWidget {
  final String originalId;
  final String pointId;
  final String pointName;
  final String pointNumber;
  final String taskName;
  final String planTaskId;
  final String planId;
  final String routeId;
  final bool canExecute;

  const PlanCheckDetail(
    this.originalId,
    this.pointId,
    this.pointName,
    this.pointNumber,
    this.taskName,
    this.planTaskId,
    this.planId,
    this.routeId,
    this.canExecute,
  );

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

class _PlanCheckDetailState extends State<PlanCheckDetail> {
  //现场确认状态
  static const String DANGER_STATE_CONFIRM = 'dangerSubmit';
  final Divider _divider = const Divider();
  final List<Map> _data = [];
  String imageUrl = '';

  @override
  void initState() {
    super.initState();
    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imageUrl = value;
      });
    });
    getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.pointName ?? ''),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Card(
              child: Padding(
                padding: const EdgeInsets.all(15.0),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Row(
                            children: [
                              const Text('检  查  点：'),
                              Expanded(
                                child: Text(
                                  widget.pointName,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Text(widget.pointNumber),
                      ],
                    ),
                    const SizedBox(
                      height: 5,
                    ),
                    Row(
                      children: [
                        const Text('检查计划：'),
                        Text(widget.taskName),
                      ],
                    )
                  ],
                ),
              ),
            ),
            Card(
              child: Padding(
                padding: const EdgeInsets.all(15.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ...buildItem(),
                    widget.canExecute
                        ? Row(
                            children: [
                              Expanded(
                                child: FlatButton(
                                  onPressed: () {
                                    showSubmitDialog(context);
                                  },
                                  child: const Text(
                                    '提交',
                                    style: TextStyle(color: Colors.white),
                                  ),
                                  color: Theme.of(context).primaryColor,
                                ),
                              ),
                            ],
                          )
                        : Container()
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  List<Widget> buildItem() {
    return _data
        .asMap()
        .map((key, value) => MapEntry(
            key,
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text((key + 1).toString() + '.' + value['itemName']),
                Row(
                  children: [
                    Expanded(
                      child: Row(
                        children: value['dataJson']
                            .map((element) => Row(
                                  children: [
                                    Radio(
                                        activeColor: value['isEdit'] ? Colors.grey : Theme.of(context).primaryColor,
                                        value: element['key'],
                                        groupValue: value['value'],
                                        onChanged: (val) {
                                          if (value['isEdit']) {
                                            return;
                                          }
                                          if (val == 'pass' && value['dangerList'].length > 0) {
                                            MsgBox.showConfirmDialog(context, () {
                                              setState(() {
                                                value['dangerList'] = [];
                                                value['value'] = val;
                                              });
                                            }, content: '切换将导致当前项隐患数据丢失，是否切换？');
                                          } else {
                                            setState(() {
                                              value['value'] = val;
                                            });
                                          }
                                        }),
                                    Text(element['name']),
                                  ],
                                ))
                            .cast<Widget>()
                            .toList(),
                      ),
                    ),
                    AnimatedSwitcher(
                      duration: const Duration(milliseconds: 500),
                      reverseDuration: const Duration(milliseconds: 200),
                      child: (value['value'] == 'notPass' && widget.canExecute)
                          ? FlatButton(
                              onPressed: () async {
                                DangerDto dangerDto = await Get.to(AddHiddenDanger(danger: DangerDto()));
                                if (dangerDto != null) {
                                  setState(() {
                                    value['dangerList'].add(dangerDto);
                                  });
                                }
                              },
                              child: const Text(
                                '添加隐患',
                                style: TextStyle(color: Colors.white, fontSize: 13),
                              ),
                              color: Theme.of(context).primaryColor,
                            )
                          : Container(),
                    ),
                  ],
                ),
                AnimatedSwitcher(
                  duration: const Duration(milliseconds: 500),
                  reverseDuration: const Duration(milliseconds: 200),
                  child: value['value'] == 'notPass'
                      ? (value['dangerList'].length > 0
                          ? Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Text('安全隐患:'),
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Column(
                                    children: filterDeleteData(value['dangerList'])
                                        .asMap()
                                        .map((index, item) => MapEntry(
                                              index,
                                              Container(
                                                height: 40,
                                                decoration: BoxDecoration(border: Border.all(color: Colors.grey, width: 0.3)),
                                                padding: const EdgeInsets.symmetric(horizontal: 15),
                                                child: Row(
                                                  children: [
                                                    Expanded(
                                                      child: Row(
                                                        children: [
                                                          Text('${index + 1}.'),
                                                          Text(item.dangerName ?? ''),
                                                        ],
                                                      ),
                                                    ),
                                                    ((item.unReviewed ?? true) && widget.canExecute) //进入审核的隐患不可编辑
                                                        ? Row(
                                                            children: [
                                                              InkWell(
                                                                  child: Icon(
                                                                    Icons.edit_outlined,
                                                                    size: 20,
                                                                    color: Theme.of(context).primaryColor,
                                                                  ),
                                                                  onTap: () async {
                                                                    await Get.to(AddHiddenDanger(danger: item));
                                                                    setState(() {});
                                                                    //showAlertDialog(index, item, value['dangerList']);
                                                                  }),
                                                              const SizedBox(
                                                                width: 12,
                                                              ),
                                                              InkWell(
                                                                  child: Icon(
                                                                    Icons.clear_rounded,
                                                                    size: 22,
                                                                    color: Theme.of(context).primaryColor,
                                                                  ),
                                                                  onTap: () {
                                                                    MsgBox.showConfirmDialog(context, () {
                                                                      if (item.id == null) {
                                                                        setState(() {
                                                                          value['dangerList'].remove(item);
                                                                        });
                                                                      } else {
                                                                        setState(() {
                                                                          item.deleted = true;
                                                                        });
                                                                      }
                                                                    }, content: '是否删除该隐患?');
                                                                    //showAlertDialog(index, item, value['dangerList']);
                                                                  }),
                                                            ],
                                                          )
                                                        : InkWell(
                                                            child: Icon(
                                                              Icons.info_outline_rounded,
                                                              size: 20,
                                                              color: Theme.of(context).primaryColor,
                                                            ),
                                                            onTap: () async {
                                                              await Get.to(AddHiddenDanger(
                                                                danger: item,
                                                                canAdd: false,
                                                              ));
                                                              setState(() {});
                                                              //showAlertDialog(index, item, value['dangerList']);
                                                            }),
                                                  ],
                                                ),
                                              ),
                                            ))
                                        .values
                                        .cast<Widget>()
                                        .toList(),
                                  ),
                                ),
                              ],
                            )
                          : Container())
                      : Container(),
                ),
                const Text('照片:'),
                const SizedBox(
                  height: 10,
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 8.0),
                  child: ImagePickerAndRemove(
                    value['pictures'],
                    readOnly: value['isEdit'],
                  ),
                ),
                const SizedBox(
                  height: 10,
                ),
                const Text('陪同检查人员:'),
                const SizedBox(height: 10),
                InkWell(
                  onTap: () async {
                    if (!widget.canExecute || value['isEdit']) {
                      return;
                    }
                    await Get.to(() =>
                        ChooseFireproofSupervisionAccompanyPerson(widget.originalId, multi: true, persons: value['persons']));
                    String personsText = '';
                    value['persons'].forEach((element) {
                      personsText += '${element['bizOrgName']}  ';
                    });
                    value['controller'].text = personsText;
                    setState(() {});
                  },
                  child: TextField(
                    controller: value['controller'],
                    enabled: false,
                    style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                    decoration: InputDecoration(
                      filled: true,
                      fillColor: FormStyles.CONTENT_COLOR,
                      border: InputBorder.none,
                      suffixIcon: Transform.translate(
                        offset: const Offset(5, 0),
                        child: const Icon(
                          Icons.arrow_right,
                          color: Colors.black87,
                        ),
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 20),
                _divider
              ],
            )))
        .values
        .toList();
  }

  ///只显示未删除的数据
  List filterDeleteData(dangerList) {
    List temp = [];
    (dangerList ?? []).forEach((element) {
      if (!element.deleted) {
        temp.add(element);
      }
    });
    return temp;
  }

  void showAlertDialog(index, danger, dangers) {
    showDialog(
        context: context,
        builder: (BuildContext context) => AlertDialog(
              title: const Text(
                '提示:',
                style: TextStyle(fontSize: 16),
              ),
              content: const Text(
                '请选择操作',
                style: TextStyle(fontSize: 14),
              ),
              actions: [
                MaterialButton(
                  child: const Text(
                    '删除',
                    style: TextStyle(color: Colors.teal, fontSize: 12),
                  ),
                  onPressed: () {
                    Get.back();
                    setState(() {
                      if (danger.id == null) {
                        dangers.remove(danger);
                      } else {
                        danger.deleted = true;
                      }
                    });
                  },
                ),
                MaterialButton(
                  child: const Text(
                    '编辑',
                    style: TextStyle(color: Colors.teal, fontSize: 12),
                  ),
                  onPressed: () async {
                    Get.back();
                    await Get.to(AddHiddenDanger(danger: danger));
                    setState(() {});
                  },
                ),
              ],
            ));
  }

  void showSubmitDialog(BuildContext context) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (
          BuildContext context,
        ) {
          return AlertDialog(
            title: const Text('提示'),
            content: const Text(
              '请选择提交方式(保存为暂存数据，提交为提交整个检查点数据)',
              style: TextStyle(fontSize: 14),
            ),
            actions: [
              MaterialButton(
                child: const Text(
                  '保存',
                  style: TextStyle(color: Colors.teal, fontSize: 14),
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                  _submitData(0);
                },
              ),
              MaterialButton(
                child: const Text(
                  '提交',
                  style: TextStyle(color: Colors.teal, fontSize: 14),
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                  _submitData(1);
                },
              ),
            ],
          );
        });
  }

  void getData() {
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      var data =
          await API.supervisionPointDetailItem({'pointId': widget.pointId, 'routeId': widget.routeId, 'planId': widget.planId});
      Get.back();
      if (data != null) {
        data.forEach((item) {
          //回显检查结果(不可编辑)
          String result = item['selectValue'] ?? '';
          //回显陪同检查人(不可编辑)
          List<Map> persons = [];
          //List<String> userNames = (item['userName'] ?? '') == '' ? [] : (item['userName'] ?? '').split(',');
          //List<String> userIds = (item['userId'] ?? '') == '' ? [] : (item['userId'] ?? '').split(',');

          List<String> userNames = (item['accompanyUserName'] ?? '') == '' ? [] : (item['accompanyUserName'] ?? '').split(',');
          List<String> userIds = (item['accompanyUserId'] ?? '') == '' ? [] : (item['accompanyUserId'] ?? '').split(',');
          for (int i = 0; i < userNames.length; i++) {
            persons.add({'bizOrgName': userNames[i], 'sequenceNbr': userIds[i]});
          }
          //TextEditingController personsController = TextEditingController(text: item['userName'] ?? '');
          TextEditingController personsController = TextEditingController(text: item['accompanyUserName'] ?? '');
          //回显检查照片(不可编辑)
          List<ChooseFileInfo> pictures = [];
          List<String> uploadPath = (item['photoData'] ?? '') == '' ? [] : (item['photoData'] ?? '').split(',');
          uploadPath.forEach((element) {
            pictures.add(ChooseFileInfo(null, isPhoto: true, isVideo: false, url: imageUrl + element));
          });
          //回显隐患记录(未进入流程可编辑，照片可编辑)
          List<DangerDto> dangers = [];
          (item['dangerList'] ?? []).forEach((element) {
            DangerDto dangerDto = DangerDto.fromJson(element);
            dangerDto.photoUrl.forEach((photo) {
              dangerDto.picture.add(ChooseFileInfo(null, isPhoto: true, isVideo: false, url: imageUrl + photo));
            });
            dangers.add(dangerDto);
          });
          item['dataJson'] = json.decode(item['dataJson']);
          item.addAll({
            'value': result,
            'isEdit': result != '',
            'pictures': pictures,
            'persons': persons,
            'dangerList': dangers,
            'controller': personsController,
            'uploadPath': uploadPath,
          });
        });
        setState(() {
          _data.addAll(data.cast<Map<String, Object>>());
        });
      }
    });
  }

  void _submitData(int type) {
    ///校验
    bool canSubmit = false;
    String errMessage = '请至少选择一项！';
    _data.forEach((element) {
      //检查项不为空校验
      if (element['value'] != '') {
        canSubmit = true;
      }
      //陪同检查人校验
      if (element['value'] != '' && element['persons'].isEmpty) {
        canSubmit = false;
        errMessage = '陪同检查人不能为空！';
      }
    });
    if (!canSubmit) {
      ToastUtils.showToast(errMessage);
      return;
    }
    //结束任务，验证所有检查项是否检查
    canSubmit = true;
    if (type == 1) {
      _data.forEach((element) {
        if (element['value'] == '') {
          canSubmit = false;
          errMessage = '请做完所有检查项后提交';
        }
      });
    }
    if (!canSubmit) {
      ToastUtils.showToast(errMessage);
      return;
    }

    ///开始提交
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '提交中，请稍后...');
      List<Future> listTask = [];

      ///图片上传
      _data.forEach((element) {
        //只提交选择了检查结果的图片
        if (element['value'] == '') {
          return;
        }
        //检查点照片提交
        List uploadPath = [];
        if (element['isEdit']) {
          //编辑跳过文件上传，拿来之前路径即可
          List<String> paths = (element['photoData'] ?? '') == '' ? [] : (element['photoData'] ?? '').split(',');
          uploadPath = paths.map((path) => {'path': path}).toList();
        } else {
          element['pictures'].forEach((item) {
            listTask.add(API.uploadImg(item, (path) {
              uploadPath.add({'path': path});
            }));
          });
        }
        element['uploadPath'] = uploadPath;
        //检查点隐患照片提交
        element['dangerList'].forEach((item) {
          List<String> photoUrl = [];
          item.picture.forEach((photo) {
            if (photo.file == null) {
              //编辑
              String url = photo.url.replaceRange(0, imageUrl.length, '');
              photoUrl.add(url);
            } else {
              //新增
              listTask.add(API.uploadImg(photo, (path) {
                photoUrl.add(path);
              }));
            }
          });
          item.photoUrl = photoUrl;
        });
      });

      ///数据提交
      Future.wait(listTask).then((value) async {
        List checkItems = [];
        //提交预处理 上传照片，构建JSON数据结构
        _data.forEach((element) {
          //只提交选择了检查结果的数据
          if (element['value'] == '') {
            return;
          }
          List pictures = [];
          List userIds = [];
          List userNames = [];
          List dangerList = [];
          element['uploadPath'].forEach((item) {
            pictures.add({'photoData': item['path'], 'shotType': '1'});
          });
          element['persons'].forEach((item) {
            userIds.add(item['sequenceNbr']);
            userNames.add(item['bizOrgName']);
          });
          element['dangerList'].forEach((danger) {
            dangerList.add(danger.toJson());
          });
          checkItems.add({
            'id': element['inputId'],
            'inputItemId': element['itemId'],
            'inputValue': element['value'],
            'routePointItemId': element['id'],
            'checkInputShot': pictures,
            //'userId': userIds.join(','),
            //'userName': userNames.join(','),
            'accompanyUserId': userIds.join(','),
            'accompanyUserName': userNames.join(','),
            'dangerList': dangerList
          });
        });
        Map submitData = {
          'planTaskId': widget.planTaskId,
          'pointId': widget.pointId,
          'routeId': widget.routeId,
          'planTaskStatus': type, //检查项提交0，检查工单提交1
          'checkItems': checkItems,
        };
        var data = await API.supervisionPointDetailItemCommit(submitData);
        Get.back();
        if (data != null && data == '整改期限不能在检查日期之前') {
          ToastUtils.showToast('安全隐患'+data);
        }else {
          Get.back();
          ToastUtils.showToast('操作成功！');
        }
      });
    });
  }
}
