import 'dart:io';

import 'package:flutter/material.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/constants/dict_enum.dart';
import 'package:sk_base_mobile/models/index.dart';
import 'package:sk_base_mobile/models/inventory.model.dart';
import 'package:sk_base_mobile/screens/new_inventory_inout/components/inventory_search.dart';
import 'package:sk_base_mobile/screens/new_inventory_inout/components/product_search.dart';
import 'package:sk_base_mobile/store/dict.store.dart';
import 'package:sk_base_mobile/util/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 NewInventoryInoutController controller;
  final dictService = Get.find<DictService>();
  final int inOrOut;
  NewInventoryInout({Key? key, this.inOrOut = InventoryInOrOutEnum.In})
      : controller = Get.put(NewInventoryInoutController(inOrOut: inOrOut)),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        top: false, // 设置为false以避免保留顶部状态栏的空间
        child: Scaffold(
            appBar: PreferredSize(
              preferredSize: Size.fromHeight(ScreenAdaper.height(
                  kToolbarHeight)), // 这里使用kToolbarHeight，它是不包含状态栏的AppBar的推荐高度
              child: AppBar(
                title: const Text('出入库登记'),
              ),
            ),
            resizeToAvoidBottomInset: true,
            body: SingleChildScrollView(
                child: Container(
              decoration: const BoxDecoration(
                color: Colors.white,
              ),
              child: Column(
                children: [
                  buildForm(),
                  Obx(() => GradientButton(
                        buttonText: TextEnum.createInventoryInOutBtnText,
                        onPressed: () => {controller.create()},
                        isLoading: controller.loading.value,
                      ))
                ],
              ),
            ))));
  }

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

    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<ProjectModel>(
        isRequired: true,
        textController: controller.projectTextController,
        labelText: '项目',
        hintText: inOrOut == InventoryInOrOutEnum.In ? '项目' : '请选择目标项目',
        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 TextFormField(
        controller: controller.productTextController,
        decoration: InputDecoration(
            hintText: '请选择产品',
            label: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "*",
                    style: TextStyle(
                        color: Colors.red, fontSize: ScreenAdaper.sp(30)),
                  ),
                  Text(
                    '产品',
                    style: TextStyle(fontSize: ScreenAdaper.sp(30)),
                  ),
                ]),
            floatingLabelBehavior: FloatingLabelBehavior.always),
        readOnly: true,
        onTap: () {
          if (inOrOut == InventoryInOrOutEnum.In) {
            ModalUtil.showGeneralDialog(content: ProductSearch(
              onProductSelected: (ProductModel product) {
                Get.back();
                String productName =
                    '${product.productNumber} ${product.name!}';
                controller.payload['productId'] = product.id;
                if ((product.productSpecification ?? '').isNotEmpty) {
                  productName += ' (${product.productSpecification})';
                }
                controller.productTextController.text = productName;
              },
            ));
          } else {
            ModalUtil.showGeneralDialog(
                    content: InventorySearch(
                      beforeSelectedCheck: (InventoryModel itemData) {
                        final isValid = (itemData.quantity ?? 0) > 0;
                        if (!isValid) {
                          SnackBarUtil().warning('库存不足');
                        }
                        return (itemData.quantity ?? 0) > 0;
                      },
                      onInventorySelected: (InventoryModel inventory) {
                        Get.back();
                        controller.payload['inventoryId'] = inventory.id;
                        String productName =
                            '${inventory.product!.name!}(￥${double.parse('${inventory.unitPrice}')})(${inventory.product?.company?.name})';
                        if ((inventory.product?.productSpecification ?? '')
                            .isNotEmpty) {
                          productName +=
                              ' (${inventory.product?.productSpecification})';
                        }
                        controller.projectTextController.text =
                            inventory.project!.name!;
                        controller.payload['projectId'] = inventory.project?.id;
                        controller.quantityTextController.text =
                            '${inventory.quantity}';
                        controller.productTextController.text = productName;
                        controller.payload['productId'] = inventory.product?.id;
                      },
                    ),
                    width: Get.width - ScreenAdaper.width(50))
                .then((value) => Get.delete<InventorySearchController>());
          }
        });
  }

  /// 时间
  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: '数量',
      onChanged: (value) {
        controller.calculatePrice('quantity');
      },
      isRequired: true,
    );
  }

  /// 单价
  Widget buildUnitPrice() {
    return ZtNumberInput(
      textController: controller.unitPriceTextController,
      labelText: '单价',
      onChanged: (value) {
        controller.calculatePrice('unitPrice');
      },
    );
  }

  /// 金额
  Widget buildAmount() {
    return ZtNumberInput(
      textController: controller.amountTextController,
      labelText: '金额',
      onChanged: (value) {
        controller.calculatePrice('amount');
      },
    );
  }

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

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

  /// 库存位置选择
  Widget buildPositionBottomPicker() {
    final firstLevelData = [
      ...dictService.getDictItemsByCode(DictTypeEnum.InventoryRoom)
    ];
    final secondLevelData = [
      DictItemModel(label: '未知', value: '未知'),
      ...dictService.getDictItemsByCode(DictTypeEnum.InventoryLine)
    ];
    final thirdDatas =
        dictService.getDictItemsByCode(DictTypeEnum.InventoryLineLevel);
    final thirdtLevelData = [
      if (thirdDatas.isNotEmpty) DictItemModel(label: '未知', value: '未知'),
      ...thirdDatas
    ];
    return TextFormField(
        controller: controller.positionTextController,
        decoration: const InputDecoration(
            labelText: '库存位置',
            floatingLabelBehavior: FloatingLabelBehavior.always),
        readOnly: true,
        onTap: () {
          printInfo(
              info: firstLevelData
                  .map((e) => Center(child: (Text(e.label))))
                  .toList()
                  .toString());
          ModalUtil.showBottomSheetPicker(
              title: '库存位置',
              firstLevel: firstLevelData
                  .map((e) => Center(child: (Text(e.label))))
                  .toList(),
              secondLevel: secondLevelData
                  .map((e) => Center(child: (Text(e.label))))
                  .toList(),
              thirdLevel: thirdtLevelData
                  .map((e) => Center(child: (Text(e.label))))
                  .toList(),
              onChanged: (_0, _1, _2) {
                String position = firstLevelData[_0].label;
                if (_1 >= 1) {
                  position += ', ${secondLevelData[_1].label}';
                }
                if (_2 >= 1) {
                  position += ', ${thirdtLevelData[_2].label}';
                }
                // , ${secondLevelData[_1].label}, ${thirdtLevelData[_2].label}
                controller.positionTextController.text = position;
                controller.payload['position'] = position;
              });
        });
  }

  /// 照片上传
  Widget buildImageUploadQueue() {
    return Container(
      padding: EdgeInsets.symmetric(
          vertical: ScreenAdaper.height(20),
          horizontal: ScreenAdaper.width(20)),
      alignment: Alignment.center,
      child: Column(
        children: [
          Text(
            '*请拍照上传照片',
            style: TextStyle(
                fontSize: ScreenAdaper.sp(25),
                color: AppTheme.secondPrimaryColor),
          ),
          SizedBox(
            height: ScreenAdaper.height(10),
          ),
          Obx(() => SingleChildScrollView(
                controller: controller.uploadScrollController,
                scrollDirection: Axis.horizontal,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ...controller.uploadImgFilesPath
                        .map((String path) => builderImagePreview(path))
                        .toList(),
                    buildImageUploader()
                  ],
                ),
              )),
        ],
      ),
    );
  }

  /// 照片预览队列Item
  Widget builderImagePreview(String path) {
    return Stack(
      children: [
        Container(
          margin: EdgeInsets.symmetric(horizontal: ScreenAdaper.width(5)),
          width: ScreenAdaper.width(180),
          height: ScreenAdaper.width(180),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20),
            border: Border.all(width: 1.0, color: AppTheme.dividerColor),
            // color: AppTheme.primaryColor,
          ),
          child: Center(
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                image: DecorationImage(
                  fit: BoxFit.cover,
                  image: FileImage(File(path)),
                ),
              ),
            ),
          ),
        ),
        Positioned(
            top: ScreenAdaper.height(5),
            right: ScreenAdaper.width(5),
            child: GestureDetector(
              onTap: () {
                controller.uploadImgFilesPath.remove(path);
              },
              child: Icon(
                Icons.close,
                shadows: [
                  Shadow(
                    color: Colors.black,
                    offset: Offset(1, 1),
                    blurRadius: 3,
                  ),
                  Shadow(
                    color: Colors.black,
                    offset: Offset(-1, -1),
                    blurRadius: 3,
                  ),
                ],
                size: ScreenAdaper.sp(40),
                color: AppTheme.nearlyWhite,
              ),
            ))
      ],
    );
  }

  // 上传照片控制器
  Widget buildImageUploader() {
    return GestureDetector(
        onTap: () {
          controller.photoPicker();
        },
        child: Container(
            margin: EdgeInsets.symmetric(horizontal: ScreenAdaper.width(5)),
            width: ScreenAdaper.width(180),
            height: ScreenAdaper.width(180),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20),
              border: Border.all(width: 1.0, color: AppTheme.dividerColor),
              // color: AppTheme.primaryColor,
            ),
            child: Center(
                child: Icon(
              Icons.add_a_photo_rounded,
              size: ScreenAdaper.sp(60),
              color: AppTheme.primaryColor,
            ))));
  }
}
