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 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/widgets/selected_image.dart';
import 'dart:io';
import 'package:liftmanager/widgets/bbs_content.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/utils/number_text_input_formatter.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:liftmanager/common/common.dart';
import 'package:flustars/flustars.dart' as flustars;
import 'package:flutter/cupertino.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/internal/wode/wode_router.dart';
import 'package:liftmanager/widgets/click_item.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'package:liftmanager/utils/theme_utils.dart';

class MasterBecome extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MasterBecomeState();
  }
}

class MasterBecomeState extends State<MasterBecome> {
  ScrollController _scrollController = new ScrollController();

  TextEditingController _nameController = new TextEditingController();
  TextEditingController _idNumberController = new TextEditingController();
  TextEditingController _mobileController = new TextEditingController();
  TextEditingController _professionalController = new TextEditingController();
  TextEditingController _workDateController = new TextEditingController();
  TextEditingController _companyController = new TextEditingController();
  TextEditingController _jobController = new TextEditingController();
  TextEditingController _residentPlaceController = new TextEditingController();
  TextEditingController _workExperienceController = new TextEditingController();
  TextEditingController _projectExperienceController =
      new TextEditingController();
  TextEditingController _proficiencyBrandController =
      new TextEditingController();
  TextEditingController _goodElectricalController = new TextEditingController();
  TextEditingController _goodMechanicalController = new TextEditingController();
  String defaultValue = "请选择";
  String ids;
  List<String>idsList = [];
  List<String>defaultValueList = [];
  // 焦点控制
  FocusNode _focusNode1 = new FocusNode();
  GlobalKey _formKey = new GlobalKey<FormState>();

  int sexChiose = -1;
  String sexChioseString = "";
  String ageChiose = "";
  int learnChiose = -1;
  String learnChioseString = "";
  String addressName = "";
  List<String> sexListChiose = [];
  List<dynamic> sexList = [
    {"value": 1, "label": "男"},
    {"value": 2, "label": "女"}
  ];
  List<String> ageListChiose = [];

  List<String> learnListChiose = [];
  List<dynamic> learnList = [
    {"value": 1, "label": "小学"},
    {"value": 2, "label": "初中"},
    {"value": 3, "label": "中专"},
    {"value": 4, "label": "高中"},
    {"value": 5, "label": "大专"},
    {"value": 6, "label": "本科"},
    {"value": 7, "label": "硕士研究生"},
    {"value": 8, "label": "博士研究生"},
  ];

  String avatarPath = '';

  String cardPicture = '';
  String degreeCertificate = '';
  String skillsCertificate = '';
  String otherCertificates = '';

  dynamic detailObj;

  bool _protocol = false;
  bool sortBool = true;

  void submit(type) {
    if (!_protocol) {
      toasts("请勾选用户协议!");
      return;
    }
    if (avatarPath.isEmpty) {
      toasts("请上传头像!");
      return;
    } else if (sexChiose == -1) {
      toasts("请选择性别!");
      return;
    } else if (ageChiose.isEmpty) {
      toasts("请选择年龄!");
      return;
    } else if (learnChiose == -1) {
      toasts("请选择学历!");
      return;
    } else if (cardPicture.isEmpty) {
      toasts("请上传身份证人像面!");
      return;
    } else if (skillsCertificate.isEmpty) {
      toasts("请上传专业技能证书人像面!");
      return;
    }
    if(addressName == null || addressName == ""){
      toasts("请选择常驻工作地!");
      return;
    }
    if(_goodElectricalController.text.length>20){
      toasts("擅长电气最大不超过20字符!");
      return;
    }
    if(_goodMechanicalController.text.length>20){
      toasts("擅长机械最大不超过20字符!");
      return;
    }
    RegExp exp = RegExp(r'^1[34578]\d{9}$');
    RegExp expSfz = RegExp(r"\d{17}[\d|x]|\d{15}");
    if(!expSfz.hasMatch(_idNumberController.text)){
                            toasts("请输入正确的身份证号");
                            return;
                          }
    if(!exp.hasMatch(_mobileController.text)){
                            toasts("请输入正确的手机号");
                            return;
                          }
    if(idsList.length<=0){
      toasts("请选择品牌");
                            return;
    }

    if(type == "add"){
      NewApiService().applyExperts({
      "age": ageChiose,
      "photo": avatarPath,
      "cardPicture": cardPicture,
      // "checkFlag": 0,
      "company": _companyController.text,
      "degreeCertificate": degreeCertificate,
      "eduLevel": learnChiose,
      "gender": sexChiose,
      "goodElectrical": _goodElectricalController.text,
      "goodMechanical": _goodMechanicalController.text,
      "idNumber": _idNumberController.text,
      "job": _jobController.text,
      "mobile": _mobileController.text,
      "name": _nameController.text,
      "otherCertificates": otherCertificates,
      "professional": _professionalController.text,
      "proficiencyBrand":ids,
      "proficiencyBrandName":defaultValue,
      "projectExperience": _projectExperienceController.text,
      "residentPlace": addressName,
      "skillsCertificate": skillsCertificate,
      "userId": int.parse(flustars.SpUtil.getString(Constant.userId)),
      "workDate": _workDateController.text,
      "workExperience": _workExperienceController.text
    }, onSuccess: (res) {
      toasts("申请成功，请等待审核");
      Navigator.pop(context);
    }, onError: (code, msg) {
      toasts(msg);
    });

    }else {
      NewApiService().updateBecomeMaster({
      "id": detailObj.id,
      "photo": avatarPath,
      "age": ageChiose,
      "cardPicture": cardPicture,
      // "checkFlag": 0,
      "company": _companyController.text,
      "degreeCertificate": degreeCertificate,
      "eduLevel": learnChiose,
      "gender": sexChiose,
      "goodElectrical": _goodElectricalController.text,
      "goodMechanical": _goodMechanicalController.text,
      "idNumber": _idNumberController.text,
      "job": _jobController.text,
      "mobile": _mobileController.text,
      "name": _nameController.text,
      "otherCertificates": otherCertificates,
      "professional": _professionalController.text,
      "proficiencyBrand":ids,
      "proficiencyBrandName":defaultValue,
      "projectExperience": _projectExperienceController.text,
      "residentPlace": addressName,
      "skillsCertificate": skillsCertificate,
      "userId": int.parse(flustars.SpUtil.getString(Constant.userId)),
      "workDate": _workDateController.text,
      "workExperience": _workExperienceController.text
    }, onSuccess: (res) {
      toasts("修改申请成功，请等待审核");
      Navigator.pop(context);
    }, onError: (code, msg) {
      toasts(msg);
    });
    }
  }

  @override
  initState() {
    getDetail();
    for (var i = 10; i < 100; i++) {
      ageListChiose.add(i.toString());
    }
    for (var i = 0; i < sexList.length; i++) {
      sexListChiose.add(sexList[i]['label']);
    }
    for (var i = 0; i < learnList.length; i++) {
      learnListChiose.add(learnList[i]['label']);
    }
    getBrandList();
    super.initState();

    FastNotification.addListener("set_address_master", (setAddressMaster) {
      setState(() {
        addressName = setAddressMaster;
        print(addressName);
        print(222222224);
      });
    });
  }

  bool _hasData = false;

  Future getDetail() async {
    await NewApiService().getBecomeMasterDetail(
        onSuccess: (res) {
      if (res != null) {
        detailObj = res;
        ageChiose = detailObj.age.toString();
        
        sexChiose = detailObj.gender;
        learnChiose = detailObj.eduLevel;
        if(sexChiose == 1){
          sexChioseString = "男";
        }else if (sexChiose == 2){
          sexChioseString = "女";
        }
        learnList.forEach((element) {
          if(learnChiose == element["value"]){
            print(learnChiose);
            print(element["value"]);
            print(123456);
            learnChioseString = element["label"];
          }
        });
        cardPicture = detailObj.cardPicture;
        _companyController.text = detailObj.company;
        degreeCertificate = detailObj.degreeCertificate;
        avatarPath = detailObj.photo;
        _goodElectricalController.text = detailObj.goodElectrical;
        _goodMechanicalController.text = detailObj.goodMechanical;
        _idNumberController.text = detailObj.idNumber;
        _jobController.text = detailObj.job;
        _mobileController.text = detailObj.mobile;
        _nameController.text = detailObj.name;
        otherCertificates = detailObj.otherCertificates;
        _professionalController.text = detailObj.professional;
        ids = detailObj.proficiencyBrand;
        defaultValue = detailObj.proficiencyBrandName;
        _projectExperienceController.text = detailObj.projectExperience;
        addressName = detailObj.residentPlace;
        skillsCertificate = detailObj.skillsCertificate;
        _workDateController.text = detailObj.workDate.toString();
        _workExperienceController.text = detailObj.workExperience;
        idsList = ids.split(",");
        defaultValueList = defaultValue.split(",");
        setState(() {});
      }else {
        avatarPath = flustars.SpUtil.getString("avatarUrl");
        _nameController.text = flustars.SpUtil.getString("name");
        _mobileController.text = flustars.SpUtil.getString(Constant.phone);
      }
      _hasData = true;
    }, onError: (code, msg) {
      toasts(msg);
    });
  }


  List<dynamic> brandList;
  Future getBrandList() async {
    await NewApiService().getBrandListNoPage(
        onSuccess: (res) {
      if (res != null) {
        brandList = res;
        setState(() {});
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  void selectPicker() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return SimpleDialog(
          title: Text("修改头像"),
          children: ["拍照", '从手机相册选择'].map((String 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) {
        upLoadFileOnce(_imageFile.path);
      }
    } catch (e) {
      toasts("没有权限，无法打开相册！");
    }
  }

  getCheckFlag(type){
    String str;
    if(type == 2){
      str = "待审核";
    }else if(type == 0) {
      str = "驳回";
    }else if (type == 1){
      str = "审核通过";
    }
    return "($str)";
  }

  void upLoadFileOnce(String path) {
    showLoading(context, "正在上传...");
    NewApiService().upload(path, onSuccess: (res) {
      dismissLoading(context);
      setState(() {
        avatarPath = res.pathUrl;
        setState(() {});
      });
    }, onError: (code, msg) {
      dismissLoading(context);
      toasts(msg);
    });
  }

  // 查看专家协议
  void openProtocol() {

  }
  
  FocusNode blankNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    // 监听FocusNode
    _focusNode1.addListener(() {
      // _focusNode1.hasFocus 是否聚焦
      print(_focusNode1.hasFocus);
    });

    return Scaffold(
      resizeToAvoidBottomPadding: false, //不让键盘弹上去
      appBar: MyAppBar(
        centerTitle: "申请为专家",
      ),
      body: _hasData? GestureDetector(
        onTap: () {
          // 点击空白页面关闭键盘
          FocusScope.of(context).requestFocus(blankNode);
        },
        child: Stack(
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(bottom: ScreenUtil().setWidth(80)),
              child: ListView(
                children: <Widget>[
                  Form(
                    key: _formKey, //设置globalKey，用于后面获取FormState
                    // autovalidate: true, //开启自动校验
                    child: Column(
                      children: <Widget>[
                        Stack(
                          children: <Widget>[
                            Container(
                              width: width,
                              height: 180,
                              child: avatarPath.isEmpty
                                  ? LoadAssetImage(
                                      "wode/apply_expert_cover",
                                      format: "jpg",
                                      fit: BoxFit.fill,
                                      width: ScreenUtil().setWidth(width),
                                      height: ScreenUtil().setWidth(180),
                                    )
                                  : LoadNetworkImage(
                                      avatarPath,
                                      fit: BoxFit.fill,
                                      width: ScreenUtil().setWidth(width),
                                      height: ScreenUtil().setWidth(180),
                                    ),
                            ),
                            Positioned(
                              left: width / 2 - 30,
                              top: 180 / 2 - 40,
                              width: 60,
                              height: 60,
                              child: GestureDetector(
                                onTap: () {
                                  selectPicker();
                                },
                                child: LoadAssetImage(
                                  "wode/apply_expert_avatar",
                                  fit: BoxFit.fill,
                                  width: ScreenUtil().setWidth(60),
                                  height: ScreenUtil().setWidth(60),
                                ),
                              ),
                            ),
                            Positioned(
                              left: width / 2 - ScreenUtil().setHeight(60),
                              top: ScreenUtil().setHeight(180) / 2 + ScreenUtil().setHeight(30),
                              width: ScreenUtil().setHeight(120),
                              height: ScreenUtil().setHeight(30),
                              child: GestureDetector(
                                onTap: () {
                                  selectPicker();
                                },
                                child: Text(
                                  "上传照片",
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    color: Color(0xffffffff),
                                    fontSize: ScreenUtil().setSp(18),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                        Container(
                          height: ScreenUtil().setHeight(45),
                          padding: EdgeInsets.only(
                            left: ScreenUtil().setWidth(15),
                            right: ScreenUtil().setWidth(15),
                          ),
                          alignment: Alignment.centerLeft,
                          decoration: BoxDecoration(
                            color: ThemeUtils.getDialogTextFieldColor(context),
                          ),
                          child: Row(
                            children: <Widget>[
                              Text(
                                "基本信息",
                                style: TextStyle(
                                  fontSize: ScreenUtil().setSp(15),
                                  fontWeight: FontWeight.bold,
                                ),
                                
                              ),
                              Text(
                                detailObj?.checkFlag == null?"":getCheckFlag(detailObj.checkFlag),
                                style: TextStyle(
                                  fontSize: ScreenUtil().setSp(15),
                                  fontWeight: FontWeight.bold,
                                  color: Color(0xFFff0000),
                                ),
                              )
                            ],
                          ),
                        ),
                        TextFieldItem(
                          title: "姓名",
                          isMust: true,
                          content: "",
                          controller: _nameController,
                          hintText: "请输入您的姓名",
                          validator: (val) {
                            return val.trim().length > 0 ? null : "请输入姓名";
                          },
                        ),
                        ChiosePicker(
                          range: sexListChiose,
                          label: "性别",
                          isMust: true,
                          value: sexChioseString,
                          onConfirm: (value, index) {
                            sexChiose = sexList[index]['value'];
                          },
                        ),
                        ChiosePicker(
                          range: ageListChiose,
                          label: "年龄",
                          isMust: true,
                          value: ageChiose,
                          onConfirm: (value, index) {
                            ageChiose = value;
                          },
                        ),
                        TextFieldItem(
                          title: "身份证号",
                          isMust: true,
                          content: "",
                          controller: _idNumberController,
                          hintText: "请输入您的身份证号",
                          validator: (val) {
                            return val.trim().length > 0 ? null : "请输入身份证号";
                          },
                        ),
                        TextFieldItem(
                          title: "联系电话",
                          isMust: true,
                          content: "",
                          controller: _mobileController,
                          hintText: "请输入您的联系电话",
                          validator: (val) {
                            return val.trim().length > 0 ? null : "请输入联系电话";
                          },
                        ),
                        ChiosePicker(
                          range: learnListChiose,
                          label: "学历",
                          isMust: true,
                          value: learnChioseString,
                          onConfirm: (value, index) {
                            learnChiose = learnList[index]['value'];
                          },
                        ),
                        TextFieldItem(
                          title: "专业",
                          isMust: true,
                          content: "",
                          controller: _professionalController,
                          hintText: "请输入您的专业",
                          validator: (val) {
                            return val.trim().length > 0 ? null : "请输入您的专业";
                          },
                        ),
                        TextFieldItem(
                          title: "从业时长",
                          isMust: true,
                          content: "",
                          keyboardType: TextInputType.number,
                          controller: _workDateController,
                          hintText: "请输入您的从业时长",
                          validator: (val) {
                            return val.trim().length > 0 ? null : "请输入您的从业时长";
                          },
                        ),
                        TextFieldItem(
                          title: "所在公司",
                          content: "",
                          controller: _companyController,
                          hintText: "请输入您的所在公司",
                        ),
                        TextFieldItem(
                          title: "现任岗位",
                          content: "",
                          controller: _jobController,
                          hintText: "请输入您的现任岗位",
                        ),
                        // TextFieldItem(
                        //   title: "常驻工作地",
                        //   content: "",
                        //   controller: _residentPlaceController,
                        //   hintText: "常驻工作地",
                        //   onChanged: (res) {
                        //     //            setState(() {});
                        //   },
                        // ),
                        InkWell(
                        onTap: () {
                          NavigatorUtils.push(
                              context, "${BbsRouter.mapChoicePoint}?type=2");
                        },
                        child: Container(
                          padding: EdgeInsets.only(
                              left: ScreenUtil().setWidth(15),
                              right: ScreenUtil().setWidth(15),
                              top: ScreenUtil().setWidth(10),
                              bottom: ScreenUtil().setWidth(10)),
                          decoration: BoxDecoration(
                            border: Border(
                              bottom:
                                  BorderSide(width: 0.5, color: Colours.line),
                            ),
                          ),
                          child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Row(
                                  children: <Widget>[
                                    Text(
                                      "常驻工作地",
                                      style: TextStyle(
                                        color: Color(0xff222222),
                                        // fontSize:ScreenUtil().setSp(14)
                                      ),
                                      textAlign: TextAlign.start,
                                    ),
                                    Text(
                                      "*",
                                      style: TextStyle(
                                        color: Color(0xffff0000),
                                        // fontSize:ScreenUtil().setSp(14)
                                      ),
                                      textAlign: TextAlign.start,
                                    ),
                                  ],
                                ),
                                Expanded(
                                  child: Text(
                                    addressName != null && addressName != ""
                                        ? addressName.split(",")[0]
                                        : "请选择",
                                    style: TextStyle(
                                      color: Color(0xff999999),
                                      // fontSize:ScreenUtil().setSp(14)
                                    ),
                                    textAlign: TextAlign.end,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                )
                              ]),
                        ),
                      ),
                        Container(
                          height: ScreenUtil().setHeight(45),
                          padding: EdgeInsets.only(
                            left: ScreenUtil().setWidth(15),
                            right: ScreenUtil().setWidth(15),
                          ),
                          alignment: Alignment.centerLeft,
                          decoration: BoxDecoration(
                            color: ThemeUtils.getDialogTextFieldColor(context),
                          ),
                          child: Text(
                            "工作经历",
                            style: TextStyle(
                              fontSize: ScreenUtil().setSp(15),
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(15),
                                top: ScreenUtil().setWidth(5),
                                bottom: ScreenUtil().setWidth(5),
                              ),
                              child: Text(
                                "工作经历",
                                style: TextStyle(
                                  color: Color(0xff222222),
                                  // fontSize:ScreenUtil().setSp(14),
                                ),
                                textAlign: TextAlign.left,
                              ),
                            ),
                          ],
                        ),
                        Container(
                          height: 100,
                          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: _workExperienceController,
                            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)
                            ),
                          ),
                        ),
                        SizedBox(
                          height: 6,
                          child: Container(color: ThemeUtils.getDialogTextFieldColor(context)),
                        ),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              padding: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(15),
                                  top: ScreenUtil().setWidth(5),
                                  bottom: ScreenUtil().setWidth(5)),
                              child: Text(
                                "项目经历",
                                style: TextStyle(
                                  color: Color(0xff222222),
                                  // fontSize:ScreenUtil().setSp(14),
                                ),
                                textAlign: TextAlign.left,
                              ),
                            ),
                          ],
                        ),
                        Container(
                          height: 100,
                          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: _projectExperienceController,
                            maxLines: 5,
                            decoration: InputDecoration(
                              contentPadding: EdgeInsets.all(0),
                              hintText: '请输入项目时间+项目名称+主要职责',
                              hintStyle: TextStyle(
                                color: Color(0xffcccccc),
                              ),
                              focusedBorder: InputBorder.none,
                              border: InputBorder.none,
                            ),
                          ),
                        ),
                        Container(
                          height: ScreenUtil().setHeight(45),
                          padding: EdgeInsets.only(
                            left: ScreenUtil().setWidth(15),
                            right: ScreenUtil().setWidth(15),
                          ),
                          alignment: Alignment.centerLeft,
                          decoration: BoxDecoration(
                            color: ThemeUtils.getDialogTextFieldColor(context),
                          ),
                          child: Text(
                            "技术特点",
                            style: TextStyle(
                              fontSize: ScreenUtil().setSp(15),
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        // TextFieldItem(
                        //   title: "擅长品牌",
                        //   isMust: true,
                        //   content: "",
                        //   controller: _proficiencyBrandController,
                        //   hintText: "请输入电梯品牌",
                        //   validator: (val) {
                        //     return val.trim().length > 0 ? null : "请输入擅长品牌";
                        //   },
                        // ),

                        ClickItem(
                          title: "擅长品牌",
                          content: defaultValue,
                          isMust:true,
                          onTap: () {
                            setState(() {
                              sortBool = false;
                            });
                          },
                        ),

                        TextFieldItem(
                          title: "擅长电气",
                          isMust: true,
                          content: "",
                          controller: _goodElectricalController,
                          hintText: "请输入电气类别",
                          validator: (val) {
                            return val.trim().length > 0 ? null : "请输入擅长电气";
                          },
                        ),
                        TextFieldItem(
                          title: "擅长机械",
                          isMust: true,
                          content: "",
                          controller: _goodMechanicalController,
                          hintText: "请输入机械类别",
                          validator: (val) {
                            return val.trim().length > 0 ? null : "请输入擅长机械";
                          },
                        ),
                        Container(
                          height: ScreenUtil().setHeight(45),
                          padding: EdgeInsets.only(
                            left: ScreenUtil().setWidth(15),
                            right: ScreenUtil().setWidth(15),
                          ),
                          alignment: Alignment.centerLeft,
                          decoration: BoxDecoration(
                            color: ThemeUtils.getDialogTextFieldColor(context),
                          ),
                          child: Text(
                            "上传证照",
                            style: TextStyle(
                              fontSize: ScreenUtil().setSp(15),
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        IdPhoto(
                            title: "身份证上传",
                            desc: "上传身份证人像面",
                            cover: "apply_idcard",
                            isMust: true,
                            uploadFile:cardPicture,
                            change: (value) {
                              cardPicture = value;
                            }),
                        IdPhoto(
                            title: "学历学位证书上传",
                            desc: "上传学位学历证书人面像",
                            cover: "apply_education",
                            uploadFile:degreeCertificate,
                            change: (value) {
                              degreeCertificate = value;
                            }),
                        IdPhoto(
                            title: "专业技能证书上传",
                            desc: "上传专业技能证书人像面",
                            cover: "apply_profession",
                            uploadFile:skillsCertificate,
                            isMust: true,
                            change: (value) {
                              skillsCertificate = value;
                            }),
                        IdPhoto(
                            title: "其他证书上传",
                            desc: "其他荣誉、培训证书等",
                            cover: "apply_other",
                            uploadFile:otherCertificates,
                            change: (value) {
                              otherCertificates = value;
                            }),
                        Container(
                          height: ScreenUtil().setHeight(45),
                          padding: EdgeInsets.only(
                            left: ScreenUtil().setWidth(15),
                            right: ScreenUtil().setWidth(15),
                          ),
                          alignment: Alignment.centerLeft,
                          decoration: BoxDecoration(
                            color: ThemeUtils.getDialogTextFieldColor(context),
                          ),
                          child: Row(
                            children: <Widget>[
                              Checkbox(
                                value: _protocol,
                                activeColor: Colors.red, //选中时的颜色
                                onChanged: (value) {
                                  setState(() {
                                    _protocol = value;
                                  });
                                  print(_protocol);
                                },
                              ),
                              GestureDetector(
                                  onTap: () {
                                    NavigatorUtils.push(
                context, "${WodeRouter.xieyiList}");
                                  },
                                  child: Row(
                                    children: <Widget>[
                                      Text("同意《"),
                                      Text(
                                        "专家协议",
                                        style: TextStyle(
                                          color:Color(0xFF0287FF),
                                        ),
                                        // textAlign:TextAlign.start,
                                      ),
                                      Text("》")
                                    ],
                                  )
                                  ),
                            ],
                          ),
                        ),
                        SizedBox(
                          height: 6,
                          child: Container(color: ThemeUtils.getDialogTextFieldColor(context)),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
            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: ((detailObj == null) || (detailObj != null&&detailObj.checkFlag == 0))? 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: () {
                      if ((_formKey.currentState as FormState).validate()) {
                        if(detailObj == null){
                          submit("add");
                        }else {
                          submit("edit");
                        }
                        
                      }
                    },
                  ),
                ):Container(
                  height: ScreenUtil().setWidth(44),
                  decoration: BoxDecoration(
                    borderRadius:
                        BorderRadius.circular(ScreenUtil().setWidth(22)),
                    color:Color(0xffcccccc)
                  ),
                  child: FlatButton(
                    // padding: EdgeInsets.all(15.0),
                    child: Text("提交"),
                    textColor: Colors.white,
                    onPressed: () {
                      toasts("审核中，请勿重复提交！");
                    },
                  ),
                ),
              ),
            ),
            !sortBool
                  ? Positioned(
                      top: 0,
                      left: 0,
                      child: GestureDetector(
                        onTap: () {
                          setState(() {
                            sortBool = true;
                            
                            if(ids!=null&&ids!=""){
                              defaultValueList = defaultValue.split(",");
                              idsList = ids.split(",");
                            }else {
                              defaultValueList = [];
                              idsList = [];
                            }
                          });
                        },
                        child: Container(
                            width: width,
                            height: height,
                            color: Color.fromRGBO(0, 0, 0, 0.5)),
                      ),
                    )
                  : Container(child: null),
            !sortBool?
            Positioned(
              top:0,
              right:0,
              child:Container(
                width: width/4*3,
                height:height,
                color: Colors.white,
                padding: EdgeInsets.only(top:ScreenUtil().setWidth(45)),
                child:ListView(
                  children:<Widget>[
                    
                   brandList!=null&&brandList!=[]?Container(
                     child: Wrap(
                  alignment: WrapAlignment.start,
                  crossAxisAlignment: WrapCrossAlignment.center,
                  children: brandList.asMap().keys.map((index){
                    return InkWell(
                      onTap: (){
                            print("666");
                            
                            setState(() {
                              if(idsList.contains(brandList[index].id.toString())){
                                defaultValueList.remove(brandList[index].name);
                                idsList.remove(brandList[index].id.toString());
                              }else {
                                if(idsList.length>=3){
                                  toasts("最多只能选择3个品牌");
                                }else {
                                  defaultValueList.add(brandList[index].name);
                                  idsList.add(brandList[index].id.toString());
                                }
                              }
                              print(idsList);
                            });
                            
                          },
                      child: Container(
                      width: width/4-12,
                      padding: EdgeInsets.only(bottom:ScreenUtil().setWidth(10),top:ScreenUtil().setWidth(10)),
                      margin: EdgeInsets.only(left:5,right:5,bottom:5,top:5),
                      decoration: BoxDecoration(
                        // border: Border(
                        //   bottom: BorderSide(width: 0.5, color: Colours.line),
                        // ),
                        color: Color(0xfff5f5f5)
                      ),
                      child:Text(
                                  brandList[index].name??"",
                                  style: TextStyle(
                                    color:idsList.contains(brandList[index].id.toString())?Color(0xffff0000):Color(0xff666666),
                                    fontSize:ScreenUtil().setSp(15)
                                  ),
                                  textAlign:TextAlign.center,
                                ),
                    ),
                    );
                    
                  }).toList(),
                )
                   ):loadCircle()
                  ],
                  
                )
              )
            ):
            Container(
              child:null
            ),
            !sortBool?
            Positioned(
              top:0,
              right:0,
              child: 
              Container(
                        width: width/4*3,
                      padding: EdgeInsets.only(left:10,top:10,bottom:10,right:10),
                      child:Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text(
                                  "品牌",
                                  style: TextStyle(
                                    color:Color(0xff666666),
                                    fontSize:ScreenUtil().setSp(16)
                                  ),
                                  textAlign:TextAlign.start,
                                ),
                          GestureDetector(
                            onTap: (){
                              setState(() {
                                sortBool = true;
                                String str = "";
                                String strD = "";
                                idsList.forEach((item){
                                  str += (item.toString() + ",");
                                });
                                ids = str.substring(0, str.length-1);
                                defaultValueList.forEach((item){
                                  strD += (item.toString() + ",");
                                });
                                defaultValue = strD.substring(0, strD.length-1);
                                print(defaultValue);
                                print(ids);

                              });
                            },
                            child: Text(
                                  "确定",
                                  style: TextStyle(
                                    color:Color(0xFF0287FF),
                                    fontSize:ScreenUtil().setSp(16)
                                  ),
                                  textAlign:TextAlign.start,
                                ),
                          )
                        ],
                      )
                    ),
            ):
            Container(
              child:null
            ),
          ],
        ),
      ):Center(
              child: Text("正在加载..."),
            ),
    );
  }

  Widget loadCircle() {
    return Container(
      padding: EdgeInsets.only(top: 10, bottom: 10),
      color: ThemeUtils.getTabsBg(context),
      child: Center(
        child: SpinKitFadingCircle(
          color: Colors.blueAccent,
          size: 30.0,
        ),
      ),
    );
  }
}

class IdPhoto extends StatefulWidget {
  IdPhoto({
    Key key,
    this.title,
    this.desc,
    this.uploadFile = "",
    this.cover,
    this.isMust: false,
    this.change,
  }) : super(key: key);

  final String title;
  final String desc;
  String uploadFile;
  final String cover;
  final bool isMust;
  final Function(String) change;

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

class _IdPhotoState extends State<IdPhoto> {
  @override
  initState() {
    super.initState();
  }

  void selectPicker() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return SimpleDialog(
          title: Text(widget.title ?? "图片上传"),
          children: ["拍照", '从手机相册选择'].map((String 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) {
        upLoadFileOnce(_imageFile.path);
        // setState(() {});
      }
    } catch (e) {
      toasts("没有权限，无法打开相册！");
    }
  }

  void upLoadFileOnce(String path) {
    showLoading(context, "正在上传...");
    NewApiService().upload(path, onSuccess: (res) {
      dismissLoading(context);
      setState(() {
        widget.uploadFile = res.pathUrl;
        widget.change != null ? widget.change(res.pathUrl) : null;
        setState(() {});
      });
    }, onError: (code, msg) {
      dismissLoading(context);
      toasts(msg);
    });
  }


  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    return Container(
      child: Container(
        // height: ScreenUtil().setWidth(200),
        padding: EdgeInsets.only(
          top: ScreenUtil().setWidth(30),
          right: ScreenUtil().setWidth(10),
          bottom: ScreenUtil().setWidth(30),
          left: ScreenUtil().setWidth(10),
        ),
        decoration: BoxDecoration(
          border: Border(
            bottom: Divider.createBorderSide(context, width: 0.6),
          ),
        ),
        child: Row(
          children: <Widget>[
            Offstage(
              offstage: !widget.isMust,
              child: Text(
                "*",
                style: TextStyle(color: Colors.red),
              ),
            ),
            Container(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    child: Text(
                      widget.title,
                      textAlign: TextAlign.left,
                      style: TextStyle(
                        fontSize: ScreenUtil().setSp(16),
                      ),
                    ),
                  ),
                  Container(
                    child: Text(
                      widget.desc,
                      textAlign: TextAlign.left,
                      style: TextStyle(
                        fontSize: ScreenUtil().setSp(14),
                        color: Color(0xFF999999),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              flex: 1,
              child: Container(),
            ),
            GestureDetector(
              onTap: () {
                selectPicker();
              },
              child: widget.uploadFile.isEmpty
                  ? LoadAssetImage(
                      "wode/" + widget.cover,
                      fit: BoxFit.fill,
                      width: ScreenUtil().setWidth(140),
                      height: ScreenUtil().setWidth(89),
                    )
                  : LoadNetworkImage(
                      widget.uploadFile,
                      fit: BoxFit.fill,
                      width: ScreenUtil().setWidth(140),
                      height: ScreenUtil().setWidth(89),
                    ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 封装输入框
class TextFieldItem extends StatelessWidget {
  const TextFieldItem({
    Key key,
    this.controller,
    @required this.title,
    this.keyboardType: TextInputType.text,
    this.hintText: "",
    this.isMust: false,
    this.content: "",
    this.maxLength,
    this.focusNode,
    this.onChanged,
    this.config,
    this.validator,
  }) : super(key: key);

  final TextEditingController controller;
  final String title;
  final String hintText;
  final bool isMust;
  final String content;
  final TextInputType keyboardType;
  final int maxLength;
  final FocusNode focusNode;
  final Function onChanged;
  final KeyboardActionsConfig config;
  final FormFieldValidator<String> validator;

  @override
  Widget build(BuildContext context) {
    if (config != null && defaultTargetPlatform == TargetPlatform.iOS) {
      // 因Android平台输入法兼容问题，所以只配置IOS平台
      FormKeyboardActions.setKeyboardActions(context, config);
    }
    if (content.length > 0) {
      controller.text = content;
    }
    return 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(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top:15),
            child: Text(title),
          ),
          Offstage(
            offstage: !this.isMust,
            child: Container(
              padding: EdgeInsets.only(top:18),
              child: Text(
                "*",
                style: TextStyle(color: Colors.red),
              ),
            )
          ),
          Expanded(
            flex: 1,
            child: TextFormField(
              textAlign: TextAlign.right,
              onChanged: onChanged,
              maxLength: maxLength,
              focusNode: focusNode,
              keyboardType: keyboardType,
              inputFormatters: _getInputFormatters(),
              controller: controller,
              //style: TextStyles.textDark14,
              decoration: InputDecoration(
                hintText: hintText,
                hintStyle: TextStyle(color: Colours.text_gray_c),
                border: InputBorder.none, //去掉下划线
                //hintStyle: TextStyles.textGrayC14
              ),
              validator: validator,
            ),
          ),
          Gaps.hGap16
        ],
      ),
    );
  }

  _getInputFormatters() {
    if (keyboardType == TextInputType.numberWithOptions(decimal: true)) {
      return [UsNumberTextInputFormatter()];
    }
    if (keyboardType == TextInputType.number ||
        keyboardType == TextInputType.phone) {
      return [WhitelistingTextInputFormatter.digitsOnly];
    }
    return null;
  }
}
