import 'package:farmer_client/models/addressController.dart';
import 'package:farmer_client/models/app.dart';
import 'package:farmer_client/models/entities/CardInfo.dart';
import 'package:farmer_client/widgets/layout/BasicPage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import '../../models/entities/OrderInfoModel.dart';
import '../../services/homeAPI.dart';
import '../../services/orderAPI.dart';

class OrderConfirmation extends BasicPage {
  TextEditingController _unameController = TextEditingController();
  GlobalKey _formKey = GlobalKey<FormState>();
  String markId = '';
  final selectDate = Rx<DateTime>(DateTime.now()); //选择的时间
  final workingArea = Rx<int>(0);
  AddressController addressController = AddressController.t;
  AppController appController = AppController.t;
  final item = Rx<CardInfo>(CardInfo()); //全部详情
  final orderInfo = Rx<OrderInfoModel>(OrderInfoModel()); //全部详情

  @override
  void beforeShow() {
    // TODO: implement beforeShow
    super.beforeShow();
    if (Get.arguments['item'] != null) {
      item(Get.arguments['item']);
    } else if (Get.arguments['id'] != null) {
      markId = Get.arguments['id'];
      EasyLoading.show(status: '数据加载中...');
      //苹果模拟器看不到定位所以加一个默认定位是邓州市中心位置
      getMachineryInfo(Get.arguments['id'],
              appController.locationStr ?? '112.091892,32.690712', true)
          .then((value) {
        item(CardInfo.fromJson(value));
        EasyLoading.dismiss();
      }).catchError((error) {
        EasyLoading.dismiss();
        Fluttertoast.showToast(msg: error.error['message']);
      });
    }
  }

  Map<String, dynamic> data = {};

  void _orderSubmit() {
    if ((_formKey.currentState as FormState).validate()) {
      data = {
        'charges': item.value.price! * workingArea.value,
        'price': item.value.price,
        'amount': workingArea.value,
        'machineryId': item.value.machineryId,
        'machineryName': item.value.name,
        'machineryType': item.value.typeId,
        'typeName': item.value.typeName,
        'address': addressController.address.value.address,
        'orgId': item.value.orgId,
        'appointmentDate':
            '${DateFormat("yyyy-MM-dd").format(selectDate.value)} 08:00:00',
      };
      generateOrder(data).then((value) {
        orderInfo(OrderInfoModel.fromJson(value));
        Fluttertoast.showToast(msg: '预约成功');
        Get.offNamed('/orderPageInfo', arguments: {
          'orderId': value['orderId'],
          'title': '待付款',
          'styleColor': Color(0xFF51D4FF)
        });
      });
      //验证通过提交数据
    }
  }

  @override
  Widget builder(BuildContext context) {
    naviTitle = '预约';
    return SizedBox(
      height: 700.h,
      child: Form(
        key: _formKey, //设置globalKey,用于后面获取FormState
        autovalidateMode: AutovalidateMode.onUserInteraction,
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.fromLTRB(15, 20, 0, 0),
              alignment: Alignment.topLeft,
              child: Text(
                '作业面积/亩',
                style: TextStyle(
                    color: Color(0xff222222),
                    fontSize: 17.sp,
                    fontWeight: FontWeight.bold),
              ),
            ),
            TextFormField(
              autofocus: false,
              keyboardType: TextInputType.number,
              controller: _unameController,
              decoration: const InputDecoration(
                isCollapsed: true,
                contentPadding:
                    EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                counterText: '', //去掉计数
                ///   UnderlineInputBorder 只有下边框  默认使用的就是下边框
                border: UnderlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                  borderSide: BorderSide(
                    color: Color(0x30000000),
                    width: 2.0,
                  ),
                ),
                floatingLabelBehavior: FloatingLabelBehavior.never,
                hintText: "请输入具体面积(亩)",
              ),
              onChanged: (e) {
                workingArea(int.parse(e));
              },
              // 校验用户名
              validator: (v) {
                return v!.trim().isNotEmpty ? null : "作业面积/亩不能为空";
              },
            ),
            Container(
              margin: const EdgeInsets.fromLTRB(15, 20, 0, 0),
              alignment: Alignment.topLeft,
              child: Text(
                '作业时间:',
                style: TextStyle(
                    color: Color(0xff222222),
                    fontSize: 17.sp,
                    fontWeight: FontWeight.bold),
              ),
            ),
            Container(
                width: 345.w,
                padding: const EdgeInsets.fromLTRB(0, 15, 0, 15),
                decoration: const BoxDecoration(
                  border: Border(
                      bottom: BorderSide(width: 1, color: Color(0x20000000)
                          // 0x17000000
                          )),
                ),
                child: Row(
                  children: [
                    Image(
                      image: const AssetImage('images/icons/timeImage.png'),
                      fit: BoxFit.cover,
                      width: 18.w,
                      height: 18.w,
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(10, 0, 0, 0),
                      child: GestureDetector(
                          onTap: () async {
                            var handleChnage = await showDatePicker(
                              context: context,
                              helpText: '请选择作业开始时间',
                              cancelText: '取消',
                              confirmText: '确定',
                              initialDate: selectDate(),
                              firstDate: DateTime.now(),
                              lastDate: DateTime(2030),
                            );
                            selectDate(handleChnage!);
                            print('${selectDate}+');
                          },
                          child: Obx(
                            () => Text(selectDate == null
                                ? '请选择日期'
                                : DateFormat("yyyy-MM-dd")
                                    .format(selectDate())),
                          )),
                    )
                  ],
                )),
            Container(
              margin: const EdgeInsets.fromLTRB(15, 20, 0, 0),
              alignment: Alignment.topLeft,
              child: Text(
                '作业位置:',
                style: TextStyle(
                    color: Color(0xff222222),
                    fontSize: 17.sp,
                    fontWeight: FontWeight.bold),
              ),
            ),
            Container(
              width: 345.w,
              padding: const EdgeInsets.fromLTRB(0, 15, 0, 15),
              decoration: const BoxDecoration(
                border: Border(
                    bottom: BorderSide(width: 1, color: Color(0x20000000)
                        // 0x17000000
                        )),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Image(
                    image: const AssetImage('images/gpsImgae.png'),
                    fit: BoxFit.cover,
                    width: 14.w,
                    height: 17.h,
                  ),
                  Padding(
                      padding: const EdgeInsets.fromLTRB(10, 0, 0, 0),
                      child: GestureDetector(
                        onTap: () {
                          Get.toNamed('/addressList', arguments: {
                            'isBack': true,
                          });
                        },
                        child: SizedBox(
                          width: 290.w,
                          child: Obx(() => Text(
                                addressController.address.value.address
                                    .toString(),
                                softWrap: true,
                                maxLines: 1,
                                textAlign: TextAlign.left,
                                overflow: TextOverflow.ellipsis,
                              )),
                        ),
                      ))
                ],
              ),
            ),
            const Spacer(),
            Container(
              alignment: Alignment.bottomCenter,
              child: SizedBox(
                width: 315.w,
                height: 49.h,
                child: ElevatedButton(
                  onPressed: () {
                    _orderSubmit();
                  },
                  child: const Text(
                    "确定",
                    style: TextStyle(
                        fontSize: 18,
                        color: Colors.white,
                        fontWeight: FontWeight.bold),
                  ),
                  style: ButtonStyle(
                    elevation: MaterialStateProperty.all(0),
                    backgroundColor:
                        MaterialStateProperty.all(const Color(0xFFFF703B)),
                    shape: MaterialStateProperty.all(
                        const RoundedRectangleBorder(
                            borderRadius:
                                BorderRadius.all(Radius.circular(24.4)))),
                  ),
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.fromLTRB(0, 30.w, 0, 30.w),
              alignment: Alignment.bottomCenter,
              child: SizedBox(
                width: 315.w,
                height: 49.h,
                child: ElevatedButton(
                  onPressed: () {
                    Get.back();
                  },
                  child: const Text(
                    "取消",
                    style: TextStyle(
                        fontSize: 18,
                        color: Color(0xFFFF703B),
                        fontWeight: FontWeight.bold),
                  ),
                  style: ButtonStyle(
                    side: MaterialStateProperty.all(const BorderSide(
                        width: 1, color: Color(0xFFFF703B))), //边框
                    elevation: MaterialStateProperty.all(0),
                    backgroundColor: MaterialStateProperty.all(Colors.white),
                    shape: MaterialStateProperty.all(
                      const RoundedRectangleBorder(
                          borderRadius:
                              BorderRadius.all(Radius.circular(24.4))),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}