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

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

  final String id;

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

class ConfirmOrderState extends State<ConfirmOrder> {
  String videoUrl;
  String imagesUrl;

  @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.pickVideo(
        source: key == 1 ? ImageSource.camera : ImageSource.gallery,
      );
      if (_imageFile != null) {
        upLoadFileOnce(_imageFile.path);
      }
    } catch (e) {
      toasts("没有权限，无法打开相册！");
    }
  }

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

  submitApply() {
    if (videoUrl == null || videoUrl == '') {
      toasts("请上传视频");
      return;
    }
    showLoading(context);
    NewApiService().chargeMakeSureCase({
      "id": widget.id,
      "afterRepair": videoUrl,
    }, onSuccess: (res) {
      dismissLoading(context);
      toasts("确认完成");
      NavigatorUtils.push(context, "${WodeRouter.orderPageMaster}?checkType=0");
      setState(() {});
    }, onError: (code, msg) {
      dismissLoading(context);
      toasts(msg);
    });
  }

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

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

    return Scaffold(
      resizeToAvoidBottomPadding: false, //不让键盘弹上去
      appBar: MyAppBar(
        centerTitle: "确认订单",
      ),
      body: Container(
        child: ListView(
          children: <Widget>[
            Form(
              key: _formKey, //设置globalKey，用于后面获取FormState
              // autovalidate: true, //开启自动校验
              child: Column(
                children: <Widget>[
                  Container(
                width: width,
                padding: EdgeInsets.only(left:15),
                child: Text(
                                                        "(建议时长3分钟，建议大小50M)",
                                                        style: TextStyle(
                                                          color: Colors.red,
                                                            fontSize:
                                                                ScreenUtil()
                                                                    .setSp(14),
                                                            ),
                                                            textAlign: TextAlign.left,
                                                      ),
              ),
                  Container(
                    color: Colors.white,
                    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: 1,
                      itemBuilder: (_, index) {
                        return Stack(
                          children: <Widget>[
                            Center(
                              child: SelectedImage(
                                image: imagesUrl,
                                index: index,
                                onTap: () {
                                  selectPicker();
                                  FocusScope.of(context).requestFocus(FocusNode());
                                },
                              ),
                            ),
                            videoUrl != null
                                ? Positioned(
                                    top: 0,
                                    right: 0,
                                    child: GestureDetector(
                                      onTap: () {
                                        print(index);
                                        videoUrl = null;
                                        imagesUrl = null;
                                        setState(() {});
                                      },
                                      child: Icon(
                                        IconData(0xe62a, fontFamily: "myfont"),
                                        size: 24.0,
                                        color: Color(0xff999999),
                                      ),
                                    ),
                                  )
                                : Container(
                                    child: null,
                                  )
                          ],
                        );
                      },
                    ),
                  ),
                  Container(
                    height: ScreenUtil().setWidth(44),
                    decoration: BoxDecoration(
                      borderRadius:
                          BorderRadius.circular(ScreenUtil().setWidth(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();
                        }
                      },
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
