import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:liftmanager/internal/bbs/page/jubao_type.dart';
import 'package:liftmanager/internal/team/page/input_text_page.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/app_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/click_item.dart';
import 'package:liftmanager/widgets/selected_image_change.dart';
import 'package:liftmanager/widgets/my_button.dart';

import 'package:liftmanager/widgets/text_field_item.dart';

class JuBaoPage extends StatefulWidget {
  JuBaoPage({this.toUserId});

  String toUserId;
  @override
  State<StatefulWidget> createState() {
    return JuBaoPageState();
  }
}

class JuBaoPageState extends State<JuBaoPage> {
  File _imageFile;
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  final FocusNode _nodeText3 = FocusNode();

  TextEditingController _teamNameController = TextEditingController();
  TextEditingController _nameController = TextEditingController();
  TextEditingController _phoneController = TextEditingController();
  TextEditingController _remarkController = TextEditingController();
  String _remarks = "";
  String _typeText = "";
  String _typeIndex = "";
  List<String> imagesUrl = [];
  void _getImage(int key) async {
    try {
      var _imageFile = await ImagePicker.pickImage(
          source: key == 1 ? ImageSource.camera : ImageSource.gallery,
          maxWidth: 800,
          imageQuality: 95);
      print(_imageFile);
      print(3333);
      if (_imageFile != null) {
        // images.add(_imageFile);
        upLoadFileOnce(_imageFile.path);
        // setState(() {});
      }
    } catch (e) {
      toasts("没有权限，无法打开相册！");
    }
  }

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

  ///选择图片
  void selectPicker(type) {
    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: () {
                    if (type == "image") {
                      _getImage(value == '拍照' ? 1 : 0);
                    } else if (type == "video") {
                      // _getVideo(value == '拍照' ? 1 : 0);
                    }
                    Navigator.of(context).pop();
                  },
                );
              }).toList());
        });
  }

  ///创建团队
  createTeamAction() {
    var remark = _remarkController.text.toString().trim();
    var name = _nameController.text.toString().trim();
    var phone = _phoneController.text.toString().trim();

    if (remark.isEmpty) {
      toasts("请描述原因");
      return;
    }
    if (name.isEmpty) {
      toasts("请填写联系人姓名");
      return;
    }
    if (phone.isEmpty) {
      toasts("请填写联系电话");
      return;
    }

    showLoading(context, "正在提交...");

    // {imgs,
    //   name,
    //   mobile,
    //   comment,
    //   type,
    //   complainedUserId,
    String temp = '';
    for (var item in imagesUrl) {
      temp += item;
      temp += ',';
    }
    ApiService(context: context).jubao(
        imgs: temp,
        name: name,
        mobile: phone,
        comment: remark,
        type: _typeIndex,
        complainedUserId: widget.toUserId,
        onSuccess: (data) {
          showAlert(context, "提示", "举报成功！", "确定", () {
            dismissLoading(context);
            NavigatorUtils.goBack(context);
            NavigatorUtils.goBackWithParams(context, true);
          });
        },
        onError: (code, msg) {
          dismissLoading(context);
          toasts(msg);
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //resizeToAvoidBottomPadding: false,
      appBar: const MyAppBar(
        centerTitle: "举报",
      ),
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: defaultTargetPlatform == TargetPlatform.iOS
                  ? FormKeyboardActions(
                      child: Container(
                      color: ThemeUtils.getTabsBg(context),
                      child: _buildBody(),
                    ))
                  : SingleChildScrollView(
                      child: Container(
                      color: ThemeUtils.getTabsBg(context),
                      child: _buildBody(),
                    )),
            )
          ],
        ),
      ),
    );
  }

  _buildBody() {
    return Padding(
        padding: const EdgeInsets.symmetric(vertical: 10.0),
        child: Stack(
          children: [
            Column(
              // crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                ClickItem(
                  title: "举报理由",
                  content: _typeText,
                  onTap: () {
                    Navigator.of(context).push(MaterialPageRoute(
                        builder: (context) => JuBaoTypePage(
                              backObj: (val, index) {
                                _typeText = val;
                                _typeIndex = index.toString();
                                setState(() {});
                              },
                            )));
                  },
                ),
                Container(
                  // width: width,
                  padding: EdgeInsets.only(left: 15, top: 10),
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "聊天证据",
                    style: TextStyle(
                      fontSize: ScreenUtil().setSp(14),
                    ),
                    textAlign: TextAlign.left,
                  ),
                ),
                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:
                          imagesUrl.length >= 9 ? 9 : imagesUrl.length + 1,
                      itemBuilder: (_, index) {
                        return Stack(
                          children: <Widget>[
                            Center(
                              child: SelectedImage(
                                  image: index < imagesUrl.length
                                      ? imagesUrl[index]
                                      : null,
                                  index: index,
                                  onTap: () {
                                    if (index >= imagesUrl.length) {
                                      selectPicker("image");
                                    }
                                    FocusScope.of(context)
                                        .requestFocus(FocusNode());
                                    print(index);
                                    print(imagesUrl);
                                  }),
                            ),
                            index < imagesUrl.length
                                ? Positioned(
                                    top: 0,
                                    right: 0,
                                    child: GestureDetector(
                                      onTap: () {
                                        print(index);
                                        imagesUrl.remove(imagesUrl[index]);
                                        setState(() {});
                                      },
                                      child: Icon(
                                        const IconData(0xe651,
                                            fontFamily: "Iconfont"),
                                        size: 24.0,
                                        color: Color(0xff999999),
                                      ),
                                    ))
                                : Container(
                                    child: null,
                                  )
                          ],
                        );
                      },
                    )),

                Container(
                  height: 120,
                  padding: EdgeInsets.only(left: 15, right: 15, bottom: 10),
                  child: TextFormField(
                      // autofocus: true,
                      maxLength: 100,
                      cursorColor: Color(0xffcccccc),
                      controller: _remarkController,
                      maxLines: 5,
                      decoration: InputDecoration(
                        contentPadding: EdgeInsets.all(0),

                        hintText: '详细描述',
                        hintStyle: TextStyle(
                          color: Color(0xffcccccc),
                          fontSize: ScreenUtil().setSp(13),
                        ),
                        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 : "不能为空";
                      }),
                ),
                TextFieldItem(
                    focusNode: _nodeText2,
                    title: "联系人",
                    controller: _nameController,
                    hintText: "填写联系人姓名"),
                TextFieldItem(
                    focusNode: _nodeText3,
                    title: "联系方式",
                    controller: _phoneController,
                    hintText: "填写联系电话号码"),
                // Expanded(child: Container()),
                SizedBox(
                  height: 100,
                ),
              ],
            ),
            Positioned(
              bottom: 5,
              left: 5,
              right: 5,
              child: MyButton(
                backColor: Colours.blue_app_main,
                onPressed: () {
                  createTeamAction();
                },
                text: "提交",
              ),
            )
          ],
        ));
  }
}
