import 'dart:convert';

import 'package:amos_flutter_ui/amos_flutter_ui.dart';

import 'package:dio/dio.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';

class TaskDetail extends StatefulWidget {
   String id;
   String routePointId;
   bool isExecutor;
   TaskDetail(this.id, this.routePointId, this.isExecutor);

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

class _TaskDetailState extends State<TaskDetail> {
  Map _data = {};
  final Map _submitData = {};
  final Divider _divider = const Divider(
    height: 10,
  );


  @override
  void initState() {
    super.initState();
    dynamic map = Get.arguments;
    if(map != null){
      widget.routePointId = map['routePointId'];
      widget.id = map['id'];
      widget.isExecutor = map['isExecutor'];
    };
    _getData();
  }

  ///初始化数据
  void _getData() {
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      var data = await API.taskPointDetail({'id': widget.id, 'routePointId': widget.routePointId});
      Get.back();
      if (data != null) {
        setState(() {
          _data = data;
        });
      }
    });
  }

  ///检查检查项是否合格
  Future<bool> _checkItemIsOk(dynamic inputItemId, String inputValue) async {
    MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
    var data = await API.checkItemIsOk({'inputItemId': inputItemId, 'inputValue': inputValue});
    Get.back();
    if (data != null) {
      return data;
    }
    return true;
  }

  ///数据提交
  void _submit() {
    bool isCheckPass = true;
    _data['itemList'].asMap().forEach((index, element) {
      //校验表单
      if ('是' == element['isMust'] && (element['inputValue'] == null || element['inputValue'] == '')) {
        if (element['itemType'] == '选择') {
          var dataJson = json.decode(element['dataJson']);
          element.addAll({'value': dataJson[0]['name']});
          return;
        }
        ToastUtils.showToast('第${index + 1}项内容不能为空');
        isCheckPass = false;
        return;
      }
      //校验异常表单
      if (element['result'] == false) {
        if (element['remark'] == null || element['remark'] == '') {
          ToastUtils.showToast('第${index + 1}项问题描述不能为空');
          isCheckPass = false;
          return;
        }
        if (element['issueFiles'] == null || element['issueFiles'].length == 0) {
          ToastUtils.showToast('第${index + 1}项问题照片不能为空');
          isCheckPass = false;
          return;
        }
      }
      //校验图片
      var pictureJson = json.decode(element['pictureJson']);
      if (pictureJson is List && pictureJson.isNotEmpty) {
        var isMust = pictureJson[0]['isMust'];
        if ('是' == isMust && (element['files'] == null || element['files'].length == 0)) {
          ToastUtils.showToast('第${index + 1}项照片不能为空');
          isCheckPass = false;
          return;
        }
      }
    });
    if (!isCheckPass) {
      return;
    }
    MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
    List<Future> list = [];
    //提交图片
    _data['itemList'].forEach((element) {
      if (element['files'] != null) {
        element['files'].forEach((item) {
          list.add(_uploadImg(element, item, 1));
        });
      }
      if (element['issueFiles'] != null) {
        element['issueFiles'].forEach((item) {
          list.add(_uploadImg(element, item, 2));
        });
      }
    });
    //提交数据
    Future.wait(list).then((value) async {
      //添加基础数据
      _submitData['planTaskId'] = _data['facility']['planTaskId'];
      _submitData['pointId'] = _data['facility']['pointId'];
      //添加选项数据
      List checkItems = [];

      _data['itemList'].forEach((element) {
        var pictureJson = json.decode(element['pictureJson']);
        Map checkItem = {};
        checkItem.addAll({
          'inputItemId': element['id'],
          'inputValue': element['inputValue'],
          'remark': element['remark'],
          'routePointItemId': element['routePointItemId']
        });
        if (element['uploadPath'] != null) {
          List uploadPath = [];
          element['uploadPath'].forEach((item) {
            Map map = {'fileUrl': item['path'], 'shotType': item['type']};
            if (item['type'] == 1 && pictureJson.isNotEmpty) {
              map.addAll({'photoConfKey': pictureJson[0]['photoConfKey']});
            }
            uploadPath.add(map);
          });
          checkItem.addAll({'checkInputShot': uploadPath});
        }
        checkItems.add(checkItem);
      });

      _submitData.addAll({'checkItems': checkItems});
      print(_submitData);
      var data = await API.checkSaveRecord(_submitData);
      if (data != null) {
        Get.back();
      }
    }).whenComplete(() {
      Get.back();
    });
  }

  ///图片上传
  Future<void> _uploadImg(element, item, type) async {
    var name = item.file.path.substring(item.file.path.lastIndexOf('/') + 1, item.file.path.length);
    var formData = await MultipartFile.fromFile(item.file.path, filename: name);
    var fileUploadResult = await API.fileStorage(FormData.fromMap({'file': formData}));
    if (element['uploadPath'] == null) {
      List uploadPath = [];
      element.addAll({'uploadPath': uploadPath});
    }
    element['uploadPath'].add({'path': fileUploadResult.keys.first, 'type': type});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text((_data['facility'] ?? {})['name'] ?? ''),
      ),
      body: SingleChildScrollView(
        child: GestureDetector(
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: Column(
            children: [
              Card(
                child: Padding(
                  padding: const EdgeInsets.all(15.0),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          const Text('设施编号：'),
                          Text((_data['facility'] ?? {})['pointNo'] ?? ''),
                        ],
                      ),
                      const SizedBox(
                        height: 8,
                      ),
                      Row(
                        children: [
                          const Text('维保设施：'),
                          Text((_data['facility'] ?? {})['name'] ?? ''),
                        ],
                      ),
                      const SizedBox(
                        height: 8,
                      ),
                      Row(
                        children: [
                          const Text('设施位置：'),
                          Text((_data['facility'] ?? {})['position'] ?? ''),
                        ],
                      ),
                      const SizedBox(
                        height: 8,
                      ),
                      Row(
                        children: [
                          const Expanded(child: Text('风险辨识与管控措施：')),
                          InkWell(
                            child: const Text(
                              '查看',
                              style: TextStyle(color: Colors.blue),
                            ),
                            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('确认'))
                                  ],
                                ),
                              );
                            },
                          ),
                        ],
                      )
                    ],
                  ),
                ),
              ),
              Card(
                child: Padding(
                  padding: const EdgeInsets.all(15.0),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          Text(
                            (_data['facility'] ?? {})['name'] ?? '',
                            style: const TextStyle(fontWeight: FontWeight.bold),
                          ),
                        ],
                      ),
                      const SizedBox(height: 10),
                      _data['itemList'] != null
                          ? Column(
                              children: _data['itemList']
                                  .asMap()
                                  .map((index, element) {
                                    if (element['itemType'] == '选择') {
                                      return MapEntry(index, _buildCheckItem(context, element, index));
                                    }
                                    if (element['itemType'] == '文本') {
                                      return MapEntry(index, _buildTextItem(context, element, index));
                                    }
                                    if (element['itemType'] == '数字') {
                                      return MapEntry(index, _buildNumItem(context, element, index));
                                    }
                                  })
                                  .values
                                  .cast<Widget>()
                                  .toList())
                          : Container()
                    ],
                  ),
                ),
              ),
              widget.isExecutor
                  ? Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Row(
                        children: [
                          Expanded(
                            child: FlatButton(
                                onPressed: () {
                                  _submit();
                                },
                                color: Colors.blueAccent,
                                child: const Text(
                                  '保存',
                                  style: TextStyle(color: Colors.white),
                                )),
                          )
                        ],
                      ),
                    )
                  : Container()
            ],
          ),
        ),
      ),
    );
  }

  ///选择项
  Widget _buildCheckItem(BuildContext context, dynamic data, int index) {
    var dataJson = json.decode(data['dataJson']);
    return Padding(
      padding: const EdgeInsets.only(top: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildTitleRow(context, data, index),
          Row(
              children: dataJson
                  .map((element) {
                    return Expanded(
                      child: Row(
                        children: [
                          Radio(
                            value: element['name'],
                            onChanged: (value) async {
                              setState(() {
                                data.addAll({'value': value});
                              });
                              bool result = await _checkItemIsOk((data['id'] ?? '').toString(), value);
                              data.addAll({'result': result});
                              setState(() {});
                            },
                            groupValue: data['value'] ?? (element['isChecked'] == '是' ? element['name'] : data['value']),
                          ),
                          Text(element['name'])
                        ],
                      ),
                    );
                  })
                  .cast<Widget>()
                  .toList()),
          _buildImageColumn(data),
          (data['result'] ?? true) ? Container() : _buildFormItem(data),
          _divider
        ],
      ),
    );
  }

  ///数值项
  Widget _buildNumItem(BuildContext context, dynamic data, int index) {
    FocusNode focusNode = FocusNode();
    focusNode.addListener(() async {
      if (!focusNode.hasFocus) {
        bool result = await _checkItemIsOk(data['id'], data['value']);
        data.addAll({'result': result});
        setState(() {});
      }
    });
    data.addAll({'focusNode': focusNode});
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildTitleRow(context, data, index),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 5),
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  focusNode: focusNode,
                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(
                    filled: true,
                    fillColor: FormStyles.CONTENT_COLOR,
                    border: InputBorder.none,
                  ),
                  style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                  onChanged: (value) {
                    data.addAll({'value': value});
                  },
                ),
              ),
            ],
          ),
        ),
        _buildImageColumn(data),
        (data['result'] ?? true) ? Container() : _buildFormItem(data),
        _divider
      ],
    );
  }

  ///文本项
  Widget _buildTextItem(BuildContext context, dynamic data, int index) {
    TextEditingController _textEditingController = new TextEditingController();
    print(data['inputValue']);
    String textStr =data['inputValue'];
    _textEditingController.value = TextEditingValue(
        text: textStr,
        selection: TextSelection.fromPosition(
            TextPosition(
                affinity: TextAffinity.downstream,
                offset: textStr.length)));
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildTitleRow(context, data, index),
        TextField(
          // controller: new TextEditingController(text: data.inputValue),
          controller:_textEditingController,
          decoration: InputDecoration(
            filled: true,
            fillColor: FormStyles.CONTENT_COLOR,
            border: InputBorder.none,
          ),
          style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
          onChanged: (value) {
            data.addAll({'inputValue': value});
          },
        ),
        _buildImageColumn(data),
        _divider
      ],
    );
  }

  ///子项标题
  Widget _buildTitleRow(BuildContext context, dynamic data, int index) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 10),
      child: Row(
        children: [
          Transform.translate(
              offset: const Offset(0, 2),
              child: Text(
                data['isMust'] == '是' ? '*' : ' ',
                style: const TextStyle(color: Colors.red),
              )),
          Text('${index + 1}.'),
          Expanded(child: Text(data['inputName'] ?? '')),
          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(
                          data['testRequirement'] ?? '',
                          style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                        ),
                        const SizedBox(
                          height: 10,
                        ),
                      ],
                    ),
                  ),
                  actions: [
                    FlatButton(
                        onPressed: () {
                          Get.back();
                        },
                        child: const Text('确认'))
                  ],
                ),
              );
            },
            child: const Icon(
              Icons.info_outline,
              color: Colors.grey,
            ),
          )
        ],
      ),
    );
  }

  ///外部照片
  Column _buildImageColumn(data) {
    if (data['files'] == null) {
      data.addAll({'files': <ChooseFileInfo>[]});
    }
    var pictureJson = json.decode(data['pictureJson']);
    return Column(
      children: (pictureJson != null && pictureJson.length > 0)
          ? [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const SizedBox(
                    height: 8,
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 5),
                    child: Text(pictureJson[0]['name']),
                  ),
                  const SizedBox(
                    height: 5,
                  ),
                  ImagePickerAndRemove(
                    data['files'],
                    readOnly: false,
                    maxLength: int.parse(pictureJson[0]['picNumber'] ?? '3'),
                  ),
                  const SizedBox(
                    height: 10,
                  ),
                ],
              )
            ]
          : [],
    );
  }

  ///异常表单
  Widget _buildFormItem(dynamic data) {
    if (data['issueFiles'] == null) {
      List<ChooseFileInfo> _files = [];
      data.addAll({'issueFiles': _files});
    }
    return AnimatedContainer(
      duration: const Duration(milliseconds: 200),
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Padding(
              padding: EdgeInsets.only(left: 5),
              child: Text(
                '问题描述',
                style: TextStyle(color: Colors.red),
              ),
            ),
            const SizedBox(
              height: 8,
            ),
            TextField(
              maxLines: 3,
              maxLengthEnforced: false,
              decoration: InputDecoration(border: InputBorder.none, filled: true, fillColor: FormStyles.CONTENT_COLOR),
              onChanged: (val) {
                data.addAll({'remark': val});
              },
            ),
            const SizedBox(
              height: 8,
            ),
            const Padding(
              padding: EdgeInsets.only(left: 5.0),
              child: Text(
                '问题照片',
                style: TextStyle(color: Colors.red),
              ),
            ),
            const SizedBox(
              height: 3,
            ),
            ImagePickerAndRemove(
              data['issueFiles'],
              readOnly: false,
              maxLength: 3,
            ),
          ],
        ),
      ),
    );
  }
}
