import 'package:base/consts/color.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:base/view/ImageViewPage.dart';
import 'package:flutter/cupertino.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/hidedanger_manage/hidden_danger_flowRecord.dart';
import '../../view/hidedanger_manage/hidden_danger_found.dart';
import '../../view/hidedanger_manage/hidden_danger_review.dart';
import '../../view/hidedanger_manage/hidedanger_pending.dart';

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

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

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

class _HiddenDangerDepartReview extends State<HiddenDangerDepartReview> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  bool isAnimating = false;

  bool canOperate = true;

  bool isTG = true;
  HideDangerInfoModel initData;
  HideDanger hideDanger = HideDanger();

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

  // 当前页码
  int pageIndex = 0;

  // Default placeholder text
  var reviewRes = 16;

  // 是否有下一页
  bool hasNext = false;
  List<String> rectMeasures = [];

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

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

  void loadData() async {
    setState(() {
      isAnimating = true;
    });
    await getHiddenDangerModel(context,this.widget.dangerId, this.widget.taskId).then((data) {
      setState(() {
        if (data != null) {
          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, this.widget.taskId, context);
          }
        }
        isAnimating = false;
      });
    });
  }

  _saveReformResult(HideDanger hd) async {
    setState(() {
      isAnimating = true;
      canOperate = false;
    });
    await saveReviewResult(hd, this.reviewRes, initData.currentFlowRecordId, {}, this.widget.taskId, initData.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 (this.reviewRes == 0) {
      HiddenDangerFound.popUpMsg("请选择评审结果！");
      return false;
    }
    if (hideDanger.remark.text.isEmpty) {
      HiddenDangerFound.popUpMsg("请填写评审说明！");
      return false;
    }
    return true;
  }

  void showAlertDialog() {
    showDialog<Null>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return StatefulBuilder(builder: (context, state) {
          return SimpleDialog(
            contentPadding: EdgeInsets.only(top: 10),
            children: <Widget>[
              Container(
                margin: EdgeInsets.all(10),
                padding: EdgeInsets.only(left: 15),
                alignment: Alignment.centerLeft,
                child: Text("是否需要公司领导审核："),
              ),
              Column(
                children: <Widget>[
                  RadioListTile(
                    value: 1,
                    groupValue: hideDanger.needCompanyVerify,
                    title: Text("是"),
                    onChanged: (val) {
                      state(() {
                        hideDanger.needCompanyVerify = val;
                      });
                    },
                  ),
                  RadioListTile(
                    value: 0,
                    groupValue: hideDanger.needCompanyVerify,
                    title: Text("否"),
                    onChanged: (val) {
                      state(() {
                        hideDanger.needCompanyVerify = val;
                      });
                    },
                  ),
                ],
              ),
              Container(
                decoration: const BoxDecoration(
                    border: Border(top: BorderSide(color: Color.fromRGBO(240, 240, 240, 1), width: 1.0))),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Container(
                        width: 140,
                        child: FlatButton(
                            child: const Text(
                              "取消",
                              style: TextStyle(fontSize: 16),
                            ),
                            onPressed: () {
                              setState(() {
                                hideDanger.needCompanyVerify = 0;
                              });
                              Navigator.pop(context);
                            })),
                    Container(
                      color: Theme.of(context).primaryColor,
                      width: 140,
                      child: FlatButton(
                          child: const Text(
                            "确认",
                            style: TextStyle(fontSize: 16, color: Colors.white),
                          ),
                          onPressed: () {
                            if (canOperate) {
                              if (_checkNeed()) {
                                _saveReformResult(hideDanger);
                              }
                            } else {
                              HiddenDangerFound.popUpMsg("正在执行操作，请稍等...");
                            }
                            Navigator.pop(context);
                          }),
                    )
                  ],
                ),
              ),
            ],
          );
        });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    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: 32,
              ),
            ),
          ))
        ],
        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()) {
                    if (reviewRes == 17) {
                      _saveReformResult(hideDanger);
                    } else {
                      showAlertDialog();
                    }
                  }
                } else {
                  HiddenDangerFound.popUpMsg("正在执行操作！请稍等...");
                }
              },
              child: const Icon(
                Icons.save,
                size: 32,
              ), //Image.asset("assets/images/search_"+theme+".png",width: 20,color: Theme.of(context).primaryColor),
            ),
          ))
        ],
        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.belongDepartmentName),
                              )
                            ],
                          ),
                          //分割线
                          Container(
                            color: Colors.grey[100],
                            height: 10,
                          ),
                        ],
                      )
                    : 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(color: Colors.black, fontSize: 18),
                              ),
                              flex: 19,
                            ),
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 10,
                      child: Container(
                        child: Text(initData.dangerName ?? ""),
                        padding: const EdgeInsets.only(top: 5, right: 10),
                      ),
                    ),
                  ],
                ),
                //隐患等级
                Row(
                  children: <Widget>[
                    Expanded(
                      flex: 5,
                      child: Container(
                        padding: EdgeInsets.only(left: 10, top: 10),
                        width: 150,
                        height: 50,
                        child: Row(
                          children: const <Widget>[
                            Expanded(
                              child: Text(
                                "隐患等级",
                                style: TextStyle(color: Colors.black, 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: 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: GestureDetector(
                              child: Wrap(
                                  direction: Axis.horizontal,
                                  spacing: -25.0,
                                  // 主轴(水平)方向间距
                                  runSpacing: 5.0,
                                  // 纵轴（垂直）方向间距
                                  alignment: WrapAlignment.end,
                                  //沿主轴方向居中
                                  children: initData.photoUrls != null
                                      ? initData.photoUrls.map((f) {
                                          return Column(
                                            mainAxisAlignment: MainAxisAlignment.start,
                                            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()),
                              onTap: () {
                                if (initData.photoUrls != null && initData.photoUrls.length > 0) {
                                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                                    return PhotoViewPage(initData.photoUrls);
                                  }));
                                }
                              },
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: Icon(
                              Icons.keyboard_arrow_right,
                              color: Theme.of(context).primaryColor,
                              size: 22,
                            ),
                          ),
                        ),
                      ],
                    ),
                    //50  89  206
                    onTap: () {
                      Navigator.push(context, MaterialPageRoute(builder: (context) {
                        return PhotoViewPage(initData.photoUrls);
                      }));
                    },
                  ),
                ),

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

                //执行日志
                Container(
                  padding: 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: 5,
                      child: Text(
                        initData.reformLimitDate != null
                            ? DateFormat('yyyy-MM-dd').format(DateTime.parse(initData.reformLimitDate.toString()))
                            : "",
                        style: const TextStyle(color: Colors.black),
                      ),
                    ),
                  ],
                ),
                //延期日期
                Row(
                  children: <Widget>[
                    Expanded(
                      flex: 5,
                      child: Container(
                        padding: 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: 5,
                      child: Text(
                        initData.delayLimitDate != null
                            ? DateFormat('yyyy-MM-dd').format(DateTime.parse(initData.delayLimitDate.toString()))
                            : "",
                        style: TextStyle(color: Colors.black),
                      ),
                    ),
                  ],
                ),
                Container(
                  child: Column(
                    children: <Widget>[
                      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(
                                      isTG ? "*" : "",
                                      style: TextStyle(color: Colors.red),
                                    ),
                                    flex: 0,
                                  ),
                                  Expanded(
                                    child: Text(
                                      "评审结果",
                                      textAlign: TextAlign.left,
                                      style: TextStyle(color: Colors.black, fontSize: 18),
                                    ),
                                    flex: 9,
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                      Container(
                          child: Column(
                        children: <Widget>[
                          Container(
                              padding: EdgeInsets.only(
                                left: 30,
                                top: 5,
                              ),
                              width: MediaQuery.of(context).size.width,
                              height: 50,
                              child: Row(
                                children: <Widget>[
                                  Expanded(
                                    child: Row(
                                      children: <Widget>[
                                        Expanded(
                                          flex: 5,
                                          child: RadioListTile(
                                              title: Text("通过"),
                                              value: 16,
                                              groupValue: reviewRes,
                                              onChanged: (value) {
                                                setState(() {
                                                  print(value);
                                                  isTG = true;
                                                  reviewRes = value;
                                                });
                                              }),
                                          //带文字的单选按钮 value值=groupValue值 即选中状态
                                        ),
                                        Expanded(
                                          flex: 5,
                                          child: RadioListTile(
                                              title: Text("不通过"),
                                              value: 17,
                                              groupValue: reviewRes,
                                              onChanged: (value) {
                                                setState(() {
                                                  print(value);
                                                  isTG = false;
                                                  reviewRes = value;
                                                });
                                              }),
                                          //带文字的单选按钮 value值=groupValue值 即选中状态
                                        ),
                                      ],
                                    ),
                                    flex: 3,
                                  ),
                                ],
                              )),
                        ],
                      )),
                    ],
                  ),
                ),
                //评审说明
                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(
                                "*",
                                style: TextStyle(color: Colors.red),
                              ),
                              flex: 0,
                            ),
                            Expanded(
                              child: Text(
                                "评审说明",
                                textAlign: TextAlign.left,
                                style: TextStyle(color: Colors.black, fontSize: 18),
                              ),
                              flex: 9,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                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),
                    ),
                  ),
                ),
                Container(
                  color: Colors.grey[100],
                  height: 10,
                ),
                //治理措施
              ],
            ),
          ),
        ),
        inAsyncCall: isAnimating,
        // demo of some additional parameters
        opacity: 0.7,
        progressIndicator: CircularProgressIndicator(),
      ),
    );
  }
}
