import 'dart:convert';
import 'dart:io';
import 'package:amos_flutter_ui/common/card.dart';
import 'package:amos_flutter_ui/message/flutter_toast.dart';
import 'package:amos_flutter_ui/message/message_box.dart';
import 'package:amos_flutter_ui/styles/form_styles.dart';
import 'package:amos_iot_login_tpl/const/global_config.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.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/planCheck/choose_location.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

///@Description     隐患审核详情
///@author          helinlin
///@create          2021-09-27 17:05
class HiddenDangerAuditDetail extends StatefulWidget {
  ///1,审核 2,复查
  int type;
  String dangerId;

  HiddenDangerAuditDetail(this.dangerId, this.type);

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

class HiddenDangerAuditDetailState extends State<HiddenDangerAuditDetail> {
  //现场确认状态
  static const String DANGER_STATE_CONFIRM1 = 'dangerSubmit';
  static const String DANGER_STATE_CONFIRM2 = 'onSiteConfirm';
  bool isPass = true;
  String remark;
  String imageUrl = '';
  Map danger = {'bizInfo': {}, 'records': []};
  List<ChooseFileInfo> pictures = [];

  @override
  void initState() {
    super.initState();
    dynamic map = Get.arguments;
    if (map != null && map['type'] != null) {
      widget.dangerId = map['id'];
      widget.type = int.parse(map['type']);
    }
    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imageUrl = value;
      });
    });
    getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('隐患详情'),
      ),
      body: SingleChildScrollView(
        child: GestureDetector(
          onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
          child: Column(
            children: [
              Card(
                child: Padding(
                  padding: const EdgeInsets.all(15.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      buildRow('编        号：', danger['businessKey']),
                      buildRow('隐患描述：', danger['dangerName']),
                      buildRow('隐患级别：', danger['dangerLevelName']),
                      Padding(
                        padding: const EdgeInsets.only(bottom: 8.0),
                        child: Row(
                          children: [
                            const Expanded(child: Text('隐患位置')),
                            Expanded(
                                flex: 2,
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: Text(
                                        (danger['dangerPosition'] ?? '').toString(),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                    GestureDetector(
                                      onTap: () => openMap(),
                                      child: const Icon(
                                        Icons.location_on_outlined,
                                        color: Colors.green,
                                      ),
                                    )
                                  ],
                                )),
                          ],
                        ),
                      ),
                      buildRow('治理方式：', danger['reformTypeName']),
                      buildRow('提交时间：', (danger['createDate'] ?? '').toString()),
                      buildRow('检  查  人：', danger['bizInfo']['checkUserName']),
                      buildRow('陪同检查人：', danger['bizInfo']['accompanyingUserName']),
                      buildRow('隐患照片：', ''),
                      ImagePickerAndRemove(
                        danger['photoUrl'] ?? [],
                        readOnly: true,
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      CollapseCard(
                        defaultExpanded: false,
                        title: const Text(
                          '记录',
                          style: TextStyle(fontSize: CoreStyles.textSizeSmall),
                        ),
                        children: danger['records'].map((item) => buildRecords(item)).cast<Widget>().toList(),
                      ),
                    ],
                  ),
                ),
              ),
              widget.type > 0
                  ? Card(
                      child: Padding(
                        padding: const EdgeInsets.all(15.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            //现场确认只能通过，隐藏不通过选项
                            (danger['dangerState'] != DANGER_STATE_CONFIRM1 && danger['dangerState'] != DANGER_STATE_CONFIRM2)
                                ? Column(
                                    children: [
                                      Row(
                                        children: [
                                          const Text(
                                            '*',
                                            style: TextStyle(color: Colors.red),
                                          ),
                                          Text(widget.type == 1 ? '审核结果' : '复查结果')
                                        ],
                                      ),
                                      Row(
                                        children: [
                                          Radio(
                                            value: true,
                                            groupValue: isPass,
                                            onChanged: radioOnClick,
                                            activeColor: Theme.of(context).primaryColor,
                                          ),
                                          const Text('通过'),
                                          // Row(
                                          //   children: [
                                          //     Radio(
                                          //       value: false,
                                          //       groupValue: isPass,
                                          //       onChanged: radioOnClick,
                                          //       activeColor: Theme.of(context).primaryColor,
                                          //     ),
                                          //     const Text('不通过')
                                          //   ],
                                          // )
                                        ],
                                      ),
                                    ],
                                  )
                                : Container(),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(widget.type == 1 ? '审核说明' : '复查说明'),
                                const SizedBox(
                                  height: 10,
                                ),
                                TextField(
                                  maxLines: 3,
                                  style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                                  decoration: InputDecoration(
                                    filled: true,
                                    fillColor: FormStyles.CONTENT_COLOR,
                                    border: InputBorder.none,
                                  ),
                                  onChanged: (val) => remark = val,
                                ),
                                ImagePickerAndRemove(
                                  pictures,
                                  readOnly: false,
                                ),
                              ],
                            ),
                            const SizedBox(
                              height: 30,
                            ),
                            Row(
                              children: [
                                Expanded(
                                    child: FlatButton(
                                  onPressed: submit,
                                  child: const Text(
                                    '提交',
                                    style: TextStyle(color: Colors.white),
                                  ),
                                  color: Theme.of(context).primaryColor,
                                )),
                              ],
                            ),
                            const SizedBox(
                              height: 10,
                            ),
                          ],
                        ),
                      ),
                    )
                  : Container()
            ],
          ),
        ),
      ),
    );
  }

  Widget buildRecords(item) => Padding(
        padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 5),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            buildRow('流程:', item['flowTaskName'], color: Theme.of(context).primaryColor),
            buildRow('结果:', item['executeState'] == 3 ? '拒绝' : '通过',
                color: item['executeState'] == 3 ? Colors.red : Colors.green),
            buildRow('说明:', item['flowData']['remark'] ?? ''),
            buildRow('时间:', item['executeTime']),
            buildRow('操作人:', item['executeUserName']),
            ...(item['actionFlag'] == 'governFileSubmit' && item['flowData']['rectifyDocs'] != null)
                ? item['flowData']['rectifyDocs']
                    .map((doc) => buildRow('附件:', doc['name'] ?? '', color: Colors.blue, onClick: () => downLoadDoc(doc['url'])))
                    .cast<Widget>()
                    .toList()
                : [Container()],
            buildRow('照片：', ''),
            ImagePickerAndRemove(
              item['flowData']['pictures'] ?? [],
              readOnly: true,
            ),
            Divider(
              height: 10,
              color: Theme.of(context).primaryColor,
            )
          ],
        ),
      );

  Widget buildRow(String key, String value, {Color color = Colors.black, Function onClick}) => Padding(
        padding: const EdgeInsets.only(bottom: 8.0),
        child: Row(
          children: [
            Expanded(
                child: Text(
              (key ?? '').toString(),
            )),
            Expanded(
                flex: 2,
                child: InkWell(
                  onTap: onClick,
                  child: Text(
                    (value ?? '').toString(),
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: color),
                  ),
                ))
          ],
        ),
      );

  void radioOnClick(val) {
    setState(() {
      isPass = val;
    });
  }

  ///附件下载
  Future<void> downLoadDoc(String docUrl) async {
    String docAddress = imageUrl + docUrl;
    //检查是否有读写权限
    bool status = await Permission.storage.isGranted;
    if (!status) {
      bool result = await Permission.storage.request().isGranted;
      if (!result) {
        ToastUtils.showToast('拒绝授权，将无法下载文件！');
        return;
      }
    }
    //获取下载目录（Android将附件存放在外置存储卡的根目录位置）
    Directory root = await getExternalStorageDirectory();
    //String docPath = root.path + '/amos_docs';
    /* ProgressDialog progressDialog = ProgressDialog(
      context,
      type: ProgressDialogType.Download,
      isDismissible: true,
      showLogs: true,
    );
    progressDialog.show();*/
    String taskId;
    FlutterDownloader.registerCallback((id, status, progress) {
      print('Download task ($id) is in status ($status) and process ($progress)');
      if (status == DownloadTaskStatus.running) {
        //progressDialog.update(progress: progress.toDouble());
      }
      if (status == DownloadTaskStatus.complete) {
        //progressDialog.hide();
        FlutterDownloader.open(taskId: taskId);
      }
      if (status == DownloadTaskStatus.failed) {
        //progressDialog.hide();
        ToastUtils.showToast('下载异常，请重新尝试！');
      }
    });
    taskId = await FlutterDownloader.enqueue(url: docAddress, savedDir: '/storage/emulated/0');
    ToastUtils.showToast('已开始下载，请在系统通知栏查看！');
  }

  void getData() {
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      var data = await API.dangerDetail(widget.dangerId);
      Get.back();
      if (data != null) {
        setState(() {
          //隐患记录照片处理
          data['photoUrl'] = (data['photoUrl'] ?? [])
              .map((path) => ChooseFileInfo(null, isPhoto: true, url: imageUrl + path))
              .toList()
              .cast<ChooseFileInfo>();
          //审核记录照片处理
          data['records'].forEach((item) {
            dynamic flowData = json.decode(item['flowJson'] ?? '{}');
            //APP上传照片处理
            if (flowData['pictures'] != null) {
              flowData['pictures'] = flowData['pictures']
                  .map((picture) => ChooseFileInfo(null, isPhoto: true, url: imageUrl + picture))
                  .toList()
                  .cast<ChooseFileInfo>();
            }
            //web上传照片处理
            if (flowData['rectifyImages'] != null) {
              flowData['pictures'] = flowData['rectifyImages']
                  .map((picture) => ChooseFileInfo(null, isPhoto: true, url: imageUrl + picture['url']))
                  .toList()
                  .cast<ChooseFileInfo>();
            }
            item['flowData'] = flowData;
          });
          danger.addAll(data);
        });
      }
    });
  }

  Future<void> submit() async {
    if (isPass == null) {
      ToastUtils.showToast('结果不能为空！');
      return;
    }
    MsgBox.showProgressDialog(context);
    List<Future> tasks = [];
    List<String> uploadPath = [];
    pictures.forEach((element) {
      tasks.add(API.uploadImg(element, (path) {
        uploadPath.add(path);
      }));
    });
    Future.wait(tasks).then((value) async {
      var data = await API.dangerAudit(isPass ? 2 : 3, {
        'id': widget.dangerId,
        'flowJson': {'remark': remark, 'pictures': uploadPath}
      });
      Get.back();
      if (data != null) {
        ToastUtils.showToast('提交成功！');
        Get.back();
      }
    }).catchError((err) => ToastUtils.showToast(err.toString()));
  }

  void openMap() {
    if (danger['longitude'] == null || danger['longitude'] == '' || danger['latitude'] == null || danger['latitude'] == '') {
      ToastUtils.showToast('未上传经纬度信息！');
      return;
    }
    //CallMapUtil.callAMap(danger['longitude'], danger['latitude']);
    Get.to(ChooseLocation(danger['longitude'], danger['latitude']));
  }
}
