import 'package:farmer_client/models/addressController.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/services.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/CardListModel.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;
  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{
      markId=Get.arguments['id'];
      getMachineryInfo(markId, '122.08400000000002,37.421998333333335', true).then((value) {
        item(CardInfo.fromJson(value));

      });

      // item(CardInfo.fromJson(Get.arguments['item']));

      return;
    }
  }


  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: {'id':orderInfo().orderId});

      });
      //验证通过提交数据
    }

  }

  @override
  Widget builder(BuildContext context) {
    naviTitle = '预约';
    return Container(
      height: 700.h,
      child: Form(
        key: _formKey, //设置globalKey,用于后面获取FormState
        autovalidateMode: AutovalidateMode.onUserInteraction,
        child: Column(
          children: <Widget>[
            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: 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: EdgeInsets.fromLTRB(0, 15, 0, 15),
                decoration: const BoxDecoration(
                  border: Border(
                      bottom: BorderSide(width: 1, color: Color(0x20000000)
                          // 0x17000000
                          )),
                ),
                child: Row(
                  children: [
                    Image(
                      image: AssetImage('images/icons/timeImage.png'),
                      fit: BoxFit.cover,
                      width: 18.w,
                      height: 18.w,
                    ),
                    Padding(
                      padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                      child: GestureDetector(
                        onTap: () async {
                          var handleChnage = await showDatePicker(
                            context: context,
                            helpText: '请选择作业开始时间',
                            cancelText: '取消',
                            confirmText: '确定',
                            initialDate: selectDate() == null
                                ? DateTime.now()
                                : selectDate(),
                            firstDate: DateTime.now(),
                            lastDate: DateTime(2030),
                          );
                          selectDate(handleChnage!);
                          print('${selectDate}+');
                        },
                        child: Obx(()=>
                            Text(selectDate == null
                                ? '请选择日期'
                                : '${DateFormat("yyyy-MM-dd").format(selectDate())}'),
                        )

                      ),
                    )
                  ],
                )),
            Container(
              margin: 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: EdgeInsets.fromLTRB(0, 15, 0, 15),
              decoration: BoxDecoration(
                border: Border(
                    bottom: BorderSide(width: 1, color: Color(0x20000000)
                        // 0x17000000
                        )),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Image(
                    image: AssetImage('images/gpsImgae.png'),
                    fit: BoxFit.cover,
                    width: 14.w,
                    height: 17.h,
                  ),
                  Padding(
                      padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                      child: GestureDetector(
                        onTap: () {
                          Get.toNamed('/addressList',
                              arguments: {'isBack': true});
                        },
                        child: Container(
                          width: 290.w,
                          child: Obx(() => Text(
                                addressController.address.value.address
                                    .toString(),
                                softWrap: true,
                                maxLines: 1,
                                textAlign: TextAlign.left,
                                overflow: TextOverflow.ellipsis,
                              )),
                        ),
                      ))
                ],
              ),
            ),
            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(
                        BorderSide(width: 1, color: Color(0xFFFF703B))), //边框
                    elevation: MaterialStateProperty.all(0),
                    backgroundColor: MaterialStateProperty.all(Colors.white),
                    shape: MaterialStateProperty.all(
                      RoundedRectangleBorder(
                          borderRadius:
                              BorderRadius.all(Radius.circular(24.4))),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}