import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutterappfuyou/code/base/YSNetWorking.dart';
import 'package:image_picker/image_picker.dart';

import 'base/YSBase.dart';
import 'base/YSTools.dart';

class YSFeedback extends StatefulWidget {
  @override
  _YSFeedbackState createState() => _YSFeedbackState();
}

class _YSFeedbackState extends State<YSFeedback> {
  TextEditingController _content = TextEditingController();
  TextEditingController _phone = TextEditingController();
  List urls = [];
  List paths = [];
  final ImagePicker _picker = ImagePicker();
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ystitle: '意见反馈',
      yschild: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(topLeft: Radius.circular(20),topRight: Radius.circular(20))
        ),
        child: SingleChildScrollView(
          padding: EdgeInsets.all(20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('详情',style: TextStyle(fontSize: 14,color: Color(0xFF292929)),),
              Container(
                height: 150,
                child: CupertinoTextField(
                  placeholder: '请输入问题描述（10~500 个字内）',
                  maxLength: 500,
                  style: TextStyle(fontSize: 14,color: Color(0xFF292929)),
                  placeholderStyle: TextStyle(fontSize: 14,color: Color(0xFF808080)),
                  maxLines: 30,
                  decoration: BoxDecoration(),
                  controller: _content,
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 10),
                width: MediaQuery.of(context).size.width,
                height: 1.5,
                child: Image.asset('lib/images/line.png'),
              ),
              Container(
                height: 50,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('联系方式',style: TextStyle(fontSize: 14,color: Color(0xFF292929)),),
                    Container(
                      width: MediaQuery.of(context).size.width-100,
                      child: CupertinoTextField(
                        placeholder: '请输入',
                        style: TextStyle(fontSize: 14,color: Color(0xFF292929)),
                        placeholderStyle: TextStyle(fontSize: 14,color: Color(0xFF808080)),
                        decoration: BoxDecoration(),
                        textAlign: TextAlign.end,
                        controller: _phone,
                        keyboardType: TextInputType.phone,
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(bottom: 15),
                width: MediaQuery.of(context).size.width,
                height: 1.5,
                child: Image.asset('lib/images/line.png'),
              ),
              Text('图片',style: TextStyle(fontSize: 14,color: Color(0xFF292929)),),
              Container(
                margin: EdgeInsets.only(top: 10,bottom: 100),
                height: (MediaQuery.of(context).size.width-60)/5,
                width: MediaQuery.of(context).size.width-40,
                child: ListView.separated(
                  itemBuilder: (context,index){
                    return GestureDetector(
                      onTap: (){
                        if(index<urls.length){

                        }else{
                          showCupertinoModalPopup(
                              context: context,
                              builder: (context) {
                                return CupertinoActionSheet(
                                  actions: <Widget>[
                                    CupertinoActionSheetAction(
                                      child: Text('相机'),
                                      onPressed: () {
                                        Navigator.pop(context);
                                        _picker.getImage(source: ImageSource.camera,imageQuality: 50).then((value) => {
                                          _uploadImageData(value)
                                        });
                                      },
                                    ),
                                    CupertinoActionSheetAction(
                                      child: Text('相册'),
                                      onPressed: () {
                                        Navigator.pop(context);
                                        _picker.getImage(source: ImageSource.gallery,imageQuality: 50).then((value) => {
                                          _uploadImageData(value)
                                        });
                                      },
                                    ),
                                  ],
                                  cancelButton: CupertinoActionSheetAction(
                                    child: Text('取消'),
                                    onPressed: () {
                                      Navigator.pop(context);
                                    },
                                  ),
                                );
                              }
                          );
                        }
                      },
                      child: index==urls.length?Container(
                        height: (MediaQuery.of(context).size.width-60)/5,
                        width: (MediaQuery.of(context).size.width-60)/5,
                        decoration: BoxDecoration(
                          color: Color(0xFFEFEFEF),
                          borderRadius: BorderRadius.all(Radius.circular(3))
                        ),
                        child: Icon(Icons.add,size: 20,color: Color(0xFFB3B3B3),),
                      ):Container(
                          height: (MediaQuery.of(context).size.width-60)/5,
                          width: (MediaQuery.of(context).size.width-60)/5,
                          decoration: BoxDecoration(
                            color: Color(0xFFEFEFEF),
                            borderRadius: BorderRadius.all(Radius.circular(3)),
                            image: DecorationImage(image: NetworkImage('${urls[index]}'),fit: BoxFit.fill,)
                          ),
                      ),
                    );
                  },
                  separatorBuilder: (context,index){
                    return Container(height: 70,width: 5,color: Colors.white,);
                  },
                  itemCount: urls.length+1,
                  scrollDirection: Axis.horizontal,
                ),
              ),
              CupertinoButton(
                padding: EdgeInsets.all(0),
                child: Container(
                  margin: EdgeInsets.only(left: 55),
                  width: MediaQuery.of(context).size.width-150,
                  height: 40,
                  decoration: BoxDecoration(
                      color: Color(0xFFEA6C8F),
                      borderRadius: BorderRadius.all(Radius.circular(20))
                  ),
                  alignment: Alignment.center,
                  child: Text('提交',style: TextStyle(fontSize: 16,color: Colors.white,decoration: TextDecoration.none),),
                ),
                onPressed: (){
                  _postFeedbackData();
                },
              )
            ],
          ),
        ),
      ),
    );
  }

  _uploadImageData(var image) async{
    ysUploadFile(context,path: image.path,type: 'advice',setter: (value){
      paths.add('${value['path']}');
      urls.add('${value['url']}');
      setState(() {});
    });
    // var dict = await ysRequestHttpNoLoading(context, requestType.get, 'upQiniuToken', {'type':'advice'});
    // if(dict!=null){
    //   var result = await syStorage.upload('${image.path}', '${dict['token']}', '${dict['path']}');
    //   if(result.success==true){
    //     paths.add('${dict['path']}');
    //     setState(() {
    //       urls.add('${dict['url']}');
    //     });
    //   }
    // }
  }


  _postFeedbackData() async{
    if(_content.text==null || _content.text.isEmpty){
      ysFlutterToast(context, '请输入反馈内容');
      return;
    }
    if(_content.text.length<10){
      ysFlutterToast(context, '反馈内容不能少于10个字');
      return;
    }
    Map request = Map();
    request['body'] = _content.text;
    request['contact'] = _phone.text;
    request['covers'] = paths;
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'i/advice', request);
    if(dict!=null){
      Navigator.pop(context);
    }
  }
}
