import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:liftmanager/net/api_service.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/my_button.dart';
import 'package:liftmanager/widgets/selected_image.dart';

class HeavyEndPage extends StatefulWidget {
  HeavyEndPage(this.projectId);

  final String projectId;

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

class HeavyEndState extends State<HeavyEndPage> {
  List<File> images = [];
  ///合格证
  _saveFinish() {
    if(images.length == 0){
      toasts("请上传竣工单");
      return;
    }
    showLoading(context, "正在提交...");
    ///上传保养图片
    ApiService(context: context).uploadMore(images, onSuccess: (imgs) {
      ///提交
      ApiService(context: context).capitalCompleted(widget.projectId,imgs,onSuccess: (res){
        dismissLoading(context);
        if(res!=null){
          NavigatorUtils.goBack(context);
        }
      },onError: (code,msg){

      });
    }, onError: (code, msg) {
      dismissLoading(context);
      toasts(msg);
    });
  }

  ///选择图片
  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(() {});
      }
    } catch (e) {
      toasts("没有权限，无法打开相册！");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeUtils.getTabsBg(context),
      appBar: MyAppBar(
        centerTitle: "提交竣工单",
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
            child: 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 >= 9 ? 9 : images.length + 1,
                itemBuilder: (_, index) {
                  return Stack(
                    children: <Widget>[
                      Center(
                        child: SelectedImage(
                            image: index < images.length ? images[index] : null,
                            onTap: () {
                              selectPicker();
                            }),
                      )
                    ],
                  );
                },
              )),
          Container(
              child: Padding(
            padding: const EdgeInsets.all(16),
            child: MyButton(
              fontSize: 14,
              onPressed: () {
                _saveFinish();
              },
              text: "确定",
            ),
          ))
        ],
      ),
    );
  }
}
