import 'package:flutter/material.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/viewmodel/alarm_info.dart';
import 'package:jcs_airport/viewmodel/confirm_alam.dart';

const _items = [
  {'value': 'BREAKDOWN', 'label': '故障'},
  {'value': 'SHIELD', 'label': '屏蔽'},
  {'value': 'Alarm', 'label': '告警'},
  {'value': 'Action', 'label': '动作'},
  {'value': 'FIREALARM', 'label': '火警'},
  {'value': 'Abnormal', 'label': '异常'},
  {'value': 'FeedBack', 'label': '反馈'},
  {'value': 'PowerLoss', 'label': '失电'},
  {'value': 'StartStop', 'label': '启停'},
  {'value': 'Activation', 'label': '激活'},
  {'value': 'Indicate', 'label': '指示信号'},
  {'value': 'Tripping', 'label': '跳闸'},
  {'value': 'OilLeak', 'label': '漏油'},
  {'value': 'Quarantine', 'label': '隔离'},
  {'value': 'Release', 'label': '释放'},
  {'value': 'Control', 'label': '控制'}
];




/// 告警详情页面
class AlarmInfoDetail extends StatefulWidget {
  const AlarmInfoDetail({Key key}) : super(key: key);

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

class _AlarmInfoDetailState extends State<AlarmInfoDetail> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  AlarmInfo alarmInfo = AlarmInfo();
  ConfirmAlam confirmAlamResult = ConfirmAlam();

  bool isAnimating = false;
  bool shouldEdit = false;
  bool shouldSubmit = false;

  String isFire = '';
  List _itemslist = [];

  @override
  void initState() {
    super.initState();
    getMe();
    dynamic map = Get.arguments;
    alarmInfo = AlarmInfo.fromJson(map);
    confirmAlamResult = ConfirmAlam.fromJson(map);
    shouldSubmit = alarmInfo.isFirm != 'yes' ? true : false;
    isFire = alarmInfo.isFirm;
    getAlarmDetailsById(map['id']);
  }

  @override
  Widget build(BuildContext context) {
    print('${Get.arguments}');
    String buttonName = getButtonText();
    return Scaffold(
        appBar: AppBar(
          title: const Text('警情详情'),
        ),
        body: SingleChildScrollView(
            child: Card(
                child: Container(
                    padding: const EdgeInsets.all(10),
                    child: Column(children: [
                      _buildAlarmInfoItem(),
                      Row(children: [
                        Expanded(
                            child: FlatButton(
                                color: Colors.blueAccent,
                                height: 40,
                                onPressed: () {
                                  MsgBox.showConfirmDialog(context, confirmAlam, content: '是否${buttonName}');
                                },
                                child: Text(buttonName, style: const TextStyle(color: Colors.white))))
                      ])
                    ])))));
  }

  String getButtonText() {
    if (shouldEdit && !shouldSubmit) {
      return '修改';
    }
    return '提交';
  }

  Future<void> confirmAlam() async {
    if (!shouldSubmit) {
      setState(() {
        shouldSubmit = true;
      });
      return;
    }
    


   if (confirmAlamResult.confirmType == null || confirmAlamResult.confirmType == '') {
        ToastUtils.showToast('确警类型不能为空！');
      return ;
    }
   if (confirmAlamResult.alamReason == null || confirmAlamResult.alamReason == '') {
        ToastUtils.showToast('报警原因不能为空！');
      return ;
    }
   if (confirmAlamResult.resolveResult == null || confirmAlamResult.resolveResult == '') {
        ToastUtils.showToast('处理情况不能为空！');
      return ;
    }


    confirmAlamResult.isBatch = confirmAlamResult.isBatch != 1 ? 0 : 1;
    MsgBox.showProgressDialog(context);
    API.confirmAlam(confirmAlamResult).then((result) {
      if (result == null) {
        Get.back();
        return;
      } else {
        ToastUtils.showToast('响应异常，提交失败！！');
      }
    }).whenComplete(() => Get.back());
  }

  /// 根据ID查询警情详情
  Future<void> getAlarmDetailsById(id) async {
    API.getAlarmDetailsById(id).then((result) {
      var data = result['data'];
      if (data != null) {
        setState(() {
          alarmInfo = AlarmInfo.detailsToJson(data);
          alarmInfo.isFirm = isFire;
        });
      }
    });
  }

  /// 构建警情详情
  Container _buildAlarmInfoItem() {
    List<Widget> widgetList = [];
    widgetList.addAll(_buildAlarmInfo());
    widgetList.addAll(_buildProcessInfo());

    return Container(
      padding: const EdgeInsets.only(right: 00, bottom: 20),
      child: Column(
        children: widgetList,
      ),
    );
  }

  /// 构建警情信息
  List<Widget> _buildAlarmInfo() {
    String firm = getIsFirm();
    Color firmColor = getIsFirmColor();
    List<Widget> widgetList = [];
    widgetList.addAll([
      Container(
        child: Row(
          children: [
            Expanded(
              flex: 5,
              child: Column(
                children: [
                  _buildTitle('警情信息'),
                  _buildRowInfo('报警类型：', alarmInfo.equipmentSpecificIndexName),
                  _buildRowInfo('报警设备：', alarmInfo.fireEquipmentName)
                ],
              ),
            ),
            Expanded(
                flex: 2,
                child: Column(children: [
                  ClipRRect(
                      //剪裁为圆角矩形
                      borderRadius: BorderRadius.circular(38.0),
                      child: Container(
                          height: 76,
                          width: 76,
                          decoration: BoxDecoration(color: firmColor),
                          child: Transform.translate(
                              offset: const Offset(15, 25),
                              child: Text(firm, style: TextStyle(color: getIsFirmTextColor(), fontWeight: FontWeight.w600)))))
                ]))
          ],
        ),
      ),
      _buildRow('报警内容：', alarmInfo.fireEquipmentSpecificIndexName),
      _buildRow('报警时间：', alarmInfo.createDate),
      _buildRow('设备编号：', alarmInfo.equipmentSpecificCode),
      _buildRow('设备位置：', alarmInfo.warehouseStructureName)
    ]);
    return widgetList;
  }

  /// 构建处理信息
  List<Widget> _buildProcessInfo() {
    bool edit = (alarmInfo.isFirm != 'yes' ? true : false);
    if (shouldSubmit) {
      edit = true;
    }
    List<Widget> widgetList = [];
    widgetList.add(_buildTitle('处理信息'));
    if (edit) {
      /// 编辑/新增处理警情
      /// 
      widgetList.add(
        AmosForm(formKey: formKey, children: _buildFormModel(context), onChanged: (value) => onChangeForm(value)),
      );
    } else {
      widgetList.add(_buildRow('确认类型：',  alarmInfo.confirmTypeName));
      widgetList.add(_build2Row('报警原因：', alarmInfo.alamReason));
      widgetList.add(_build2Row('处理情况：', alarmInfo.resolveResult));
      widgetList.add(_buildRow('处理人员：', alarmInfo.confirmUserName));
      widgetList.add(_buildRow('处理时间：', alarmInfo.confirmDate));
    }

    return widgetList;
  }

  Future<void> onChangeForm(value) {
    print(value.toString());
     confirmAlamResult.resolveResult = value['resolveResult'];
    confirmAlamResult.alamReason = value['alamReason'];
    confirmAlamResult.isBatch = value['batch'] ? 1 : 0;

  }

  String getIsFirm() {
    String firm = alarmInfo.isFirm == 'yes' ? '已处理' : '待处理';
    return firm;
  }

  Color getIsFirmColor() {
    Color firm = alarmInfo.isFirm == 'yes' ? const Color(0xffcccccc) : const Color(0xffff9900);
    return firm;
  }

  Color getIsFirmTextColor() {
    Color firm = alarmInfo.isFirm == 'yes' ? Colors.black : Colors.white;
    return firm;
  }

  /// 构建编辑/新增处理警情表单
  List<Widget> _buildFormModel(context) {

    

 confirmAlamResult.confirmType=alarmInfo.confirmType;

  print(confirmAlamResult.confirmType);
 confirmAlamResult.alamReason=alarmInfo.alamReason;
 confirmAlamResult.resolveResult=alarmInfo.resolveResult;
 _itemslist.clear();
 _itemslist.add({'value': 'wrong', 'label': '误报'});
 _itemslist.add({'value': 'test', 'label': '测试'});
 _items.forEach((element) {
   if(element['label'].toString()==alarmInfo.equipmentSpecificIndexName){
     _itemslist.add(element);
   }


 });


    List<Widget> formItems = [];
    formItems.add(Padding(
      padding: const EdgeInsets.symmetric(horizontal: 15),
      child: Row(
        children: [

          const Expanded(
              child: Text(
                '*',
                style: TextStyle(color: Colors.red),
              ),
              flex: 0,
            ),
          const Expanded(child: Text('确认类型：')),
          Expanded(
            child: DropdownButtonFormField<String>(
                //style: const TextStyle(fontSize: 14),
                decoration: const InputDecoration(border: InputBorder.none),
                items: _itemslist
                    .map((item) => DropdownMenuItem(
                      
                          child: Text(item['label'].toString()),
                          value: item['value'].toString(),
                        ))
                    .cast<DropdownMenuItem<String>>()
                    .toList(),
                value: confirmAlamResult.confirmType,
                onChanged: (value) {
                  // setState(() {
                    confirmAlamResult.confirmType = value;
                  // });
                }),
          ),
        ],
      ),
    ));
    formItems.add(FormItem(
      label: '批量处理',
      layout: FormLayout.horizontal,
      labelWidth: 80,
      invert: true,
      formfield: AmosCheckbox(
          fieldKey: 'batch',
          initialValue: false,
          title: '批量',
          onChanged: (val) {
            print(val);
            confirmAlamResult.isBatch = val ? 0 : 1;
          }),
    ));
    formItems.addAll([
       Row(
        children: [
       const Expanded(
              child: Text(
                '*',
                style: TextStyle(color: Colors.red),
              ),
              flex: 0,
            ),
         Expanded(child: FormItem(
          layout: FormLayout.horizontal,
          label: '报警原因',
          // labelWidth: 80,
          invert: true,
          formfield: AmosTextField(fieldKey: 'alamReason',  initialValue: confirmAlamResult.alamReason ,  maxLines: 5, hint: '请输入告警原因')),
          ),
          ]),
        Row(
        children: [
        const Expanded(
              child: Text(
                '*',
                style: TextStyle(color: Colors.red),
              ),
              flex: 0,
            ),
          Expanded(child: FormItem(
          layout: FormLayout.horizontal,
          label: '处理情况',
          // labelWidth: 80,
          invert: true,
          formfield: AmosTextField(fieldKey: 'resolveResult',initialValue: confirmAlamResult.resolveResult , maxLines: 5, hint: '请输入处理情况')),
          ),
        ])

    ]);

    return formItems;
  }

  /// 构建单行显示信息
  Widget _buildRow(String title, String content) {
    return Container(
      padding: const EdgeInsets.only(bottom: 5, left: 16),
      child: Row(
        children: [
          Expanded(
              flex: 2,
              child: Text(
                title ?? '',
              )),
          Expanded(
              flex: 7,
              child: Text(
                content ?? '',
              )),
        ],
      ),
    );
  }

  /// 构建换行显示信息
  Widget _build2Row(String title, String content) {
    return Container(
      child: Row(
        children: [
          Expanded(
            child: Column(
              children: [
                Container(
                  padding: const EdgeInsets.only(bottom: 5, left: 16),
                  child: Row(
                    children: [
                      Expanded(child: Text(title ?? '')),
                    ],
                  ),
                ),
                Container(
                    padding: const EdgeInsets.only(bottom: 5, left: 16),
                    child: Transform.translate(
                        offset: const Offset(20, 0),
                        child: Row(
                          children: [
                            Expanded(child: Text(content ?? '')),
                          ],
                        )))
              ],
            ),
          )
        ],
      ),
    );
  }

  /// 构建警情信息 待处理右侧组件
  Widget _buildRowInfo(String title, String content) {
    return Container(
      padding: const EdgeInsets.only(bottom: 5, left: 16),
      child: Row(
        children: [
          Expanded(flex: 3, child: Text(title ?? '')),
          Expanded(flex: 5, child: Transform.translate(offset: const Offset(-10, 0), child: Text(content ?? ''))),
        ],
      ),
    );
  }

  /// 构建分组标题
  Widget _buildTitle(String title) {
    return Container(
      padding: const EdgeInsets.only(bottom: 10, left: 16),
      child: Row(
        children: [
          Expanded(flex: 2, child: Text(title ?? '', style: TextStyle(fontSize: 22, fontWeight: FontWeight.w800))),
        ],
      ),
    );
  }

  Future<void> getMe() {
    API.agencyuserMe().then((userInfo) {
      userInfo['orgRoles'].forEach((key, value) {
        for (final item in value) {
          if (item['roleType'] == 'admin') {
            setState(() {
              shouldEdit = true;
            });
          }
        }
      });
      print(userInfo);
    });
  }
}
