import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:liftmanager/internal/account/provider/user_provider.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/utils/image_utils.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:provider/provider.dart';
import 'package:liftmanager/widgets/bbs_content.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/widgets/text_field_item.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/internal/wode/wode_router.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:image_picker/image_picker.dart';
import 'package:liftmanager/widgets/selected_image_change.dart';
import 'dart:convert';

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

  final String id;

  @override
  ArchiveState createState() => ArchiveState();
}

class ArchiveState extends State<Archive> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  UserProvider provider = UserProvider();

  TextEditingController _title = TextEditingController();
  TextEditingController _expression = TextEditingController();
  TextEditingController _solution = TextEditingController();

  List<String> images = [];

  @override
  void initState() {
    // getBountyList();
    getQuestionDetail();
    super.initState();

  }
  dynamic detailObj;
  Future getQuestionDetail() async {
    await NewApiService().getQuestionDetailAll(int.parse(widget.id),
        onSuccess: (res) {
      if (res != null) {
        detailObj = res.records[0];
        print(123456);
        print(jsonEncode(res));
        _title.text = detailObj.title;
        _expression.text = detailObj.expression;
        _solution.text = detailObj.solution;
          images = [];
          detailObj.imgs.split(",").forEach((item){
            images.add(item);
          });
          
        setState(() {});
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  List<String> bountyList = [];

  void confirmArchive() {
    if (_title.text == '') {
      toasts("请输入标题");
      return;
    }
    if (_expression.text == '') {
      toasts("请输入问题现象");
      return;
    }
    if (_solution.text == '') {
      toasts("请输入解决方案");
      return;
    }

    NewApiService().questionCollect({
      "id":detailObj!=null?detailObj.id:null,
      "liftCaseId": widget.id,
      "title": _title.text,
      "expression": _expression.text,
      "solution": _solution.text,
      "imgs": images.join(",")
    }, onSuccess: (res) {
      toasts("归档成功");
      NavigatorUtils.push(context, "${WodeRouter.orderPageMaster}?checkType=0");
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  void getBountyList() {
    NewApiService().queryConstant('reward_setting', 'reward', onSuccess: (res) {
      print(res);
      bountyList.clear();
      for (var i = 0; i < res.length; i++) {
        bountyList.add(res[i].value);
      }
      setState(() {});
    }, onError: (code, msg) {
      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(() {});
        upLoadFileOnce(_imageFile.path);
      }
    } catch (e) {
      toasts("没有权限，无法打开相册！");
    }
  }

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

  @override
  void dispose() {
    // provider.dispose();
    super.dispose();
  }

  FocusNode blankNode = FocusNode();
  
  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    return
        // Center(child:new Text("个人中心"));
        ChangeNotifierProvider<UserProvider>(
      create: (_) => provider,
      child: Scaffold(
        key: _scaffoldKey,
        resizeToAvoidBottomPadding: false,
        appBar: MyAppBar(
          centerTitle: "归档",
        ),
        body: GestureDetector(
          onTap: () {
            // 点击空白页面关闭键盘
            FocusScope.of(context).requestFocus(blankNode);
          },
          child: Consumer<UserProvider>(
            builder: (_, provider, __) {
              return Stack(
                children: <Widget>[
                  ListView(
                    padding: EdgeInsets.all(0.0),
                    children: <Widget>[
                      TextFieldItem(
                        title: "标题",
                        content: "",
                        controller: _title,
                        keyboardType: TextInputType.text,
                        // maxLength: 30,
                        hintText: "请输入标题",
                        onChanged: (res) {
                          
                        },
                      ),
                      Container(
                        decoration: BoxDecoration(
                          border: Border(
                            bottom: BorderSide(width: 0.5, color: Colours.line),
                          ),
                        ),
                        child: Column(
                          children: <Widget>[
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                Container(
                                  padding: EdgeInsets.only(
                                    left: ScreenUtil().setWidth(15),
                                    top: ScreenUtil().setWidth(10),
                                    bottom: ScreenUtil().setWidth(5),
                                  ),
                                  child: Text(
                                    "问题现象",
                                    textAlign: TextAlign.left,
                                  ),
                                ),
                              ],
                            ),
                            Container(
                              padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(15),
                                right: ScreenUtil().setWidth(15),
                                bottom: ScreenUtil().setWidth(20),
                              ),
                              child: TextFormField(
                                cursorColor: Color(0xffcccccc),
                                controller: _expression,
                                maxLines: 5,
                                maxLength: 500,
                                decoration: InputDecoration(
                                  contentPadding: EdgeInsets.all(0),
                                  hintText: '请输入问题现象',
                                  hintStyle:
                                      TextStyle(color: Color(0xffcccccc)),
                                  focusedBorder: InputBorder.none,
                                  border: InputBorder.none,
                                ),
                                // 校验
                                validator: (val) {
                                  // return val.trim().length > 0 ? null : "不能为空";
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        decoration: BoxDecoration(
                          border: Border(
                            bottom: BorderSide(width: 0.5, color: Colours.line),
                          ),
                        ),
                        child: Column(
                          children: <Widget>[
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                Container(
                                  padding: EdgeInsets.only(
                                    left: ScreenUtil().setWidth(15),
                                    top: ScreenUtil().setWidth(10),
                                    bottom: ScreenUtil().setWidth(5),
                                  ),
                                  child: Text(
                                    "解决方法",
                                    textAlign: TextAlign.left,
                                  ),
                                ),
                              ],
                            ),
                            Container(
                              padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(15),
                                right: ScreenUtil().setWidth(15),
                                bottom: ScreenUtil().setWidth(20),
                              ),
                              child: TextFormField(
                                cursorColor: Color(0xffcccccc),
                                controller: _solution,
                                maxLines: 5,
                                maxLength: 500,
                                decoration: InputDecoration(
                                  contentPadding: EdgeInsets.all(0),
                                  hintText: '请输入解决方法',
                                  hintStyle:
                                      TextStyle(color: Color(0xffcccccc)),
                                  focusedBorder: InputBorder.none,
                                  border: InputBorder.none,
                                ),
                                // 校验
                                validator: (val) {
                                  // return val.trim().length > 0 ? null : "不能为空";
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
                      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: images.length >= 3 ? 3 : images.length + 1,
                          itemBuilder: (_, index) {
                            return Stack(
                              children: <Widget>[
                                Center(
                                  child: SelectedImage(
                                    image: index < images.length
                                        ? images[index]
                                        : null,
                                    onTap: () {
                                      if (index >= images.length) {
                                        selectPicker();
                                      }
                                      FocusScope.of(context)
                                          .requestFocus(FocusNode());
                                    },
                                  ),
                                ),
                                index < images.length
                                    ? Positioned(
                                        top: 0,
                                        right: 0,
                                        child: GestureDetector(
                                          onTap: () {
                                            print(index);
                                            images.remove(images[index]);
                                            setState(() {});
                                          },
                                          child: Icon(
                                            IconData(0xe62a,
                                                fontFamily: "myfont"),
                                            size: 24.0,
                                            color: Color(0xff999999),
                                          ),
                                        ))
                                    : Container(
                                        child: null,
                                      )
                              ],
                            );
                          },
                        ),
                      ),
                      // ChioseThis(
                      //   list: bountyList,
                      //   label: "赏金",
                      //   value: '',
                      //   fun: (index) {
                      //     print(index);
                      //     Navigator.maybePop(context);
                      //   },
                      // ),
                      // InkWell(
                      //   onTap: () {
                      //     showPicker(context);
                      //   },
                      //   child: Container(
                      //     height: 50.0,
                      //     margin: const EdgeInsets.only(left: 16.0),
                      //     width: double.infinity,
                      //     decoration: BoxDecoration(
                      //         border: Border(
                      //       bottom: Divider.createBorderSide(context, width: 0.6),
                      //     )),
                      //     child: Row(
                      //       children: <Widget>[
                      //         Padding(
                      //           padding: const EdgeInsets.only(right: 5.0),
                      //           child: Text("赏金"),
                      //         ),
                      //         Expanded(
                      //           flex: 1,
                      //           child: Text(""),
                      //         ),
                      //         Text("请选择"),
                      //         Text(">"),
                      //         Gaps.hGap16
                      //       ],
                      //     ),
                      //   ),
                      // ),
                      SizedBox(height: ScreenUtil().setWidth(80))
                    ],
                  ),
                  Positioned(
                    bottom: 0,
                    left: 0,
                    child: Container(
                      width: width,
                      padding: EdgeInsets.only(
                        top: ScreenUtil().setWidth(15),
                        bottom: ScreenUtil().setWidth(15),
                        left: ScreenUtil().setWidth(25),
                        right: ScreenUtil().setWidth(25),
                      ),
                      color: Colors.white,
                      child: Container(
                        height: ScreenUtil().setWidth(44),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(
                            ScreenUtil().setWidth(22),
                          ),
                          gradient: const LinearGradient(
                            colors: [Color(0xFF00D9FF), Color(0xFF0287FF)],
                          ),
                        ),
                        child: FlatButton(
                          // padding: EdgeInsets.all(15.0),
                          child: Text("立即归档"),
                          textColor: Colors.white,
                          // textColor: Colors.white,
                          onPressed: () {
                            if(_title.text.length > 30){
                              toasts("标题长度不得大于30！");
                            }else {
                              confirmArchive();
                            }
                            
                          },
                        ),
                      ),
                    ),
                  )
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
