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

class YSAddDiary extends StatefulWidget {
  @override
  _YSAddDiaryState createState() => _YSAddDiaryState();
}

class _YSAddDiaryState extends State<YSAddDiary> {
  int selectedIndex = 9999;
  String tagStr,locationStr;
  List tags = [];
  final ImagePicker _picker = ImagePicker();
  List images = [];
  List paths = [];
  TextEditingController _content = TextEditingController();
  @override
  void initState() {
    Future.delayed(Duration(seconds: 0)).then((value){
      _getTagListData();
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ystitle: '新增日记',
      ysright: CupertinoButton(
        padding: EdgeInsets.all(0),
        child: Container(
          height: 30,
          width: 55,
          decoration: BoxDecoration(
            color: Color(0xFFFFEB3B),
            border: Border.all(color: Color(0xFF292929),width: 1),
            borderRadius: BorderRadius.all(Radius.circular(20))
          ),
          alignment: Alignment.center,
          child: Text('发表',style: TextStyle(fontSize: 14,color: Color(0xFF292929),decoration: TextDecoration.none),),
        ),
        onPressed: (){
          _postDiaryData();
        },
      ),
      yschild: Container(
        color: Colors.white,
        child: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                width: MediaQuery.of(context).size.width,
                height: 120,
                margin: EdgeInsets.all(15),
                color: Colors.white,
                child: CupertinoTextField(
                  placeholder: '记录生活的点点滴滴',
                  style: TextStyle(fontSize: 14,color: Color(0xFF292929),decoration: TextDecoration.none),
                  maxLines: 30,
                  decoration: BoxDecoration(),
                  placeholderStyle: TextStyle(fontSize: 14,color: Color(0xFF808080),decoration: TextDecoration.none),
                  controller: _content,
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: 15,right: 15,bottom: 50),
                height: (MediaQuery.of(context).size.width-42)/3,
                child: GridView.builder(
                  scrollDirection: Axis.horizontal,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 1,mainAxisSpacing: 6),
                  itemBuilder: (context,index){
                    return GestureDetector(
                      onTap: (){
                        if(index<images.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==images.length?Container(
                        height: (MediaQuery.of(context).size.width-42)/3,
                        width: (MediaQuery.of(context).size.width-42)/3,
                        color: Color(0xFFEFEFEF),
                        child: Icon(Icons.add,size: 40,color: Color(0xFF8A8A8A),),
                      ):Container(
                        height: (MediaQuery.of(context).size.width-42)/3,
                        width: (MediaQuery.of(context).size.width-42)/3,
                        color: Color(0xFFEFEFEF),
                        child: Image(image: NetworkImage('${images[index]}'),fit: BoxFit.fill,)
                      ),
                    );
                  },
                  itemCount: images.length+1,
                ),
              ),
              Container(
                width: MediaQuery.of(context).size.width,
                height: 1.5,
                child: Image.asset('lib/images/line.png'),
              ),
              CupertinoButton(
                padding: EdgeInsets.all(0),
                child: Container(
                  height: 50,
                  width: MediaQuery.of(context).size.width,
                  margin: EdgeInsets.only(left: 15,right: 15),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Container(width: 20,height: 20,margin: EdgeInsets.only(right: 15,left: 30),child: Image.asset('lib/images/tag.png'),),
                          Text(tagStr==null?'添加标签':tagStr,style: TextStyle(fontSize: 14,color: Color(0xFF292929),decoration: TextDecoration.none),)
                        ],
                      ),
                      Icon(Icons.keyboard_arrow_right,size: 20,color: Color(0xFFAEB3BD),)
                    ],
                  ),
                ),
                onPressed: (){
                  showModalBottomSheet(
                    context: context,
                    backgroundColor: Colors.transparent,
                    builder: (context){
                      return StatefulBuilder(
                        builder: (context,setYSState){
                          return Container(
                            height: 274,
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                CupertinoButton(
                                  padding: EdgeInsets.all(0),
                                  child: Container(
                                    height: 20,
                                    child: Image.asset('lib/images/off.png'),
                                  ),
                                  onPressed: (){
                                    Navigator.pop(context);
                                  },
                                ),
                                Container(
                                  height: 230,
                                  decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.only(topLeft: Radius.circular(20),topRight: Radius.circular(20))
                                  ),
                                  child: Column(
                                    children: [
                                      Container(
                                        width: MediaQuery.of(context).size.width,
                                        padding: EdgeInsets.only(left: 15,right: 15),
                                        height: 48.5,
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [
                                            Text('选择标签',style: TextStyle(fontSize: 14,color: Color(0xFF292929),decoration: TextDecoration.none),),
                                            CupertinoButton(
                                              padding: EdgeInsets.all(0),
                                              child: Text('完成',style: TextStyle(fontSize: 14,color: Color(0xFF4CC17C),decoration: TextDecoration.none),),
                                              onPressed: (){
                                                Navigator.pop(context);
                                                setState(() {
                                                  if(selectedIndex==tags.length){
                                                    getStringWidget(1);
                                                  }else{
                                                    tagStr = tags[selectedIndex]['name'];
                                                  }
                                                });
                                              },
                                            )
                                          ],
                                        ),
                                      ),
                                      Container(
                                        width: MediaQuery.of(context).size.width,
                                        height: 1.5,
                                        child: Image.asset('lib/images/line.png'),
                                      ),
                                      Container(
                                        width: MediaQuery.of(context).size.width,
                                        padding: EdgeInsets.only(left: 15,right: 15,top: 20,bottom: 20),
                                        height: 180,
                                        child: GridView.builder(
                                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3,crossAxisSpacing: 20,mainAxisSpacing: 20,childAspectRatio: 0.3),
                                          itemBuilder: (context,index){
                                            return GestureDetector(
                                              onTap: (){
                                                if(index==tags.length){
                                                  Navigator.pop(context);
                                                  getStringWidget(1);
                                                }else{
                                                  setYSState(() {
                                                    selectedIndex = index;
                                                  });
                                                }
                                              },
                                              child: Container(
                                                padding: EdgeInsets.all(5),
                                                alignment: Alignment.center,
                                                child: Text(tags.length==index?'自定义':tags[index]['name'],style: TextStyle(fontSize: 14,color: selectedIndex==index?Color(0xFFFF6688):Color(0xFF292929),
                                                    decoration: TextDecoration.none),maxLines: 1,textAlign: TextAlign.center,),
                                                decoration: BoxDecoration(
                                                    borderRadius: BorderRadius.all(Radius.circular(3)),
                                                    border: Border.all(color: selectedIndex==index?Color(0xFFFF6688):Color(0xFFB3B3B3),width: 0.5)
                                                ),
                                              ),
                                            );
                                          },
                                          scrollDirection: Axis.horizontal,
                                          itemCount: tags.length+1,
                                        ),
                                      )
                                    ],
                                  ),
                                )
                              ],
                            ),
                          );
                        },
                      );
                    }
                  );
                },
              ),
              Container(
                width: MediaQuery.of(context).size.width-90,
                margin: EdgeInsets.only(left: 65),
                height: 1.5,
                child: Image.asset('lib/images/line.png'),
              ),
              CupertinoButton(
                padding: EdgeInsets.all(0),
                child: Container(
                  height: 50,
                  width: MediaQuery.of(context).size.width,
                  margin: EdgeInsets.only(left: 15,right: 15),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Container(width: 20,height: 20,margin: EdgeInsets.only(right: 15,left: 30),child: Image.asset('lib/images/location.png'),),
                          Text(locationStr==null?'添加位置':locationStr,style: TextStyle(fontSize: 14,color: Color(0xFF292929),decoration: TextDecoration.none),)
                        ],
                      ),
                      Icon(Icons.keyboard_arrow_right,size: 20,color: Color(0xFFAEB3BD),)
                    ],
                  ),
                ),
                onPressed: (){
                  getStringWidget(2);
                },
              ),
              Container(
                width: MediaQuery.of(context).size.width-90,
                margin: EdgeInsets.only(left: 65),
                height: 1.5,
                child: Image.asset('lib/images/line.png'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _getTagListData() async{
    SharedPreferences prefer = await SharedPreferences.getInstance();
    var list = await ysRequestHttpNoLoading(context, requestType.get, 'basic/Tag', {'category_id':prefer.getInt('chapters')+1});
    if(list!=null){
      tags = list;
    }
  }

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

  _postDiaryData() async{
    if(images.length==0&&_content.text==null){
      ysFlutterToast(context, '请添加内容信息');
      return;
    }
    Map request = Map();
    SharedPreferences prefer = await SharedPreferences.getInstance();
    int chapter = prefer.getInt('chapters')+1;
    request['category_id'] = chapter;
    if(chapter>2){
      request['child_id'] = prefer.getInt('childId');
    }
    if(_content.text!=null){
      request['body'] = _content.text;
    }
    if(paths.length>0){
      request['covers'] = paths;
    }
    if(locationStr!=null){
      request['position'] = locationStr;
    }
    if(tagStr!=null){
      request['tag'] = tagStr;
    }
    Map dict = await ysRequestHttp(context, requestType.post, 'diary/diarize', request);
    if(dict!=null){
      Navigator.of(context).pop('确定');
    }
  }

  getStringWidget(int type){
    TextEditingController textController = TextEditingController();
    showDialog(context: context,builder: (context){
      return Dialog(
        backgroundColor: Colors.transparent,
        child: StatefulBuilder(
          builder: (context,setYSState){
            return Container(
              width: MediaQuery.of(context).size.width,
              padding: EdgeInsets.all(15),
              height: 150,
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(10))
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(type==1?'添加标签':'添加位置',style: TextStyle(fontSize: 14,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                  Container(
                    height: 30,
                    width: MediaQuery.of(context).size.width-30,
                    child: CupertinoTextField(
                      style: TextStyle(fontSize: 13,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                      placeholderStyle: TextStyle(fontSize: 13,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                      placeholder: type==1?'请输入标签':'请输入位置',
                      controller: textController,
                      decoration: BoxDecoration(),
                    ),
                    //Text('chooseDate',style: TextStyle(fontSize: 13,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                    decoration: BoxDecoration(
                        border: Border(bottom: BorderSide(width: 0.5,color: Color(0xFFD7D7D7)))
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(),
                      Row(
                        children: [
                          CupertinoButton(
                            padding: EdgeInsets.all(0),
                            child: Text('取消',style: TextStyle(fontSize: 13,color: Color(0xFF8E1B3C),decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                            onPressed: (){
                              Navigator.pop(context);
                            },
                          ),
                          CupertinoButton(
                            padding: EdgeInsets.all(0),
                            child: Text('确定',style: TextStyle(fontSize: 13,color: Color(0xFF8E1B3C),decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                            onPressed: (){
                              Navigator.pop(context);
                              if(textController.value.text.length>0){
                                setState(() {
                                  if(type==1){
                                    tagStr = textController.value.text;
                                  }else{
                                    locationStr = textController.value.text;
                                  }
                                });
                              }
                            },
                          )
                        ],
                      )
                    ],
                  )
                ],
              ),
            );
          },
        ),
      );
    });
  }
}
