import 'dart:io';

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/model/team_auth_item.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/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/selected_image.dart';
import 'package:liftmanager/widgets/text_field_item.dart';

class TeamAuthUploadPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return TeamCardUploadPageState();
  }
}

class TeamCardUploadPageState extends State<TeamAuthUploadPage> {
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  final FocusNode _nodeText3 = FocusNode();

  TeamAuthItem item = TeamAuthItem();
  List<File> images = [];
  File headerImg;

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

  getTeamAuthInfo() {
    ApiService(context: context).teamAuth(onSuccess: (res) {
      if (res != null) {
        item = res;
        setState(() {});
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  ///选择图片
  void selectPicker(int index) {
    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: () {
                    if (index == -1) {
                      _getHeaderImage(value == '拍照' ? 1 : 0);
                    } else {
                      _getImage(value == '拍照' ? 1 : 0, index);
                    }

                    Navigator.of(context).pop();
                  },
                );
              }).toList());
        });
  }

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

  void _getImage(int key, int index) async {
    try {
      var _imageFile = await ImagePicker.pickImage(
          source: key == 1 ? ImageSource.camera : ImageSource.gallery,
          maxWidth: 800,
          imageQuality: 95);
      if (_imageFile != null) {
        if (images.length > index) {
          images[index] = _imageFile;
        } else {
          images.add(_imageFile);
        }

        setState(() {});
      }
    } catch (e) {
      toasts("没有权限，无法打开相册！");
    }
  }

  /**
   * 提交认证信息
   */
  uploadAuthData() {
    if (item.attestationName.length == 0) {
      toasts("请输入团队名称");
      return;
    }
    if (item.contactsName.length == 0) {
      toasts("请输入联系人");
      return;
    }
    if (item.contactsTel.length == 0) {
      toasts("请输入联系人电话");
      return;
    }
    if (images.length != 2) {
      toasts("请上传营业执照/资质证书");
      return;
    }
//    if(headerImg ==null){
//      toasts("请上传团队logo");
//      return;
//    }
    showLoading(context, "正在提交");
    ApiService(context: context).uploadMore(images, onSuccess: (list) {
      ApiService(context: context).teamUploadAuth(
          item.id,
          item.attestationName,
          item.contactsName,
          item.contactsTel,
          list[0],
          list[1],
          item.logoImg, onSuccess: (res) {
        dismissLoading(context);
        showAlert(context, "提示", "提交成功", "确定", () {
          NavigatorUtils.goBack(context);
          NavigatorUtils.goBack(context);
        });
      }, onError: (code, msg) {
        dismissLoading(context);
        toasts(msg);
      });
    }, onError: (code, msg) {
      dismissLoading(context);
      toasts(msg);
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        appBar: MyAppBar(
          centerTitle: "我的团队",
          actions: <Widget>[
            FlatButton(
              child: Text("提交"),
              textColor: Colours.dark_text,
              highlightColor: Colors.transparent,
              onPressed: () {
                uploadAuthData();
              },
            )
          ],
        ),
        body: SafeArea(
          child: Column(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: defaultTargetPlatform == TargetPlatform.iOS
                    ? FormKeyboardActions(child: _buildBody())
                    : SingleChildScrollView(child: _buildBody()),
              )
            ],
          ),
        ));
  }

  _buildBody() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: _listWidgets(),
    );
  }

  _listWidgets() {
    return [
      Container(
        padding: EdgeInsets.only(top: 10, bottom: 20),
        color: ThemeUtils.getTabsBg(context),
        child: Center(
          child: SelectedImage(
              image: headerImg,
              onTap: () {
                selectPicker(-1);
              }),
        ),
      ),
      Container(
        padding: EdgeInsets.only(bottom: 20),
        color: ThemeUtils.getTabsBg(context),
        child: Center(
            child: Container(
              padding: EdgeInsets.fromLTRB(8, 2, 8, 2),
              decoration: BoxDecoration(borderRadius: BorderRadius.circular(12)),
              child: Text("logo",
                  style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),
            )),
      ),
      Gaps.vGap10,
      ClickItem(
        title: "状态",
        content:
        "${item.isCertificated == 1 ? '已认证' : item.isCertificated == 2 ? '审核中' : item.isCertificated == 3 ? '认证失败' : '未认证'}",
      ),
      TextFieldItem(
        title: "团队名称",
        content: "${item.attestationName}",
        controller: TextEditingController(),
        hintText: "请填写团队名称",
        focusNode: _nodeText1,
        onChanged: (res) {
          item.attestationName = res;
        },
      ),
      TextFieldItem(
        title: "联系人",
        content: "${item.contactsName}",
        controller: TextEditingController(),
        hintText: "请填写联系人",
        focusNode: _nodeText2,
        onChanged: (res) {
          item.contactsName = res;
        },
      ),
      TextFieldItem(
        title: "联系人电话",
        content: "${item.contactsTel}",
        controller: TextEditingController(),
        hintText: "请填写联系人电话",
        focusNode: _nodeText3,
        onChanged: (res) {
          item.contactsTel = res;
        },
      ),
      Gaps.vGap10,
      ClickItem(
        title: "企业营业执照/资质证书",
        content: "",
        hideDiv: true,
      ),
      Container(
          color: ThemeUtils.getTabsBg(context),
          child: GridView.builder(
            shrinkWrap: true,
            padding: const EdgeInsets.fromLTRB(8.0, 12, 8.0, 12.0),
            physics: NeverScrollableScrollPhysics(),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3, childAspectRatio: 1.18),
            itemCount: 2,
            itemBuilder: (_, index) {
              return Stack(
                children: <Widget>[
                  Center(
                    child: SelectedImage(
                        image: index < images.length ? images[index] : null,
                        onTap: () {
                          selectPicker(index);
                        }),
                  )
                ],
              );
            },
          ))
    ];
  }
}
