import 'dart:io';
import 'package:flutter/material.dart';
import 'package:fun_selfie_app/widgets/common_form_item.dart';
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart';
import 'package:fun_selfie_app/utils/common_toast.dart';
import 'package:date_format/date_format.dart';
import 'package:fun_selfie_app/utils/permission_request.dart';

class AddNewsPage extends StatefulWidget {
  const AddNewsPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _AddNewsPageState();
}

class _AddNewsPageState extends State<AddNewsPage> {
  bool _switchVal = false;
  File? imagePath;
  GlobalKey<FormState> formKey = GlobalKey<FormState>(); //表单验证
  final TextEditingController newsName = TextEditingController();
  final TextEditingController newsPlace = TextEditingController();
  final TextEditingController newsDate = TextEditingController();
  final TextEditingController newsZs = TextEditingController();
  final TextEditingController newsDs = TextEditingController();
  final TextEditingController newsDsDate = TextEditingController();
  final ImagePicker _imagePicker = ImagePicker();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('创建活动'),
          centerTitle: true,
          // titleSpacing: 40,
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 40),
              child: TextButton(
                  child: const Text(
                    '保存',
                    style: TextStyle(color: Colors.white, fontSize: 20),
                  ),
                  onPressed: () {
                    onSubmit();
                  }),
            ),
          ],
        ),
        body: Form(
            key: formKey,
            autovalidateMode: AutovalidateMode.onUserInteraction,
            child: SingleChildScrollView(
                child: Column(children: <Widget>[
              CommonFormItem(
                label: '活动的名称',
                hitText: '请输入',
                controller: newsName,
                validator: (v) => (v == '') ? "请输入" : null,
              ),
              CommonFormItem(
                label: '活动的地点',
                hitText: '请输入',
                controller: newsPlace,
                validator: (v) => (v == '') ? "请输入" : null,
              ),
              CommonFormItem(
                readOnly: true,
                label: '开始日期',
                hitText: '请输入',
                controller: newsDate,
                validator: (v) => (v == '') ? "请输入" : null,
                onTap: () async {
                  final curentDate = DateTime.now();
                  showDatePicker(
                          context: context,
                          initialDate: curentDate,
                          firstDate: curentDate,
                          lastDate: DateTime(2100),
                          locale: const Locale('zh'))
                      .then((value) {
                    if (value == null) return;
                    var dateStr = formatDate(
                        value.toLocal(), [yyyy, '年', mm, '月', dd, '日']);
                    newsDate.text = dateStr;
                  });
                },
              ),
              CommonFormItem(
                label: '连拍张数',
                hitText: '请输入',
                controller: newsZs,
                validator: (v) => (v == '') ? "请输入" : null,
              ),
              CommonFormItem(
                label: '自拍倒数',
                hitText: '请输入',
                suffixText: '秒',
                controller: newsDs,
                validator: (v) => (v == '') ? "请输入" : null,
              ),
              CommonFormItem(
                label: '首张补充倒数时间',
                hitText: '请输入',
                suffixText: '秒',
                controller: newsDsDate,
                validator: (v) => (v == '') ? "请输入" : null,
              ),
              Padding(
                padding: const EdgeInsets.only(left: 20, right: 20),
                child: Row(
                  children: [
                    const Text('平铺相纸', style: TextStyle(fontSize: 18)),
                    const Expanded(child: SizedBox()),
                    Transform.scale(
                        scale: 1.7,
                        child: Switch(
                            value: _switchVal,
                            inactiveTrackColor: Colors.grey,
                            inactiveThumbColor: Colors.white,
                            activeColor: const Color.fromARGB(100, 98, 0, 238),
                            activeTrackColor:
                                const Color.fromARGB(100, 98, 0, 238),
                            onChanged: (value) {
                              setState(() {
                                _switchVal = !_switchVal;
                              });
                            }))
                  ],
                ),
              ),
              Center(
                child: imagePath == null
                    ? const Text('')
                    : InkWell(
                        child: Image.file(imagePath!),
                        onTap: () {
                          selectImage(context);
                        }),
              ),
              _switchVal && imagePath == null
                  ? FloatingActionButton.extended(
                      label: const Text('选择边框'),
                      onPressed: () {
                        selectImage(context);
                      },
                    )
                  : const Text('')
            ]))));
  }

  Future selectImage(BuildContext context) async {
    bool result = await permissionCheckAndRequest(context, "通知");
    if (result) CommonToast.okToast("已拥有该权限");
    XFile? image = await _imagePicker.pickImage(source: ImageSource.gallery);
    if (image == null) return;
    final File filePath = File(image.path);
    // upLoadImage(filePath);
    setState(() {
      imagePath = filePath;
    });
  }

  upLoadImage(File image) async {
    String path = image.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
    FormData formData = FormData.fromMap({
      "userId": "10000024",
      "file": await MultipartFile.fromFile(
        path,
        filename: name,
        //contentType: ContentType.parse("image/$suffix")
      )
    });

    Dio dio = Dio();
    var respone = await dio.post<String>("/upload", data: formData);
    if (respone.statusCode == 200) {
      CommonToast.okToast('图片上传成功');
    }
  }

  onSubmit() {
    final form = formKey.currentState;
    if (form!.validate()) {
      if (_switchVal && imagePath == null) {
        CommonToast.okToast('请选择活动边框');
        return;
      }
    }
  }
}
