import 'package:flutter/material.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
import 'package:get/get.dart';
import 'package:sk_base_mobile/app_theme.dart';
import 'package:sk_base_mobile/constants/constants.dart';
import 'package:sk_base_mobile/models/index.dart';
import 'package:sk_base_mobile/screens/new_inventory_inout/components/date_time.dart';
import 'package:sk_base_mobile/util/date.util.dart';
import 'package:sk_base_mobile/widgets/core/zt_number_input.dart';
import 'package:sk_base_mobile/widgets/core/zt_search_select.dart';
import 'package:sk_base_mobile/widgets/core/zk_date_picker.dart';
import 'package:sk_base_mobile/widgets/core/zt_text_input.dart';
import 'package:sk_base_mobile/widgets/gradient_button.dart';
import 'package:sk_base_mobile/screens/new_inventory_inout/new_inventory_inout_controller.dart';
import 'package:sk_base_mobile/util/screen_adaper_util.dart';

class NewInventoryInout extends StatelessWidget {
  final String inOrOut;
  NewInventoryInout({super.key, this.inOrOut = 'in'});

  final controller = Get.put(NewInventoryInoutController());

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenAdaper.height(800),
      width: Get.width,
      decoration: const BoxDecoration(
        color: Colors.white,
      ),
      child: ClipRRect(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(
                ScreenAdaper.sp(30),
              ),
              topRight: Radius.circular(ScreenAdaper.sp(30))),
          child: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              // 点击空白处时收起键盘
              // FocusScope.of(Get.context!).unfocus();
            },
            child: Stack(
              children: [
                Positioned.fill(
                    child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    buildTitle(),
                    SingleChildScrollView(
                      child: buildForm(),
                    ),
                    Spacer(),
                    Obx(() => GradientButton(
                          onPressed: () => {controller.insertTask(context)},
                          isLoading: controller.loading.value,
                        ))
                  ],
                ))
              ],
            ),
          )),
    );
  }

  Widget buildTitle() {
    return Container(
      decoration: const BoxDecoration(
          border: Border(bottom: BorderSide(color: AppTheme.dividerColor))),
      padding: EdgeInsets.symmetric(
          vertical: ScreenAdaper.height(5), horizontal: ScreenAdaper.width(20)),
      child: Row(
        children: [
          Text(
            TextEnum.inventoryInOutDialogTitle,
            style: TextStyle(
              fontSize: ScreenAdaper.sp(25),
              fontWeight: FontWeight.w700,
            ),
          ),
          const Spacer(),
          IconButton(
              onPressed: () {
                Get.back();
              },
              icon: Icon(
                Icons.close,
                size: ScreenAdaper.sp(30),
              ))
        ],
      ),
    );
  }

  Widget buildForm() {
    double formVerticalGap = 20.0;
    double formHorizontalGap = 20.0;
    final children = [
      Row(children: [
        Expanded(
          flex: 2,
          child: buildProjectPicker(),
        ),
        SizedBox(
          width: ScreenAdaper.width(formHorizontalGap),
        ),
        Expanded(
          flex: 3,
          child: buildProductPicker(),
        ),
      ]),
      SizedBox(
        height: ScreenAdaper.height(formVerticalGap),
      ),
      Row(
        children: [
          Expanded(flex: 1, child: buildDatePicker()),
          SizedBox(
            width: ScreenAdaper.width(formHorizontalGap),
          ),
          Expanded(flex: 1, child: buildQuantity()),
        ],
      ),
      SizedBox(
        height: ScreenAdaper.height(formVerticalGap),
      ),
      Row(
        children: [Expanded(child: buildAgent())],
      ),
      SizedBox(
        height: ScreenAdaper.height(formVerticalGap),
      ),
      Row(
        children: [Expanded(child: buildRemark())],
      ),
    ];

    final child = Column(
      mainAxisAlignment: MainAxisAlignment.center,
      mainAxisSize: MainAxisSize.max,
      children: children,
    );

    return Form(
        key: controller.formKey,
        child: Container(
          padding: EdgeInsets.symmetric(
              vertical: ScreenAdaper.height(20),
              horizontal: ScreenAdaper.width(20)),
          alignment: Alignment.center,
          child: child,
        ));
  }

  /// 项目
  Widget buildProjectPicker() {
    return ZtSearchSelect(
        isRequired: true,
        textController: controller.projectTextController,
        labelText: '项目',
        itemBuilder: (itemData) => Container(
            padding: EdgeInsets.symmetric(
                vertical: ScreenAdaper.height(15),
                horizontal: ScreenAdaper.width(20)),
            child: Text(
              '${itemData?.name}',
              style: TextStyle(fontSize: ScreenAdaper.sp(20)),
            )),
        suggestionsCallback: (String keyword) {
          return controller.getProjects(keyword: keyword);
        },
        onClear: () {
          controller.payload.remove('projectId');
        },
        onSelected: (ProjectModel project) {
          controller.projectTextController.text = project.name ?? '';
          controller.payload['projectId'] = project.id;
        });
  }

  /// 产品
  Widget buildProductPicker() {
    return ZtSearchSelect(
        isRequired: true,
        textController: controller.productTextController,
        labelText: '产品',
        itemBuilder: (itemData) => ListTile(
              title: Text('${itemData?.name}'),
              subtitle: Text('${itemData?.company?.name ?? ''}'),
            ),
        suggestionsCallback: (String keyword) {
          return controller.getProducts(keyword: keyword);
        },
        onClear: () {
          controller.payload.remove('productId');
        },
        onSelected: (ProductModel product) {
          controller.productTextController.text = product.name ?? '';
          controller.payload['productId'] = product.id;
        });
  }

  /// 时间
  Widget buildDatePicker() {
    return ZtDatePicker(
      textController: controller.dateTextController,
      onClear: () {
        controller.payload.remove('time');
      },
      onDateSelected: (date) {
        if (date != null) {
          controller.dateTextController.text = DateUtil.format(date);
          controller.payload['time'] = controller.dateTextController.text;
        }
      },
    );
  }

  /// 数量
  Widget buildQuantity() {
    return ZtNumberInput(
      textController: controller.quantityTextController,
      labelText: '数量',
      isRequired: true,
    );
  }

  /// 经办人
  Widget buildAgent() {
    return ZtTextInput(
      textController: controller.agentTextController,
      labelText: '经办人',
      isRequired: true,
    );
  }

  /// 备注
  Widget buildRemark() {
    return ZtTextInput(
      textController: controller.remarkTextController,
      labelText: '备注',
      isRequired: true,
      isTextArea: true,
    );
  }
}
