import 'package:base/consts/color.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/view/defect/hidden_defect_found.dart';
import 'package:safe_control/services/PlanTaskInitConfigServices.dart';
import 'package:safe_control/view/CheckExecute/checkexec_inspection_list.dart';

import '../../model/plan_inspection/check_point_detail.dart';
import '../../services/plan_inspection_services.dart';
import '../../view/CheckExecute/ImageListView.dart';
import '../../view/CheckExecute/checkexec_item_content.dart';
import '../../view/hidedanger_manage/hidden_Inspection_danger_add.dart';



class CheckExecListContent extends StatefulWidget {
  ///巡检点check Id
  num id;
  CheckExecListContent(this.id);
  @override
  State<StatefulWidget> createState() {
    return _CheckExecListContent();
  }
}

class _CheckExecListContent extends State<CheckExecListContent> {
  CheckPointDetail _checkPointDetail;
  String theme = '';
  String imageUrl = '';
  List<Image> imageList = [];
  List<NetworkImage> imageListThumb = [];
  bool isDefect = false;

  @override
  Widget build(BuildContext context) {
    if (_checkPointDetail == null) {
      return Scaffold(
        appBar: AppBar(
          title: const Text(
            '',
          ),
          centerTitle: true,
          elevation: 0.2,
          brightness: Brightness.light,
        ),
      );
    }

    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: Text(
            _checkPointDetail.pointName ?? '计划外',
          ),
          centerTitle: true,
          elevation: 0.2,
          brightness: Brightness.light,
          actions: <Widget>[
            isDefect && _checkPointDetail.pointStatus == '2'
                ? IconButton(
                    icon: const Icon(Icons.note_add),
                    tooltip: '添加任务',
                    onPressed: () {
                      getInitPlanTaskConfig(null, _checkPointDetail.pointId).then((data) {
                        if(data.extClass == null) {
                          return;
                        }
                        String equipmentId = '';
                        String equipmentName = '';
                        String dataSourceCode = '';
                        String defectEquipmentCode = '';
                        data.extClass.forEach((f) {
                          if(f.equipmentId != null){
                            equipmentId = equipmentId + f.equipmentId + ',';
                          }
                          equipmentName = equipmentName + f.name + ',';
                          dataSourceCode = f.dataSourceCode;
                          defectEquipmentCode = f.code;
                        });
                        if(equipmentId.contains(",")) {
                          equipmentId = equipmentId.substring(0,equipmentId.length -1);
                        }
                        if(equipmentName.contains(",")) {
                          equipmentName = equipmentName.substring(0,equipmentName.length -1);
                        }
                        List<UNCheckInput> selectedId = [];
                        _checkPointDetail.checkInputs.keys.forEach((f) {;
                          _checkPointDetail.checkInputs[f].forEach((key, value) {
                            value.forEach((d) {
                              var obj = {
                                'itemId':d.checkInputId,
                                'name': d.inputName,
                                'inputValue':d.inputValue,
                                'isSelected':false,
                              };
                              UNCheckInput _uNCheckInput = UNCheckInput.fromJson(obj);
                              selectedId.add(_uNCheckInput);
                            });

                          });
                        });
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) =>
                                    HiddenDefectFound(
                                      equipmentName: equipmentName,
                                      equipmentId: equipmentId,
                                      dataSourceCode: dataSourceCode,
                                      defectEquipmentCode:defectEquipmentCode,
                                      checkId: _checkPointDetail.checkId,
                                      unCheckInputData: selectedId
                                    )));
                      });
                    },
                    color: Colors.white)
                : Container(),
          ],
        ),
        body: SingleChildScrollView(
          child: Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Container(
                      padding: const EdgeInsets.only(left: 20, top: 10),
                      width: 150,
                      height: 40,
                      child: const Text(
                        '点编号',
                        style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
                      ),
                    ),
                    Text(_checkPointDetail.pointNo ?? ''),
                  ],
                ),
                const Divider(),
                Row(
                  children: <Widget>[
                    Container(
                      padding: const EdgeInsets.only(left: 20, top: 10),
                      width: 150,
                      height: 40,
                      child: const Text(
                        ''
                        ''
                        '巡检计划',
                        style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
                      ),
                    ),
                    Container(
                      child: Text(_checkPointDetail.planName ?? '计划外'),
                      width: 200,
                      height: 40,
                    ),
                  ],
                ),
                const Divider(),
                Row(
                  children: <Widget>[
                    Container(
                      padding: const EdgeInsets.only(left: 20, top: 10),
                      width: 150,
                      height: 40,
                      child: const Text(
                        '执行时间',
                        style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
                      ),
                    ),
                    Text(_checkPointDetail.checkTime),
                  ],
                ),
                const Divider(),
                Row(
                  children: <Widget>[
                    Container(
                      padding: const EdgeInsets.only(left: 20, top: 10),
                      width: 150,
                      height: 40,
                      child: const Text(
                        '执行部门',
                        style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
                      ),
                    ),
                    Text(_checkPointDetail.departmentName ?? ''),
                  ],
                ),
                const Divider(),
                Row(
                  children: <Widget>[
                    Container(
                      padding: const EdgeInsets.only(left: 20, top: 10),
                      width: 150,
                      height: 40,
                      child: const Text(
                        '执行人',
                        style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
                      ),
                    ),
                    Expanded(
                        child: Text(
                      _checkPointDetail.username ?? '',
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    )),
                  ],
                ),
                const Divider(),
                Row(
                  children: <Widget>[
                    Container(
                      padding: const EdgeInsets.only(left: 20, top: 10),
                      width: 150,
                      height: 40,
                      child: const Text(
                        '点状态',
                        style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
                      ),
                    ),
                    Text(
                      getPointStatus(_checkPointDetail.pointStatus),
                      style: TextStyle(color: getPointColor(_checkPointDetail.pointStatus)),
                    ),
                  ],
                ),
                Container(
                  color: Colors.grey[100],
                  height: 10,
                ),
                Container(
                  padding: const EdgeInsets.only(left: 20, top: 10),
                  height: 40,
                  child: const Text(
                    '检查项目',
                    style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
                  ),
                  alignment: Alignment.centerLeft,
                ),
                const Divider(
                  height: 1,
                ),
                const Padding(
                  padding: EdgeInsets.only(top: 10),
                ),
                Container(
                    child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: _checkPointDetail.checkInputs.keys.map((f) {
                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        GestureDetector(
                            child: Container(
                                width: 280,
                                padding: const EdgeInsets.only(left: 20),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    f == '其他'
                                        ? Container()
                                        : Container(
                                            height: 20,
                                            child: Text(
                                              f,
                                              style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                                            ),
                                            alignment: Alignment.topLeft,
                                          ),
                                    Container(
                                      padding: const EdgeInsets.only(top: 5),
                                      child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: _checkPointDetail.checkInputs[f].keys.map((t) {
                                            return Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: <Widget>[
                                                Column(
                                                    crossAxisAlignment: CrossAxisAlignment.start,
                                                    children: _checkPointDetail.checkInputs[f][t].map((itemData) {
                                                      return Text(itemData.inputName,
                                                          style: TextStyle(
                                                              color: itemData.inputStatus == '2'
                                                                  ? Colors.red
                                                                  : Colors.black,
                                                              fontSize: 14));
                                                    }).toList())
                                              ],
                                            );
                                          }).toList()),
                                    )
                                  ],
                                )),
                            onTap: () {
                              Navigator.push(context, MaterialPageRoute(builder: (context) {
                                return CheckExecItemContent(_checkPointDetail.checkId);
                              }));
                            }),
                      ],
                    );
                  }).toList(),
                )),
                Container(
                  height: 10.0,
                  color: Colors.grey[100],
                ),
                getImageEidget(),
                Container(
                  height: 10.0,
                  color: Colors.grey[100],
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 10.0, top: 10.0, bottom: 20.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      const Text('备注'),
                      Container(
                        margin: const EdgeInsets.only(right: 20, top: 20),
                        height: 80,
                        width: double.infinity,
                        color: Colors.grey[100],
                        child: Padding(
                          padding: const EdgeInsets.all(5),
                          child: Text(_checkPointDetail.remark ?? ''),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            color: Colors.white,
          ),
        ));
  }

  Widget getImageEidget() {
    num thumbIdx = -1;
    return GestureDetector(
      child: Padding(
          padding: const EdgeInsets.only(left: 10.0, top: 15.0, bottom: 20.0),
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
            Row(
              children: <Widget>[
                const Text('现场照片'),
                imageListThumb.isNotEmpty
                    ? Container(
                        width: 260,
                        height: 40,
                        padding: EdgeInsets.only(left: 210.0 - imageListThumb.length * 20.0),
                        child: Stack(
                          children: imageListThumb.map((f) {
                            thumbIdx++;
                            return thumbIdx == 0
                                ? Positioned(
                                    child: CircleAvatar(
                                      backgroundColor: Colors.transparent,
                                      backgroundImage: NetworkImage(f.url),
                                      radius: 20,
                                    ),
                                  )
                                : Positioned(
                                    left: thumbIdx * 20.0,
                                    child: CircleAvatar(
                                      backgroundColor: Colors.transparent,
                                      backgroundImage: NetworkImage(f.url),
                                      radius: 20,
                                    ),
                                    //CircleAvatar(child: Image.network(f.url,height: 20,width: 20,fit: BoxFit.fill,),backgroundColor: Colors.transparent),
                                  );
                          }).toList(),
                        ),
                      )
                    : Container(
                        width: 260,
                      ),
                Icon(
                  Icons.keyboard_arrow_right,
                  color: GetConfig.getColor(theme),
                  size: 20,
                ),
              ],
            ),
          ])),
      onTap: () {
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return ImageListView(imageList);
        }));
      },
    );
  }

  @override
  void initState() {
    super.initState();
    dynamic map = Get.arguments;
    if (map != null){
      widget.id = num.parse(map['id']);
    }
    getData();
    initConfig();
    SharedPreferences.getInstance().then((sp) {
      String str = sp.get('permissionList');
      if(str.indexOf('/hiddenAdd') != -1){
        isDefect = true;
      }else{
        isDefect = false;
      }
      setState(() {});
    });
  }

  void initConfig() {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        theme = preferences.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
        imageUrl = preferences.getString('imageUrl') ?? '';
      });
    });
  }


  Future<void> getData() async {
    await queryCheckPointDetail(widget.id).then((data) {
      if (data != null) {
        setState(() {
          _checkPointDetail = data;
          _checkPointDetail.pointImgUrls.forEach((url) {
            if (null != url && url.isNotEmpty) {
              url = imageUrl + url;
              if (url.endsWith('jpg')) {
                imageList.add(Image.network(url.replaceAll('\\', '/')));
                imageListThumb.add(NetworkImage(url.replaceAll('\\', '/')));
              }
            }
            imageListThumb = imageListThumb.length > 3 ? imageListThumb.sublist(0, 3).toList() : imageListThumb;
          });
        });
      }
    });
  }

  String getPointStatus(String pointStatus) {
    if (pointStatus == '0') {
      return '未开始';
    } else if (pointStatus == '1') {
      return '合格';
    } else if (pointStatus == '2') {
      return '不合格';
    } else if (pointStatus == '3') {
      return '漏检';
    } else {
      return '';
    }
  }

  Color getPointColor(String pointStatus) {
    if (pointStatus == '0') {
      return Colors.grey;
    } else if (pointStatus == '1') {
      return Colors.green;
    } else if (pointStatus == '2') {
      return Colors.red;
    } else if (pointStatus == '3') {
      return Colors.orange;
    } else {
      return Colors.white;
    }
  }
}
