import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:liftmanager/internal/wode/wode_router.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/colors.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/selected_image_change.dart';

class Representations extends StatefulWidget {
  Representations(this.id);

  final String id;

  @override
  State<StatefulWidget> createState() {
    return RepresentationsState();
  }
}

class RepresentationsState extends State<Representations> {
  List<String> images = [];

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

  ///选择图片
  void selectPicker() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return SimpleDialog(
          title: Text("选择方式"),
          children: ["拍照", '从手机相册选择'].map((String value) {
            print("$value");
            return SimpleDialogOption(
              child: Text(
                "${value}",
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
              ),
              onPressed: () {
                _getImage(value == '拍照' ? 1 : 0);
                Navigator.of(context).pop();
              },
            );
          }).toList(),
        );
      },
    );
  }

  void _getImage(int key) async {
    try {
      var _imageFile = await ImagePicker.pickImage(
          source: key == 1 ? ImageSource.camera : ImageSource.gallery,
          maxWidth: 800,
          imageQuality: 95);
      if (_imageFile != null) {
        // images.add(_imageFile);
        // setState(() {});
        upLoadFileOnce(_imageFile.path);
      }
    } catch (e) {
      toasts("没有权限，无法打开相册！");
    }
  }

  upLoadFileOnce(path) {
    showLoading(context, "正在上传...");
    NewApiService().upload(path, onSuccess: (res) {
      // imagesUrl.add(res.pathUrl);
      dismissLoading(context);
      setState(() {
        images.add(res.pathUrl);
      });
    }, onError: (code, msg) {
      dismissLoading(context);
      toasts(msg);
    });
  }

  submitApply() {
    // _contentController
    NewApiService().submitAppeal({
      "dataId": int.parse(widget.id),
      "content": _contentController.text,
      "imgs": images.join(",")
    }, onSuccess: (res) {
      dismissLoading(context);
      toasts("提交成功");
      FocusScope.of(context).requestFocus(FocusNode());
      NavigatorUtils.push(context, "${WodeRouter.orderPage}?checkType=0");
    }, onError: (code, msg) {
      dismissLoading(context);
      toasts(msg);
    });
  }

  FocusNode blankNode = FocusNode();

  // 文本编辑控制
  GlobalKey _formKey = new GlobalKey<FormState>();
  TextEditingController _contentController = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;

    return Scaffold(
      resizeToAvoidBottomPadding: false, //不让键盘弹上去
      appBar: MyAppBar(
        centerTitle: "申诉",
      ),
      body: GestureDetector(
        onTap: () {
          // 点击空白页面关闭键盘
          FocusScope.of(context).requestFocus(blankNode);
        },
        child: Container(
          child: ListView(
            children: <Widget>[
              Form(
                key: _formKey, //设置globalKey，用于后面获取FormState
                // autovalidate: true, //开启自动校验
                child: Column(
                  children: <Widget>[
                    Row(
                      children: [
                        Container(
                          color: Colours.blue_app_main,
                          height: 13,
                          width: 2,
                        ),
                        SizedBox(
                          width: 13,
                        ),
                        Text('申诉内容'),
                      ],
                    ),
                    Container(
                      height: ScreenUtil().setWidth(120),
                      padding: EdgeInsets.only(
                          left: 15, right: 15, bottom: 20, top: 10),
                      child: TextFormField(
                        // autofocus: true,
                        maxLength: 500,
                        cursorColor: Color(0xffcccccc),
                        controller: _contentController,
                        maxLines: 5,
                        decoration: InputDecoration(
                          contentPadding: EdgeInsets.all(0),
                          hintText: '请详细描述您想申诉的内容',
                          hintStyle: TextStyle(color: Color(0xffcccccc)),
                          focusedBorder: InputBorder.none,
                          border: InputBorder.none,
                          // filled: true, // 背景色
                          // fillColor: Colors.cyan.withAlpha(35),
                          // icon: Icon(Icons.person)
                        ),

                        // 校验
                        validator: (val) {
                          return val.trim().length > 0 ? null : "不能为空";
                        },
                      ),
                    ),
                    SizedBox(
                      height: 6,
                      child: Container(color: Color(0xFFF1F4FC)),
                    ),
                    SizedBox(
                      height: 6,
                    ),
                    Row(
                      children: [
                        Container(
                          color: Colours.blue_app_main,
                          height: 13,
                          width: 2,
                        ),
                        SizedBox(
                          width: 13,
                        ),
                        Text('上传图片'),
                      ],
                    ),
                    Container(
                      color: ThemeUtils.getTabsBg(context),
                      child: GridView.builder(
                        shrinkWrap: true,
                        padding: const EdgeInsets.fromLTRB(8.0, 12, 8.0, 12.0),
                        physics: NeverScrollableScrollPhysics(),
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 3, childAspectRatio: 1.18),
                        itemCount: images.length >= 6 ? 6 : images.length + 1,
                        itemBuilder: (_, index) {
                          return Stack(
                            children: <Widget>[
                              Center(
                                child: SelectedImage(
                                  image: index < images.length
                                      ? images[index]
                                      : null,
                                  onTap: () {
                                    if (index >= images.length) {
                                      selectPicker();
                                    }
                                    FocusScope.of(context)
                                        .requestFocus(FocusNode());
                                  },
                                ),
                              ),
                              index < images.length
                                  ? Positioned(
                                      top: 0,
                                      right: 0,
                                      child: GestureDetector(
                                        onTap: () {
                                          print(index);
                                          images.remove(images[index]);
                                          setState(() {});
                                        },
                                        child: Icon(
                                          const IconData(0xe651,
                                              fontFamily: "Iconfont"),
                                          size: 24.0,
                                          color: Color(0xff999999),
                                        ),
                                      ))
                                  : Container(
                                      child: null,
                                    )
                            ],
                          );
                        },
                      ),
                    ),
                    Container(
                      height: 44,
                      decoration: BoxDecoration(
                        color: Colours.blue_app_main,
                        borderRadius: BorderRadius.circular(22),
                        // gradient: const LinearGradient(
                        //     colors: [Color(0xFF00D9FF), Color(0xFF0287FF)]),
                      ),
                      margin: EdgeInsets.all(20.0),
                      width: double.infinity,
                      child: FlatButton(
                        // padding: EdgeInsets.all(15.0),
                        child: Text("提交"),
                        // color: Theme
                        //     .of(context)
                        //     .primaryColor,
                        textColor: Colors.white,
                        onPressed: () {
                          /*
                        * 如果：context不对。可以使用GlobalKey，
                        * 通过_formKey.currentState 获取FormState后，
                        * 调用validate()方法校验用户名密码是否合法，校验
                        * 通过后再提交数据。 
                        */
                          if ((_formKey.currentState as FormState).validate()) {
                            submitApply();
                          }
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
