import 'dart:convert';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
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/TextView.dart';
import '../../view/CheckExecute/checkexec_inspection.dart';

class CheckExecItemContent extends StatefulWidget {
  int checkId;

  CheckExecItemContent(this.checkId);

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

class _CheckExecItemContent extends State<CheckExecItemContent> {
  CheckPointDetail checkPointItemDetail;

  List<Image> imageList = [];
  String theme = '';
  String imageUrl = '';

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

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

  Future<void> initPage() async {
    await queryCheckPointDetail(widget.checkId).then((result) {
      setState(() {
        checkPointItemDetail = result;
        checkPointItemDetail.pointImgUrls.forEach((url) {
          if (null != url && url.isNotEmpty) {
            url = imageUrl + url;
            imageList.add(Image.network(url.replaceAll('\\', '/')));
          }
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (theme.isEmpty) {
      return const Scaffold(body: Text(''));
    }
    if (null == checkPointItemDetail || checkPointItemDetail.checkInputs.isEmpty) {
      return Scaffold(
          appBar: AppBar(
        title: const Text(
          '各检查项详情',
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
      ));
    }
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '各检查项详情',
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
      ),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            const Padding(
              padding: EdgeInsets.only(top: 5),
            ),
            Container(
              child: Column(
                children: checkPointItemDetail.checkInputs.keys.map((f) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      f == "其他"
                          ? Container()
                          : Container(
                              padding: const EdgeInsets.only(left: 10),
                              height: 20,
                              child: Text(
                                f,
                                style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
                              ),
                              alignment: Alignment.topLeft,
                            ),
                      Column(
                        children: checkPointItemDetail.checkInputs[f].keys.map((t) {
                          return Column(
                            children: <Widget>[
                              t.isNotEmpty
                                  ? Container(
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: <Widget>[
                                          Text(
                                            t,
                                            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                                          ),
                                          const Divider()
                                        ],
                                      ),
                                      margin: const EdgeInsets.only(top: 10, bottom: 10, left: 10),
                                    )
                                  : Container(),
                              Column(
                                  children: checkPointItemDetail.checkInputs[f][t].map((itemData) {
                                if (itemData.itemType == '文本' || itemData.itemType == '数字') {
                                  return Column(
                                    children: <Widget>[
                                      getTextNumFiled(itemData),
                                      const Divider(
                                        height: 1,
                                      )
                                    ],
                                  );
                                } else if (itemData.itemType == '选择') {
                                  return Column(
                                    children: <Widget>[
                                      getSelectFiled(itemData),
                                      const Divider(
                                        height: 1,
                                      )
                                    ],
                                  );
                                }
                              }).toList())
                            ],
                          );
                        }).toList(),
                      ),
                      Container(
                        height: 10.0,
                        color: Colors.grey[100],
                      ),
                    ],
                  );
                }).toList(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 组装文本，数字检查项显示
  Widget getTextNumFiled(CheckInput _checkItem) {
    TextEditingController _remarkController = TextEditingController();

    // 初始化拍照点下拉
    List<DropdownMenuItem> getListData() {
      List<DropdownMenuItem> items = [];
      // 循环初始化扩展分类
      for (var p in _checkItem.pictureInfo) {
        DropdownMenuItem dropdownMenuItem1 = DropdownMenuItem(
          child: Row(
            children: <Widget>[
              null == p.isMust || "否" != p.isMust
                  ? Container()
                  : const Text(
                      "*",
                      style: TextStyle(color: Colors.red),
                    ),
              Text(p.name)
            ],
          ),
          value: p.name,
        );
        items.add(dropdownMenuItem1);
      }

      if (items.isEmpty) {
        DropdownMenuItem dropdownMenuItem1 = const DropdownMenuItem(
          child: Text("无拍照点"),
          value: "无拍照点",
        );
        items.add(dropdownMenuItem1);
      }
      return items;
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Padding(
            padding: const EdgeInsets.only(left: 10, top: 10, bottom: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    null == _checkItem.isMust || "是" != _checkItem.isMust
                        ? Container()
                        : const Text(
                            "*",
                            style: TextStyle(color: Colors.red),
                          ),
                    Container(
                      width: 300,
                      child: Text(_checkItem.inputName ?? ""),
                    ),
                    GestureDetector(
                      child: Container(
                        width: 40,
                        padding: EdgeInsets.only(left: 10),
                        alignment: Alignment.topRight,
                        child: Row(
                          children: <Widget>[
                            const Icon(
                              Icons.message,
                              color: Colors.grey,
                              size: 14,
                            ),
                            Icon(
                              Icons.keyboard_arrow_right,
                              color: GetConfig.getColor(theme),
                              size: 14,
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        Navigator.push(this.context, MaterialPageRoute(builder: (context) {
                          return TextView(
                            text: _checkItem.remark ?? "",
                            readonly: true,
                          );
                        }));
                      },
                    ),
                  ],
                ),
                const Padding(
                  padding: EdgeInsets.only(top: 5),
                ),
                Container(
                  margin: EdgeInsets.only(right: 20),
                  height: 80,
                  width: double.infinity,
                  color: Colors.grey[100],
                  child: Padding(
                    padding: EdgeInsets.all(5),
                    child: Text(_checkItem.inputValue ?? ""),
                  ),
                ),
                Row(
                  children: <Widget>[
                    Text("拍照点"),
                    const Padding(
                      padding: EdgeInsets.only(left: 20, top: 20, bottom: 10),
                    ),
                    Container(
                      height: 40.0,
                      child: DropdownButton(
                        items: getListData(),
                        hint: Padding(
                          padding: const EdgeInsets.only(
                            right: 70.0,
                          ),
                          child: Text(_checkItem.pictureInfo.isNotEmpty ? _checkItem.pictureInfo[0].name : "无拍照点"),
                        ),
                        //下拉菜单选择完之后显示给用户的值
                        value: _checkItem.selectPicName,
                        onChanged: (T) {
                          //下拉菜单item点击之后的回调
                          setState(() {
                            _checkItem.selectPicName = T;
                            int i = 0;
                            _checkItem.pictureInfo.forEach((element) {
                              i++;
                              if (element.name == T) {
                                _checkItem.selectPic = [_checkItem.pointInputImgUrls[i]];
                              }
                            });
                            // 筛选图片
                          });
                        },
                        elevation: 24,
                        //设置阴影的高度
                        style: const TextStyle(
                            //设置文本框里面文字的样式
                            color: Colors.black),
                        isDense: false,
                        //减少按钮的高度。默认情况下，此按钮的高度与其菜单项的高度相同。如果isDense为true，则按钮的高度减少约一半。 这个当按钮嵌入添加的容器中时，非常有用
                        iconSize: 35.0, //设置三角标icon的大小
                      ),
                    ),
                  ],
                ),
                Container(
                  height: _checkItem.pointInputImgUrls.isEmpty
                      ? 100
                      : (_checkItem.pointInputImgUrls.length % 4 == 0
                          ? (_checkItem.pointInputImgUrls.length / 4 * 80 + 20)
                          : (_checkItem.pointInputImgUrls.length / 4 * 80 + 100)),
                  child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
                    Wrap(
                      children: _checkItem.pointInputImgUrls.isNotEmpty
                          ? _checkItem.pointInputImgUrls.map((p) {
                              p = imageUrl + p;
                              return GestureDetector(
                                child: Padding(
                                  padding: const EdgeInsets.only(right: 10, bottom: 10),
                                  child: Image.network(p.replaceAll("\\", "/"), width: 80.0, height: 80.0),
                                ),
                                onTap: () {
                                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                                    return ImageView(Image.network(
                                      p.replaceAll("\\", "/"),
                                    ));
                                  }));
                                },
                              );
                            }).toList()
                          : <Widget>[],
                    ),
                  ]),
                ),
              ],
            )),
      ],
    );
  }

// 组装选择检查项显示
  Widget getSelectFiled(CheckInput _checkItem) {
    TextEditingController _remarkController = TextEditingController();
    // 获取radio信息
    List<RadioWidgetInfo> rds = List();
    for (var rd in jsonDecode(_checkItem.dataJson)) {
      rds.add(RadioWidgetInfo.fromJson(rd));
    }

    // 初始化拍照点下拉
    List<DropdownMenuItem> getListData() {
      List<DropdownMenuItem> items = List();
      // 循环初始化扩展分类
      for (var p in _checkItem.pictureInfo) {
        DropdownMenuItem dropdownMenuItem1 = DropdownMenuItem(
          child: Row(
            children: <Widget>[
              null == p.isMust || "是" != p.isMust
                  ? Container()
                  : const Text(
                      "*",
                      style: TextStyle(color: Colors.red),
                    ),
              Text(p.name)
            ],
          ),
          value: p.name,
        );
        items.add(dropdownMenuItem1);
      }

      if (items.isEmpty) {
        DropdownMenuItem dropdownMenuItem1 = DropdownMenuItem(
          child: Row(
            children: <Widget>[Text("无拍照点")],
          ),
          value: "无拍照点",
        );
        items.add(dropdownMenuItem1);
      }
      return items;
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Padding(
            padding: const EdgeInsets.only(left: 10, top: 10, bottom: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    _checkItem.isMust == "是"
                        ? const Text(
                            "*",
                            style: TextStyle(color: Colors.red),
                          )
                        : Container(),
                    Container(
                      width: 300,
                      child: Text(_checkItem.inputName ?? ""),
                    ),
                    GestureDetector(
                      child: Container(
                        width: 40,
                        padding: const EdgeInsets.only(left: 10),
                        alignment: Alignment.topRight,
                        child: Row(
                          children: <Widget>[
                            const Icon(
                              Icons.message,
                              color: Colors.grey,
                              size: 14,
                            ),
                            Icon(
                              Icons.keyboard_arrow_right,
                              color: GetConfig.getColor(theme),
                              size: 14,
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        Navigator.push(context, MaterialPageRoute(builder: (context) {
                          return TextView(
                            text: _checkItem.remark ?? "",
                            readonly: true,
                          );
                        }));
                      },
                    ),
                  ],
                ),
                const Padding(
                  padding: EdgeInsets.only(top: 5),
                ),
                Column(
                  children: rds.map((r) {
                    return Row(
                      children: <Widget>[
                        Radio(
                          value: r.name,
                          groupValue: _checkItem.inputValue ?? "",
                          onChanged: null,
                        ),
                        Text(r.name)
                      ],
                    );
                  }).toList(),
                ),
                Row(
                  children: <Widget>[
                    const Text("拍照点"),
                    const Padding(
                      padding: EdgeInsets.only(left: 20, top: 20, bottom: 10),
                    ),
                    Container(
                      height: 40.0,
                      child: DropdownButton(
                        items: getListData(),
                        hint: Padding(
                          padding: const EdgeInsets.only(
                            right: 70.0,
                          ),
                          child: Text(_checkItem.pictureInfo.isNotEmpty ? _checkItem.pictureInfo[0].name : "无拍照点"),
                        ),
                        //下拉菜单选择完之后显示给用户的值
                        value: _checkItem.selectPicName ?? "",
                        onChanged: (T) {
                          //下拉菜单item点击之后的回调
                          setState(() {
                            _checkItem.selectPicName = T;
                            // 筛选图片
                            _checkItem.selectPic = _checkItem.pointInputImgUrls.toList();
                          });
                        },
                        elevation: 24,
                        //设置阴影的高度
                        style: const TextStyle(
                            //设置文本框里面文字的样式
                            color: Colors.black),
                        isDense: false,
                        //减少按钮的高度。默认情况下，此按钮的高度与其菜单项的高度相同。如果isDense为true，则按钮的高度减少约一半。 这个当按钮嵌入添加的容器中时，非常有用
                        iconSize: 35.0, //设置三角标icon的大小
                      ),
                    ),
                  ],
                ),
                Container(
                  height: 100,
                  child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
                    Wrap(
                      children: _checkItem.pointInputImgUrls.isNotEmpty
                          ? _checkItem.pointInputImgUrls.map((p) {
                              p = imageUrl + p;
                              return GestureDetector(
                                child: Padding(
                                  padding: const EdgeInsets.only(right: 10),
                                  child: Image.network(p.replaceAll("\\", "/"), width: 80.0, height: 80.0),
                                ),
                                onTap: () {
                                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                                    return ImageView(Image.network(
                                      p.replaceAll("\\", "/"),
                                    ));
                                  }));
                                },
                              );
                            }).toList()
                          : <Widget>[],
                    ),
                  ]),
                ),
              ],
            )),
      ],
    );
  }
}
