import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:liftmanager/internal/account/model/certificate_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 CertificateUploadPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return CertificateUploadPageState();
  }
}

class CertificateUploadPageState extends State<CertificateUploadPage> {
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  final FocusNode _nodeText3 = FocusNode();

  CertificateItem item = CertificateItem();
  List<File> images = [];
  @override
  void initState() {
    super.initState();
  }

  uploadCertificate() {
    if (item.code.length == 0 ||
        item.issuanceAgency.length == 0 ||
        item.expirationDate.length == 0) {
      toasts("请填写完整信息");
      return;
    }
    if(images.length !=2){
      toasts("请上传操作证");
      return;
    }
    showLoading(context, "正在提交...");
    ApiService(context: context).uploadMore(images, onSuccess: (imgs) {
      ApiService(context: context).liftCertificateAdd(item.code, item.issuanceAgency,
          item.expirationDate, item.certificateType,imgs[0], imgs[1],
          onSuccess: (res) {
            dismissLoading(context);
            showAlert(context, "提示", "保存成功", "确定", (){
              NavigatorUtils.goBack(context);
              NavigatorUtils.goBackWithParams(context,true);
            });
          }, onError: (code, msg) {
            dismissLoading(context);
            toasts(msg);
          });
    });
  }

  /// 选择时间
  Future<void> _selectTime(Function callback) async {
    DatePicker.showDatePicker(context,
        showTitleActions: true, onChanged: (date) {}, onConfirm: (date) {
          callback("${date.toString().split(".")[0]}");
        }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  ///选择图片
  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: () {
                    _getImage(value == '拍照' ? 1 : 0,index);
                    Navigator.of(context).pop();
                  },
                );
              }).toList());
        });
  }

  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("没有权限，无法打开相册！");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: "操作证上传",
        actions: <Widget>[
          FlatButton(
            child: Text("确定"),
            textColor: Colours.dark_text,
            highlightColor: Colors.transparent,
            onPressed: () {
              uploadCertificate();
            },
          )
        ],
      ),
      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: <Widget>[
        TextFieldItem(
          title: "操作证编号",
          content: "${item.code}",
          controller: TextEditingController(),
          hintText: "请填写操作证编号",
          focusNode: _nodeText1,
          onChanged: (res) {
            item.code = res;
//            setState(() {});
          },
        ),
        ClickItem(
          title: "证件有效期",
          content: "${item.expirationDate}",
          hintText: "请选择证件有效期",
          onTap: (){
            _selectTime((String time) {
              setState(() {
                item.expirationDate = time.split(" ")[0];
              });
            });
          },
        ),
        TextFieldItem(
          title: "发证单位",
          content: "${item.issuanceAgency}",
          controller: TextEditingController(),
          hintText: "请填写发证单位",
          focusNode: _nodeText2,
          onChanged: (res) {
            item.issuanceAgency = res;
          },
        ),
        TextFieldItem(
          title: "证件类型",
          content: "${item.certificateType}",
          controller: TextEditingController(),
          hintText: "请填写证件类型(如：T1)",
          focusNode: _nodeText3,
          onChanged: (res) {
            item.certificateType = res;
          },
        ),
        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:images.length >= 2 ? 2 : images.length + 1,
              itemBuilder: (_, index) {
                return Stack(
                  children: <Widget>[

                    Center(
                      child:SelectedImage(
                          image:index < images.length ? images[index] : null,
                          onTap: () {
                            selectPicker(index);
                          }),
                    )
                  ],
                );
              },
            )),
      ],
    );
  }
}
