import 'dart:convert';
import 'dart:io';

import 'package:base/consts/color.dart';
import 'package:base/view/ImageViewPage.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../model/Hidden_Danger/hidden_danger_model.dart';
import '../../services/HiddenDanger.dart';
import '../../view/CheckExecute/ImageList.dart';
import '../../view/hidedanger_manage/hidden_danger_flowRecord.dart';
import '../../view/hidedanger_manage/hidden_danger_found.dart';
import '../../view/hidedanger_manage/hidden_danger_processed_rectification_measures_show.dart';
import '../../view/hidedanger_manage/hidden_danger_review.dart';

class HiddenDangerProcessedDetailsChecked extends StatefulWidget {
  final int dangerId;
  final int state;
  final String taskId;

  const HiddenDangerProcessedDetailsChecked(this.dangerId, this.taskId, {this.state});

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

class _HiddenDangerProcessedDetailsChecked extends State<HiddenDangerProcessedDetailsChecked> {
  TextEditingController remark = TextEditingController();

  bool get wantKeepAlive => true;

  bool isAnimating = false;

  bool canOperate = true;
  String myUserId;
  List<String> recMeasures = [];
  List<File> imageList;
  HideDangerInfoModel initData;
  HideDanger hideDanger = HideDanger();

  String theme = '';
  String imageUrl = '';

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

  Future<void> getInitInfo() async {
    await SharedPreferences.getInstance().then((data) {
      if (data != null) {
        setState(() {
          theme = data.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
          imageUrl = data.getString('imageUrl') ?? '';
        });
      }
    }).then((data) {
      loadData();
    });
  }

  Future<void> loadData() async {
    setState(() {
      isAnimating = true;
    });
    await getHiddenDangerModel(context,widget.dangerId, widget.taskId).then((data) {
      if (data != null) {
        setState(() {
          initData = data;
          List<String> photos = [];
          (initData.photoUrls ?? []).forEach((item) {
            photos.add(imageUrl + item);
          });
          initData.photoUrls = photos;
          initData.currentUserCanExcute = initData.currentUserCanExcute == null ? false : true;
          if (widget.state != null && initData.dangerState != null && widget.state != initData.dangerState) {
            HiddenDangerReview.goToPage(initData.dangerState, initData.dangerId, widget.taskId, context);
          }

          isAnimating = false;
        });
      }
    });
  }

  Future<void> _upDateImg(List<File> att) async {
    setState(() {
      isAnimating = true;
      canOperate = false;
    });
    // var bizCode = "latent_danger_recheck";
    await updataImg(att).then((data) {
      setState(() {
        ///保存文件路径
        if (data.success) {
          hideDanger.photoUrls = data.message;
          HiddenDangerFound.popUpMsg('图片上传成功!');
        } else {
          HiddenDangerFound.popUpMsg(data.message);
        }
        isAnimating = false;
        canOperate = true;
      });
    }).catchError(() {
      isAnimating = false;
      canOperate = true;
      setState(() {});
    });
  }

  Future<void> _saveRecheckResult(HideDanger hd, radio) async {
    setState(() {
      isAnimating = true;
      canOperate = false;
    });
    var result = 0;
    if (radio == 1) {
      //常规处理
      result = 13;
    } else {
      //安措计划
      result = 14;
    }
    var jsonFlow = {'photoUrls': hd.photoUrls};

    await saveReviewResult(hd, result, initData.currentFlowRecordId, jsonFlow, this.widget.taskId, this.widget.dangerId)
        .then((data) {
      setState(() {
        if (data.success) {
          HiddenDangerFound.popUpMsg(data.message);

          Navigator.pop(context);
        } else {
          HiddenDangerFound.popUpMsg(data.message);
        }
        isAnimating = false;
        canOperate = true;
      });
    });
  }

  bool _checkNeed() {
    if (radioValue == 2 && hideDanger.remark.text == '') {
      HiddenDangerFound.popUpMsg('验收不合格！请填写备注信息！');
      return false;
    }
    return true;
  }

  // Default placeholder text
  var radioValue = 1;

  @override
  Widget build(BuildContext context) {
    ///null == routeList || routeList.length <= 0
    if (initData == null || initData.dangerId == null) {
      return Scaffold(
          appBar: AppBar(
        title: const Text(
          '隐患验证',
        ),
        actions: <Widget>[
          Align(
              child: Padding(
            padding: const EdgeInsets.only(right: 8),
            child: GestureDetector(
              child: const Icon(
                Icons.save,
                size: 25,
              ),
            ),
          ))
        ],
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
      ));
    }

    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '隐患验证',
        ),
        actions: <Widget>[
          Align(
              child: Padding(
            padding: const EdgeInsets.only(right: 8),
            child: GestureDetector(
              onTap: () {
                if (canOperate) {
                  if (_checkNeed()) _saveRecheckResult(hideDanger, radioValue);
                } else {
                  HiddenDangerFound.popUpMsg('正在执行操作！请稍等...');
                }
              },
              child: const Icon(
                Icons.save,
                size: 25,
              ),
            ),
          ))
        ],
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
      ),
      body: ModalProgressHUD(
        child: SingleChildScrollView(
          child: Container(
            color: Colors.white,
            child: Column(
              children: <Widget>[
                initData.dangerType == 2
                    ? Column(
                        children: <Widget>[
                          Row(
                            children: <Widget>[
                              Expanded(
                                flex: 5,
                                child: Container(
                                  padding: const EdgeInsets.only(left: 10, top: 10),
                                  height: 50,
                                  child: const Text(
                                    "点名称",
                                    style: TextStyle(color: Colors.black, fontSize: 18),
                                  ),
                                ),
                              ),
                              Expanded(
                                flex: 10,
                                child: Text(initData.riskInfo == null ? '-' : initData.riskInfo.pointName),
                              )
                            ],
                          ),
                          //点编号
                          Row(
                            children: <Widget>[
                              Expanded(
                                flex: 5,
                                child: Container(
                                  padding: const EdgeInsets.only(left: 10, top: 10),
                                  height: 50,
                                  child: const Text(
                                    "点编号",
                                    style: TextStyle(color: Colors.black, fontSize: 18),
                                  ),
                                ),
                              ),
                              Expanded(
                                flex: 10,
                                child: Text(initData.riskInfo == null ? "-" : initData.riskInfo.pointNo),
                              )
                            ],
                          ),

                          //分割线
                          //所属部门/车间
                          Row(
                            children: <Widget>[
                              Expanded(
                                flex: 5,
                                child: Container(
                                  padding: const EdgeInsets.only(left: 10, top: 10),
                                  width: 150,
                                  height: 50,
                                  child: const Text(
                                    "等级",
                                    style: TextStyle(color: Colors.black, fontSize: 18),
                                  ),
                                ),
                              ),
                              Expanded(
                                flex: 10,
                                child: Text("${initData.riskInfo != null ? initData.riskInfo.pointLevel : "--"}"),
                              )
                            ],
                          ),
                          //分割线
                          Container(
                            color: Colors.grey[100],
                            height: 10,
                          ),

                          Row(
                            children: <Widget>[
                              Container(
                                padding: const EdgeInsets.only(left: 10, top: 10),
                                height: 50,
                                child: const Text(
                                  '检查依据',
                                  style: TextStyle(
                                    fontWeight: FontWeight.w500,
                                    fontSize: 18,
                                  ),
                                ),
                              ),
                            ],
                          ),

                          initData.riskInfo != null && initData.riskInfo.basis != null
                              ? Column(
                                  children: initData.riskInfo.basis.map((base) {
                                    return Container(
                                      height: 30,
                                      decoration: const BoxDecoration(
                                          border: Border(bottom: BorderSide(color: Color.fromRGBO(244, 244, 244, 1)))),
                                      width: MediaQuery.of(context).size.width,
                                      margin: const EdgeInsets.only(left: 30),
                                      child: Text(
                                        json.decode(base)['name'].toString(),
                                        style: const TextStyle(color: Colors.black, fontSize: 16),
                                      ),
                                    );
                                  }).toList(),
                                )
                              : Container(),
                          Container(
                            color: Colors.grey[100],
                            height: 10,
                          ),
                        ],
                      )
                    : const Text(""),

                ///隐患名称
                Row(
                  children: <Widget>[
                    Expanded(
                      flex: 5,
                      child: Container(
                        padding: const EdgeInsets.only(left: 10, top: 10),
                        width: 150,
                        height: 50,
                        child: Row(
                          children: const <Widget>[
                            Expanded(
                              child: Text(
                                '隐患名称',
                                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 18),
                              ),
                              flex: 19,
                            ),
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 10,
                      child: Container(
                        child: Text(initData.dangerName ?? ""),
                        padding: const EdgeInsets.only(top: 5, right: 10),
                      ),
                    ),
                  ],
                ),

                ///隐患地点
                initData.position == null
                    ? Container()
                    : Row(
                        children: <Widget>[
                          Expanded(
                            flex: 5,
                            child: Container(
                              padding: const EdgeInsets.only(left: 10, top: 10),
                              width: 150,
                              height: 50,
                              child: Row(
                                children: const <Widget>[
                                  Expanded(
                                    child: Text(
                                      '隐患地点',
                                      style: TextStyle(fontWeight: FontWeight.w500, fontSize: 18),
                                    ),
                                    flex: 19,
                                  ),
                                ],
                              ),
                            ),
                          ),
                          Expanded(
                            flex: 10,
                            child: Text(initData.position ?? "-"),
                          ),
                        ],
                      ),

                ///隐患等级
                Row(
                  children: <Widget>[
                    Expanded(
                      flex: 5,
                      child: Container(
                        padding: const EdgeInsets.only(left: 10, top: 10),
                        width: 150,
                        height: 50,
                        child: Row(
                          children: const <Widget>[
                            Expanded(
                              child: Text(
                                '隐患等级',
                                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 18),
                              ),
                              flex: 19,
                            ),
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 10,
                      child: Text(
                        initData.levelDesc ?? '',
                        style: TextStyle(color: initData.level == 1 ? Colors.orange : Colors.red),
                      ),
                    ),
                  ],
                ),

                Container(
                  child: GestureDetector(
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 3,
                          child: Container(
                            padding: const EdgeInsets.only(left: 10, top: 10),
                            height: 50,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: const <Widget>[
                                Expanded(
                                  child: Text(
                                    '现场照片',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(fontWeight: FontWeight.w500, fontSize: 18),
                                  ),
                                  flex: 9,
                                ),
                              ],
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 7,
                          child: Container(
                            child: Wrap(
                                direction: Axis.horizontal,
                                spacing: -25.0, // 主轴(水平)方向间距
                                // runSpacing: 20.0, // 纵轴（垂直）方向间距
                                alignment: WrapAlignment.end, //沿主轴方向居中
                                children: initData.photoUrls != null
                                    ? initData.photoUrls.map((f) {
                                        return Column(
                                          mainAxisAlignment: MainAxisAlignment.end,
                                          children: <Widget>[
                                            Container(
                                              width: 40,
                                              height: 40,
                                              //  margin: EdgeInsets.only(right: 5),
                                              decoration: BoxDecoration(
                                                  color: Colors.transparent,
                                                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                                                  image: DecorationImage(image: NetworkImage(f), fit: BoxFit.cover)),
                                            ),
                                          ],
                                        );
                                      }).toList()
                                    : List()),
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: Icon(
                              Icons.keyboard_arrow_right,
                              color: Theme.of(context).primaryColor,
                              size: 22,
                            ),
                          ),
                        ),
                      ],
                    ),
                    onTap: () {
                      Navigator.push(context, MaterialPageRoute(builder: (context) {
                        return PhotoViewPage(initData.photoUrls);
                      }));
                    },
                  ),
                ),

                Container(
                  color: Colors.grey[100],
                  height: 10,
                ),

                Container(
                  color: Colors.grey[100],
                  height: 10,
                ),

                //执行日志
                Container(
                  padding: const EdgeInsets.only(left: 15),
                  width: MediaQuery.of(context).size.width,
                  height: 55,
                  child: GestureDetector(
                    child: Row(
                      children: <Widget>[
                        const Expanded(
                          child: Text('执行日志',
                              textAlign: TextAlign.left,
                              style: TextStyle(
                                fontWeight: FontWeight.w500,
                                fontSize: 19,
                              )),
                          flex: 9,
                        ),
                        Expanded(
                          child: Icon(
                            Icons.keyboard_arrow_right,
                            color: Theme.of(context).primaryColor,
                          ),
                          flex: 1,
                        ),
                      ],
                    ),
                    onTap: () {
                      Navigator.push(context, MaterialPageRoute(builder: (context) {
                        return HidenDangerFlowRecord(initData.dangerId);
                      }));
                    },
                  ),
                ),
                Container(
                  color: Colors.grey[100],
                  height: 10,
                ),
                Row(
                  children: <Widget>[
                    Expanded(
                      flex: 5,
                      child: Container(
                        padding: const EdgeInsets.only(left: 10, top: 10),
                        width: 150,
                        height: 50,
                        child: Row(
                          children: const <Widget>[
                            Expanded(
                              child: Text(
                                '治理日期',
                                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 18),
                              ),
                              flex: 19,
                            ),
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 10,
                      child: Text(
                        DateFormat('yyyy-MM-dd').format(DateTime.parse(
                            initData.reformLimitDate == null ? DateTime.now().toString() : initData.reformLimitDate.toString())),
                        style: const TextStyle(color: Colors.black),
                      ),
                    ),
                  ],
                ),

                //治理方式
                Row(
                  children: <Widget>[
                    Expanded(
                      flex: 5,
                      child: Container(
                        padding: const EdgeInsets.only(left: 10, top: 10),
                        width: 150,
                        height: 50,
                        child: Row(
                          children: const <Widget>[
                            Expanded(
                              child: Text(
                                '治理方式',
                                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 18),
                              ),
                              flex: 19,
                            ),
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 10,
                      child: Text(
                        initData.reformTypeDesc ?? '-',
                        style: const TextStyle(color: Colors.black),
                      ),
                    ),
                  ],
                ),

                //治理措施
                Container(
                  padding: const EdgeInsets.only(left: 15),
                  width: MediaQuery.of(context).size.width,
                  height: 55,
                  child: GestureDetector(
                    child: Row(
                      children: <Widget>[
                        const Expanded(
                          child: Text("治理措施",
                              textAlign: TextAlign.left,
                              style: TextStyle(
                                fontWeight: FontWeight.w500,
                                fontSize: 19,
                              )),
                          flex: 9,
                        ),
                        Expanded(
                          child: Icon(
                            Icons.keyboard_arrow_right,
                            color: Theme.of(context).primaryColor,
                          ),
                          flex: 1,
                        ),
                      ],
                    ),
                    onTap: () {
                      Navigator.push(context, MaterialPageRoute(builder: (context) {
                        return HiddenDangerProcessedRectificationMeasuresShow(initData);
                      }));
                    },
                  ),
                ),

                Container(
                  color: Colors.grey[100],
                  height: 10,
                ),

                ///验收结果
                Row(
                  children: <Widget>[
                    Expanded(
                      flex: 5,
                      child: Container(
                        padding: EdgeInsets.only(left: 10, top: 10),
                        width: 150,
                        height: 50,
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              child: Text(
                                "*",
                                style: TextStyle(color: Colors.red),
                              ),
                              flex: 0,
                            ),
                            Expanded(
                              child: Text(
                                "验证结果",
                                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 18),
                              ),
                              flex: 19,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                Container(
                    child: Column(
                  children: <Widget>[
                    Container(
                        padding: EdgeInsets.only(
                          left: 0,
                          top: 5,
                        ),
                        width: MediaQuery.of(context).size.width,
                        height: 50,
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              child: Row(
                                children: <Widget>[
                                  Expanded(
                                    flex: 4,
                                    child: RadioListTile(
                                        title: Text("合格"),
                                        value: 1,
                                        groupValue: radioValue,
                                        onChanged: (value) {
                                          setState(() {
                                            print(value);
                                            radioValue = value;
                                          });
                                        }),
                                  ),
                                  Expanded(
                                    flex: 4,
                                    child: RadioListTile(
                                        title: Text("不合格"),
                                        value: 2,
                                        groupValue: radioValue,
                                        onChanged: (value) {
                                          setState(() {
                                            print(value);
                                            radioValue = value;
                                          });
                                        }),
                                  ),
                                ],
                              ),
                              flex: 3,
                            ),
                          ],
                        )),
                  ],
                )),
                Container(
                  color: Colors.grey[100],
                  height: 10,
                ),
                //拍照取证
                Container(
                  child: GestureDetector(
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 3,
                          child: Container(
                            padding: const EdgeInsets.only(left: 18),
                            height: 50,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: const <Widget>[
                                Expanded(
                                  child: Text(
                                    "拍照取证",
                                    textAlign: TextAlign.left,
                                    style: TextStyle(fontWeight: FontWeight.w500, fontSize: 18),
                                  ),
                                  flex: 9,
                                ),
                              ],
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 7,
                          child: Container(
                            child: Wrap(
                                spacing: -25.0, // 主轴(水平)方向间距
                                // runSpacing: 20.0, // 纵轴（垂直）方向间距
                                alignment: WrapAlignment.end, //沿主轴方向居中
                                children: hideDanger.photoUrls != ""
                                    ? hideDanger.photoUrls.split(",").map((f) {
                                        return Row(
                                          mainAxisAlignment: MainAxisAlignment.end,
                                          children: <Widget>[
                                            Container(
                                              width: 40,
                                              height: 40,
                                              //  margin: EdgeInsets.only(right: 5),
                                              decoration: BoxDecoration(
                                                  color: Colors.transparent,
                                                  borderRadius: BorderRadius.all(Radius.circular(20.0)),
                                                  image: DecorationImage(image: NetworkImage(f), fit: BoxFit.cover)),
                                            ),
                                          ],
                                        );
                                      }).toList()
                                    : List()),
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: Icon(
                              Icons.photo_camera,
                              color: Theme.of(context).primaryColor,
                              size: 22,
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: Icon(
                              Icons.keyboard_arrow_right,
                              color: Theme.of(context).primaryColor,
                              size: 22,
                            ),
                          ),
                        ),
                      ],
                    ),
                    onTap: () {
                      Navigator.push(context, MaterialPageRoute(builder: (context) {
                        return ImageList(imageList);
                      })).then((v) {
                        if (v != null) {
                          setState(() {
                            imageList = v;
                            _upDateImg(imageList);
                          });
                        }
                      });
                    },
                  ),
                ),
                Container(
                  color: Colors.grey[100],
                  height: 10,
                ),

                ///备注
                Row(
                  children: <Widget>[
                    Expanded(
                      flex: 10,
                      child: Container(
                        padding: EdgeInsets.only(left: 10, top: 10),
                        height: 50,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            Expanded(
                              child: Text(
                                "备注",
                                textAlign: TextAlign.left,
                                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 18),
                              ),
                              flex: 5,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                Container(
                  width: MediaQuery.of(context).size.width - 50,
                  height: 100,
                  margin: EdgeInsets.only(bottom: 30),
                  decoration: BoxDecoration(color: Color.fromRGBO(244, 244, 244, 1)),
                  child: TextField(
                    maxLength: 500,
                    controller: hideDanger.remark,
                    maxLines: null,
                    decoration: InputDecoration(
                      contentPadding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 10),
                      border: InputBorder.none,
                      hasFloatingPlaceholder: true,
                      hintText: "请输入备注",
                      filled: true,
                      fillColor: Color.fromRGBO(244, 244, 244, 1),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
        inAsyncCall: isAnimating,
        // demo of some additional parameters
        opacity: 0.7,
        progressIndicator: CircularProgressIndicator(),
      ),
    );
  }
}
