import 'dart:convert';
import 'dart:io';

import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/internal/bbs/page/tab/position/label_collection.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/iconfont.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/bbs_content.dart';
import 'package:liftmanager/widgets/text_field_item.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];

  List experienceRangeList = ['1年以下', '1年-3年', '3年-5年', '5年-10年', '10年以上'];
  String experienceRangeSelected = '';
  List<String> salaryRangeList = [
    '1千以下',
    '1千-2千',
    '2千-4千',
    '4千-6千',
    '6千-8千',
    '8千-1万',
    '1万-1.5万',
    '1.5万以上'
  ];
  String salaryRangeSelected = '';

  String birthdaySelected = '';

  List<String> selectedLabels = [];

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

  TextEditingController _usernameController = TextEditingController();
  TextEditingController _telController = TextEditingController();
  TextEditingController _wechatController = TextEditingController();
  TextEditingController _evaluationController = TextEditingController();

  @override
  void initState() {
    super.initState();

    NewApiService().getResume(
        onError: (code, msg) {},
        onSuccess: (res) {
          setState(() {
            try {
              _usernameController.text = res.name;
              sexChioseValue = res.gender;
              sexChiose = sexListChiose[sexChioseValue - 1];
              birthdaySelected = res.birthday ?? '';
              _telController.text = res.telephone;
              _wechatController.text = res.wechat;
              experienceRangeSelected = res.workingTime ?? '';
              salaryRangeSelected = res.salary ?? '';
              _evaluationController.text = res.intro;
              selectedLabels.addAll((json.decode(res.ability) as List<dynamic>).cast<String>());
            } catch (e){
                print(e);
            }
          });
        });
  }

  @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(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    TextFieldItem(
                      title: "姓名",
                      content: "",
                      isMust: true,
                      controller: _usernameController,
                      hintText: "请输入",
                      onChanged: (res) {
                        //            setState(() {});
                      },
                    ),
                    ChioseThis(
                        list: sexListChiose,
                        label: "性别",
                        isMust:true,
                        value: sexChiose,
                        fun: (index) {
                          setState(() {
                            sexChiose = sexListChiose[index];
                            sexChioseValue = sexListValue[index];
                          });
                          Navigator.maybePop(context);
                          FocusScope.of(context).requestFocus(FocusNode());
                        }),
                    DatePickerInputField(
                      label: '出生年月',
                      value: birthdaySelected,
                      onSelectionConfirmed: (value) {
                        setState(() {
                          birthdaySelected = value;
                        });
                      },
                    ),
                    TextFieldItem(
                      title: "联系电话",
                      content: "",
                      isMust: true,
                      controller: _telController,
                      hintText: "请输入",
                      keyboardType: TextInputType.number,
                      onChanged: (res) {
                        //            setState(() {});
                      },
                    ),
                    TextFieldItem(
                      title: "微信号",
                      content: "",
                      controller: _wechatController,
                      hintText: "请输入",
                      keyboardType: TextInputType.text,
                      onChanged: (res) {
                        //            setState(() {});
                      },
                    ),
                    ChiosePicker(
                        range: experienceRangeList,
                        label: "从业时间",
                        value: experienceRangeSelected,
                        onConfirm: (value, index) {
                          setState(() {
                            experienceRangeSelected = value;
                          });
                          Navigator.maybePop(context);
                          FocusScope.of(context).requestFocus(FocusNode());
                        }),
                    ChiosePicker(
                      range: salaryRangeList,
                      label: '期望薪资',
                      isMust:true,
                      value: salaryRangeSelected,
                      onConfirm: (value, index) {
                        setState(() {
                          salaryRangeSelected = value;
                        });
                        Navigator.maybePop(context);
                        FocusScope.of(context).requestFocus(FocusNode());
                      },
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    CommonSectionHeader(
                      title: '个人标签',
                      fontSize: 14,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Container(
                      // height: 120,
                      padding: EdgeInsets.only(
                          left: ScreenUtil().setWidth(15),
                          right: ScreenUtil().setWidth(15),
                          bottom: ScreenUtil().setWidth(20)),
                      child: labelSection(),
                    ),
                    SizedBox(
                      height: 1,
                      child: Container(color: Color(0xFFF1F4FC)),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    CommonSectionHeader(
                      title: '其他介绍',
                      isMust:true,
                      fontSize: 14,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    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: 13,
                            ),
                            focusedBorder: InputBorder.none,
                            border: InputBorder.none,
                          ),

                          // 校验
                          validator: (val) {
                            return val.trim().length > 0 ? null : "不能为空";
                          }),
                    ),
                    SizedBox(
                      height: 1,
                      child: Container(color: Color(0xFFF1F4FC)),
                    ),
                    SizedBox(
                      height: ScreenUtil().setWidth(80),
                    ),
                  ],
                ),
              )
            ])),
            Positioned(
                bottom: 0,
                left: 0,
                child: Container(
                  width: width,
                  color: Colors.white,
                  padding: EdgeInsets.only(
                    top: ScreenUtil().setWidth(15),
                    bottom: ScreenUtil().setWidth(15),
                    left: ScreenUtil().setWidth(10),
                    right: ScreenUtil().setWidth(10),
                  ),
                  child: Container(
                    height: ScreenUtil().setWidth(44),
                    decoration: BoxDecoration(
                      borderRadius:
                          BorderRadius.circular(ScreenUtil().setWidth(22)),
                      color: Color(0xff5589FF),
                    ),
                    child: FlatButton(
                      // padding: EdgeInsets.all(15.0),
                      child: Text("提交申请", style: TextStyle(fontSize: 16)),
                      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 (salaryRangeSelected == null ||
                            salaryRangeSelected.isEmpty) {
                          toasts("请输入期望薪资");
                          return;
                        }
                        if (_telController.text == null ||
                            _telController.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 ((_formKey.currentState as FormState).validate()) {
                          var form = {
                            "infoId": int.parse(widget.id),
                            "userId":
                                FlutterStars.SpUtil.getString(Constant.userId),
                            "name": _usernameController.text,
                            "gender": sexChioseValue,
                            "birthday": birthdaySelected,
                            "telephone": _telController.text,
                            "wechat": _wechatController.text,
                            "workingTime": experienceRangeSelected,
                            "salary": salaryRangeSelected,
                            "ability": json.encode(selectedLabels),
                            "intro": _evaluationController.text,
                          };

                          NewApiService().applyJob(form, onSuccess: (res) {
                            toasts("职位申请成功");
                            NavigatorUtils.goBackWithParams(context, true);
                            bool isApply = true;
                            FastNotification.push("apply", isApply);
                            setState(() {});
                          }, onError: (code, msg) {
                            toasts(msg);
                          });
                        }
                      },
                    ),
                  ),
                ))
          ],
        ),
      ),
    );
  }

  Widget labelSection() {
    var labels = selectedLabels
        .map(
          (e) => Container(
            padding: EdgeInsets.symmetric(horizontal: 10),
            height: 31,
            decoration: BoxDecoration(
              color: Color(0xffF4F8FA),
              borderRadius: BorderRadius.circular(20),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  e,
                  style: TextStyle(
                    fontSize: 13,
                    color: Color(0xff5589FF),
                  ),
                ),
                SizedBox(
                  width: 10,
                ),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      selectedLabels.remove(e);
                    });
                  },
                  child: Icon(
                    Iconfont.shanchu_shuzimianbanbianjitai,
                    color: Colors.grey,
                    size: 15,
                  ),
                )
              ],
            ),
          ),
        )
        .toList();

    labels.add(
      Container(
        width: 75,
        height: 31,
        decoration: BoxDecoration(
          color: Color(0xffF4F8FA),
          borderRadius: BorderRadius.circular(20),
        ),
        child: GestureDetector(
          onTap: () async {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (_) => LabelCollection(
                  selectedLabels: selectedLabels,
                ),
              ),
            );
            setState(() {
              // selectedLabels = updatedLabels;
            });
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Icon(
                Iconfont.tianjia9,
                size: 15,
                color: Colors.grey,
              ),
              Text(
                '标签',
                style: TextStyle(fontSize: 13, color: Color(0xffCCCCCC)),
              ),
            ],
          ),
        ),
      ),
    );

    return Wrap(
      spacing: 5,
      runSpacing: 5,
      children: labels.toList(),
    );
  }
}
