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 'dart:io';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/widgets/text_field_item.dart';
import 'package:liftmanager/widgets/bbs_content.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'package:liftmanager/common/common.dart';
// import 'package:flustars/flustars.dart';
import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:liftmanager/utils/theme_utils.dart';

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

  final String id;

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

class PositionApplyState extends State<PositionApply> {
  List<File> images = [];

  String sexChiose = "";
  int sexChioseValue;
  List<String> sexListChiose = ['男', '女'];
  List<int> sexListValue = [1, 2];
  dynamic usreJob = {
    "infoId": 0,
    "userId": 1,
    "ability": "",
    "email": "",
    "intro": "",
    "name": "",
    "telephone": "",
    "salary": 0,
    "gender": 0
  };

  // 焦点控制
  FocusNode _focusNode1 = new FocusNode();
  GlobalKey _formKey = new GlobalKey<FormState>();

  TextEditingController _usernameController = new TextEditingController();
  TextEditingController _salaryController = new TextEditingController();
  TextEditingController _telController = new TextEditingController();
  TextEditingController _emailController = new TextEditingController();
  TextEditingController _skillController = new TextEditingController();
  TextEditingController _evaluationController = new TextEditingController();

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

    return Scaffold(
      resizeToAvoidBottomPadding: false, //不让键盘弹上去
      appBar: MyAppBar(
        centerTitle: "申请职位",
      ),
      body: GestureDetector(
        onTap: () {
          // 点击空白页面关闭键盘
          FocusScope.of(context).requestFocus(_focusNode1);
        },
        child: Stack(
          children: <Widget>[
            Container(
                child: ListView(children: <Widget>[
              Form(
                key: _formKey, //设置globalKey，用于后面获取FormState
                // autovalidate: true, //开启自动校验
                child: Column(
                  children: <Widget>[
                    TextFieldItem(
                      title: "姓名",
                      content: "",
                      controller: _usernameController,
                      // controller: TextEditingController(),
                      hintText: "请输入您的姓名",
                      onChanged: (res) {
                        //            setState(() {});
                      },
                    ),
                    ChioseThis(
                        list: sexListChiose,
                        label: "性别",
                        value: sexChiose,
                        fun: (index) {
                          setState(() {
                            sexChiose = sexListChiose[index];
                            sexChioseValue = sexListValue[index];
                          });
                          Navigator.maybePop(context);
                          FocusScope.of(context)
                                            .requestFocus(FocusNode());
                        }),
                    TextFieldItem(
                      title: "期望薪资（元/月）",
                      content: "",
                      controller: _salaryController,
                      hintText: "请输入您的期望薪资",
                      keyboardType: TextInputType.number,
                      // maxLength: 6,
                      onChanged: (res) {
                        //            setState(() {});
                      },
                      // validator: (val) {
                      //   return val.trim().length > 0 ? null : "不能为空";
                      // },
                    ),
                    TextFieldItem(
                      title: "联系方式",
                      content: "",
                      controller: _telController,
                      hintText: "请输入您的电话",
                      keyboardType: TextInputType.number,
                      onChanged: (res) {
                        //            setState(() {});
                      },
                    ),
                    TextFieldItem(
                      title: "联系邮箱",
                      content: "",
                      controller: _emailController,
                      hintText: "请输入您的邮箱",
                      onChanged: (res) {
                        //            setState(() {});
                      },
                    ),
                    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(
                            "个人技能",
                            style: TextStyle(
                              color: Color(0xff222222),
                              // fontSize:ScreenUtil().setSp(14),
                            ),
                            textAlign: TextAlign.left,
                          ),
                        ),
                      ],
                    ),
                    Container(
                      height: 120,
                      padding: EdgeInsets.only(
                          left: ScreenUtil().setWidth(15),
                          right: ScreenUtil().setWidth(15),
                          bottom: ScreenUtil().setWidth(20)),
                      child: TextFormField(
                          // autofocus: true,
                          maxLength: 50,
                          cursorColor: Color(0xffcccccc),
                          controller: _skillController,
                          maxLines: 5,
                          decoration: InputDecoration(
                            contentPadding: EdgeInsets.all(0),

                            hintText: '请输入您的个人技能',
                            hintStyle: TextStyle(
                              color: Color(0xffcccccc),
                              // fontSize: ScreenUtil().setSp(14)
                            ),
                            focusedBorder: InputBorder.none,
                            border: InputBorder.none,
                            // filled: true, // 背景色
                            // fillColor: Colors.cyan.withAlpha(35),
                            // icon: Icon(Icons.person)
                          ),

                          // 校验
                          validator: (val) {
                            return val.trim().length > 0 ? null : "不能为空";
                          }),
                    ),
                    SizedBox(
                      height: 6,
                      child: Container(color: Color(0xFFF1F4FC)),
                    ),
                    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(
                            "自我评价",
                            style: TextStyle(
                              color: Color(0xff222222),
                              // fontSize:ScreenUtil().setSp(14),
                            ),
                            textAlign: TextAlign.left,
                          ),
                        ),
                      ],
                    ),
                    Container(
                      height: ScreenUtil().setWidth(120),
                      padding: EdgeInsets.only(
                          left: ScreenUtil().setWidth(15),
                          right: ScreenUtil().setWidth(15),
                          bottom: ScreenUtil().setWidth(20)),
                      child: TextFormField(
                          // autofocus: true,
                          maxLength: 50,
                          cursorColor: Color(0xffcccccc),
                          controller: _evaluationController,
                          maxLines: 5,
                          decoration: InputDecoration(
                            contentPadding: EdgeInsets.all(0),

                            hintText: '请输入您的自我评价',
                            hintStyle: TextStyle(
                              color: Color(0xffcccccc),
                              // fontSize: ScreenUtil().setSp(14)
                            ),
                            focusedBorder: InputBorder.none,
                            border: InputBorder.none,
                            // filled: true, // 背景色
                            // fillColor: Colors.cyan.withAlpha(35),
                            // icon: Icon(Icons.person)
                          ),

                          // 校验
                          validator: (val) {
                            return val.trim().length > 0 ? null : "不能为空";
                          }),
                    ),
                    SizedBox(
                      height: 6,
                      child: Container(color: Color(0xFFF1F4FC)),
                    ),
                    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: ThemeUtils.getDialogTextFieldColor(context),
                  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,
                      onPressed: () {
                        /*
                        * 如果：context不对。可以使用GlobalKey，
                        * 通过_formKey.currentState 获取FormState后，
                        * 调用validate()方法校验用户名密码是否合法，校验
                        * 通过后再提交数据。 
                        */
                        if(_usernameController.text == null || _usernameController.text.trim()==""){
                            toasts("请输入姓名");
                            return;
                        }
                        if(sexChioseValue == null){
                          toasts("请选择性别");
                          return;
                        }
                        if(_salaryController.text == null || _salaryController.text.trim()==""){
                            toasts("请输入期望薪资");
                            return;
                        }
                        if(_telController.text == null || _telController.text.trim()==""){
                            toasts("请输入联系方式");
                            return;
                        }
                        if(_emailController.text == null || _emailController.text.trim()==""){
                            toasts("请输入联系邮箱");
                            return;
                        }
                        if(_skillController.text == null || _skillController.text.trim()==""){
                            toasts("请输入个人技能");
                            return;
                        }
                        if(_evaluationController.text == null || _evaluationController.text.trim()==""){
                            toasts("请输入自我评价");
                            return;
                        }
                        
                        RegExp exp = RegExp(r'^1[34578]\d{9}$');
                        RegExp expEmail = RegExp(r"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
                        if(!exp.hasMatch(_telController.text)){
                            toasts("请输入正确的手机号");
                            return;
                        }
                        if(!expEmail.hasMatch(_emailController.text)){
                            toasts("请输入正确的邮箱");
                            return;
                        }

                        print(_salaryController.text);

                        if ((_formKey.currentState as FormState).validate()) {
                          usreJob = {
                            "infoId": int.parse(widget.id),
                            "userId":
                                FlutterStars.SpUtil.getString(Constant.userId),
                            "ability": _skillController.text,
                            "email": _emailController.text,
                            "intro": _evaluationController.text,
                            "name": _usernameController.text,
                            "telephone": _telController.text,
                            "salary": _salaryController.text == ''
                                ? 0
                                : int.parse(_salaryController.text),
                            "gender": sexChioseValue
                          };
                          NewApiService().applyJob(usreJob, onSuccess: (res) {
                            toasts("职位申请成功");
                            NavigatorUtils.goBackWithParams(context, true);
                            bool isApply = true;
                            FastNotification.push("apply", isApply);
                            setState(() {});
                          }, onError: (code, msg) {
                            toasts(msg);
                          });
                        }
                      },
                    ),
                  ),
                ))
          ],
        ),
      ),
    );
  }
}
