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 '../../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/plan_inspection/plan_list_screen.dart';

class PlanListContentDetail extends StatefulWidget {
  final num planTaskId;
  final num pointId;

  const PlanListContentDetail(this.planTaskId, this.pointId);

  @override
  State<StatefulWidget> createState() => _PlanListContentDetail();
}

class _PlanListContentDetail extends State<PlanListContentDetail> {
  CheckPointDetail pointDetail;
  String theme = '';
  String imageUrl = '';
  List<NetworkImage> imageListThumb = [];
  List<Image> imageList = [];

  @override
  void initState() {
    super.initState();
    getData();
    initConfig();
  }

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

  Future<void> getData() async {
    await queryPointPlanTaskDetail(widget.planTaskId, widget.pointId).then((data) {
      if (data.message != null && data.message.isNotEmpty) {
        showDialog(
            context: context,
            barrierDismissible: false,
            builder: (_) => AlertDialog(
                    title: Column(
                      children: const <Widget>[
                        Text('信息'),
                        Divider(height: 2),
                      ],
                    ),
                    content: Text(data.message),
                    actions: <Widget>[
                      FlatButton(
                        child: const Text('关闭', style: TextStyle(fontSize: 20, color: Colors.grey)),
                        onPressed: () {
                          Navigator.of(context).pushAndRemoveUntil(
                              MaterialPageRoute(builder: (context) => PlanListScreen()), (route) => route == null);
                        },
                      ),
                    ])).then((v) {
          return v;
        });
        return;
      }
      setState(() {
        pointDetail = data;
        pointDetail.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;
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    num thumbIdx = -1;
    if (theme.isEmpty) {
      return const Scaffold(body: Text(''));
    }
    // 数据未加载完成，只显示头部
    if (null == pointDetail) {
      return Scaffold(
          appBar: AppBar(
        title: const Text(
          '',
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
      ));
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(
          pointDetail.pointName ?? '',
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
      ),
      body: SingleChildScrollView(
        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(pointDetail.pointNo ?? '', style: const TextStyle(color: Colors.grey)),
              ],
            ),
            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(
                  pointDetail.planName ?? '',
                  maxLines: 1,
                  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(pointDetail.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(pointDetail.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(
                  pointDetail.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(pointDetail.pointStatus),
                  style: TextStyle(color: getPointColor(pointDetail.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: 18),
              ),
              alignment: Alignment.centerLeft,
            ),
            const Divider(
              height: 1,
            ),
            const Padding(
              padding: EdgeInsets.only(top: 10),
            ),
            Container(
              padding: const EdgeInsets.only(left: 20, top: 5),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: pointDetail.checkInputs.keys.map((f) {
                  return GestureDetector(
                      child: Container(
                          width: 280,
                          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(
                                child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: pointDetail.checkInputs[f].keys.map((t) {
                                      return Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: <Widget>[
//                                      Text(f),
                                          Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: pointDetail.checkInputs[f][t].map((itemData) {
                                                return Text(itemData.inputName,
                                                    style: TextStyle(
                                                        color: itemData.inputStatus == '2' ? Colors.red : Colors.black,
                                                        fontSize: 14));
                                              }).toList())
                                        ],
                                      );
                                    }).toList()),
                                padding: const EdgeInsets.only(top: 5),
                              )
                            ],
                          )),
                      onTap: () {
                        if (pointDetail.pointStatus != '0') {
                          Navigator.push(context, MaterialPageRoute(builder: (context) {
                            return CheckExecItemContent(pointDetail.checkId);
                          }));
                        }
                      });
                }).toList(),
              ),
            ),
            pointDetail.pointStatus == '0'
                ? Container()
                : Container(
                    height: 10.0,
                    color: Colors.grey[100],
                  ),
            pointDetail.pointStatus == '0'
                ? Container()
                : 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(
                                '*',
                                style: TextStyle(color: Colors.red),
                              ),
                              const Text('现场照片'),
                              imageListThumb.isNotEmpty
                                  ? Container(
                                      width: 260,
                                      height: 30,
                                      padding: EdgeInsets.only(left: 210.0 - imageListThumb.length * 20.0),
                                      child: Stack(
                                        children: imageListThumb.map((f) {
                                          thumbIdx++;
                                          return thumbIdx == 0
                                              ? Positioned(
                                                  child: CircleAvatar(
                                                    child: Image.network(
                                                      f.url,
                                                      height: 25,
                                                    ),
                                                    backgroundColor: Colors.grey,
                                                    radius: 20,
                                                  ),
                                                )
                                              : Positioned(
                                                  left: thumbIdx * 25.0,
                                                  child: CircleAvatar(
                                                    child: Image.network(
                                                      f.url,
                                                      height: 25,
                                                    ),
                                                    backgroundColor: Colors.grey,
                                                    radius: 20,
                                                  ),
                                                );
                                        }).toList(),
                                      ),
                                    )
                                  : Container(
                                      width: 260,
                                    ),
                              Icon(
                                Icons.keyboard_arrow_right,
                                color: Theme.of(context).primaryColor,
                                size: 20,
                              ),
                            ],
                          ),
                        ])),
                    onTap: () {
                      Navigator.push(context, MaterialPageRoute(builder: (context) {
                        return ImageListView(imageList);
                      }));
                    },
                  ),
            pointDetail.pointStatus == '0'
                ? Container()
                : Container(
                    height: 10.0,
                    color: Colors.grey[100],
                  ),
            pointDetail.pointStatus == '0'
                ? Container()
                : 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(pointDetail.remark ?? ''),
                          ),
                        ),
                      ],
                    ),
                  ),
          ],
        ),
      ),
    );
  }

  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;
    }
  }
}
