
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:liftmanager/internal/team/page/input_text_page.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/app_navigator.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/click_item.dart';
import 'package:liftmanager/widgets/my_button.dart';
import 'package:liftmanager/widgets/selected_image.dart';
import 'package:liftmanager/widgets/text_field_item.dart';

class TeamCreatePage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return TeamCreatePageState();
  }
}

class TeamCreatePageState extends State<TeamCreatePage>{
  File _imageFile;
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  final FocusNode _nodeText3 = FocusNode();

  TextEditingController _teamNameController = TextEditingController();
  TextEditingController _nameController = TextEditingController();
  TextEditingController _phoneController = TextEditingController();
  String _remarks = "";

  void _getImage(int key) async{
    try {
      _imageFile = await ImagePicker.pickImage(source: key == 1 ? ImageSource.camera : ImageSource.gallery, maxWidth: 800, imageQuality: 95);
      setState(() {});
    } catch (e) {
      toasts("没有权限，无法打开相册！");
    }
  }

  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());
        });
  }

  ///创建团队
  createTeamAction(){
    var team_name = _teamNameController.text.toString().trim();
    var name = _nameController.text.toString().trim();
    var phone = _phoneController.text.toString().trim();
    if(_imageFile == null){
      toasts("请上传团队logo");
      return;
    }
    if(team_name.isEmpty){
      toasts("请填写团队名称");
      return;
    }
    if(name.isEmpty){
      toasts("请填写联系人姓名");
      return;
    }
    if(phone.isEmpty){
      toasts("请填写联系电话");
      return;
    }
    print(_imageFile.path);
    showLoading(context, "正在创建...");
    ApiService(context: context).upload(_imageFile.path,onSuccess: (data){
      ApiService(context: context).teamCreate(data, team_name, _remarks, name, phone,onSuccess: (data){
        showAlert(context, "提示", "创建成功", "确定", (){
          dismissLoading(context);
          NavigatorUtils.goBack(context);
          NavigatorUtils.goBackWithParams(context,true);
        });
      },onError: (code,msg){
        dismissLoading(context);
        toasts(msg);
      });
    },onError: (code,msg){
      toasts(msg);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //resizeToAvoidBottomPadding: false,
      appBar: const MyAppBar(
        centerTitle: "创建团队",
//        actions: <Widget>[
//          FlatButton(
//            child: Text("保存", key: const Key('actionName'),style: TextStyle(color: Colors.white),),
//            textColor: Colours.material_bg,
//            color: Colours.material_bg
//          )
//        ],
      ),
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: defaultTargetPlatform == TargetPlatform.iOS ? FormKeyboardActions(
                  child:Container(
                    color: ThemeUtils.getTabsBg(context),
                    child: _buildBody(),
                  )
              ) : SingleChildScrollView(
                  child: Container(
                    color: ThemeUtils.getTabsBg(context),
                    child: _buildBody(),
                  )
              ),
            )
          ],
        ),
      ),
    );
  }

  _buildBody(){
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Gaps.vGap5,
          const Padding(
            padding: const EdgeInsets.only(left: 16.0),
            child: const Text("团队资料", style: TextStyles.textBold18),
          ),
          Gaps.vGap16,
          Center(
            child: SelectedImage(
                image: _imageFile,
                onTap: selectPicker
            ),
          ),
          Gaps.vGap10,
          Center(
            child: Text(
              "团队logo",
              style: Theme.of(context).textTheme.subtitle.copyWith(fontSize: Dimens.font_sp14),
            ),
          ),
          Gaps.vGap16,
          TextFieldItem(
              focusNode: _nodeText1,
              controller: _teamNameController,
              title: "团队名称",
              hintText: "填写团队名称"
          ),
          ClickItem(
            title: "团队简介",
            content: _remarks,

            onTap: (){
              AppNavigator.pushResult(context,
                  InputTextPage(
                    title: "团队简介",
                    hintText: "请填写...",
                    content: _remarks,
                  ), (result){
                    setState(() {
                      _remarks =result.toString();
                    });
                  });
            },
          ),
          Gaps.vGap16,
          Gaps.vGap16,
          const Padding(
            padding: const EdgeInsets.only(left: 16.0),
            child: const Text("联系人信息", style: TextStyles.textBold18),
          ),
          TextFieldItem(
              focusNode: _nodeText2,
              title: "联系人",
              controller: _nameController,
              hintText: "填写联系人姓名"
          ),
          TextFieldItem(
              focusNode: _nodeText3,
              title: "联系电话",
              controller: _phoneController,
              hintText: "填写联系电话号码"
          ),
          Padding(
            padding: const EdgeInsets.all(16),
            child: MyButton(
              onPressed: (){
                createTeamAction();
              },
              text: "提交",
            ),
          )

        ],
      ),
    );
  }

}