Untitled

 avatar
unknown
plain_text
2 years ago
25 kB
6
Indexable
import 'dart:async';
import 'dart:io';
import 'package:ceramic_quotation/app/constant/app_string.dart';
import 'package:ceramic_quotation/app/database/database_service.dart';
import 'package:ceramic_quotation/app/model/product_model/product_model.dart';
import 'package:ceramic_quotation/app/model/product_model/product_request_model.dart';
import 'package:ceramic_quotation/app/modules/product/product_service/product_service.dart';
import 'package:ceramic_quotation/app/utils/app_prefrence.dart';
import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';
import 'package:filesystem_picker/filesystem_picker.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart' hide FormData, MultipartFile;
import 'package:path_provider/path_provider.dart';
import '../../../model/sorting_model/product_sorting_model.dart';
import '../../../utils/utils.dart';

class ProductController extends GetxController {
  final TextEditingController mrp = TextEditingController();
  final TextEditingController productId = TextEditingController();
  final TextEditingController skycode = TextEditingController();
  final TextEditingController name = TextEditingController();
  final DatabaseService databaseService = getIt.get<DatabaseService>();

  Dio dio = Dio();
  String? dirPath;
  File? file;
  double progress = 0;
  var dataList = [];
  var createPath;
  List<ProductModel> dataListValue = [];
  int? sortColumnIndex;
  ProductModel? productModel = ProductModel();
  List<ProductData>? productData;
  bool isSelected = false;
  List<bool>? checkBoxValues;
  List<ProductData> itemAddList = [];
  List<ProductData> newItemAddList = [];
  bool closeDialog = true;
  double totalAmouint = 0;

  bool sortAscending = true;
  Directory? root = Platform.isMacOS
      ? Directory("/Users/imac/")
      : Directory("/storage/emulated/0/");

  List<FileSystemEntity>? imageList;

  filterImage() async {
    imageList =
        Directory(AppPreference.getString("folder_path") ?? "").listSync(
      recursive: true,
    );
    return imageList;
  }

  sum(double mrp, double qty, int index) {
    var qAmt = mrp * qty;
    itemAddList[index].gAmt = qAmt;
    update();
    return qAmt;
  }

  double? Disc({
    required double mrp,
    required double dis_per,
    required int index,
  }) {
    double discountAmt = mrp * (dis_per) / 100;

    itemAddList[index].nAmt = (double.parse(mrp.toString()) - discountAmt);
    update();
    return itemAddList[index].nAmt;
  }

  startTimer() {
    new Timer.periodic(
      Duration(seconds: 2),
      (Timer timer) {
        if (progress == 1) {
          timer.cancel();
          Get.back();
          getProduct();
        } else {
          progress += 0.2;
        }
        update();
      },
    );
  }

  Future<String> createFolders(String cow) async {
    final dir = Directory((Platform.isMacOS
                ? await getApplicationSupportDirectory()
                : Platform.isAndroid
                    ? await getExternalStorageDirectory()
                    : await getApplicationSupportDirectory())!
            .path +
        '/$cow');
    dirPath = dir.path;
    AppPreference.set("folder_path", "${dir.path}/");
    if ((await dir.exists())) {
      print(AppString.alreadyExist + dir.absolute.path);
      return dir.path;
    } else {
      dir.create();
      print(AppString.createFolder + dir.path);
      return dir.path;
    }
  }

  folderPicker(BuildContext context) async {
    final path = await FilesystemPicker.open(
      title: AppString.saveFolder,
      context: context,
      rootDirectory: root!,
      fsType: FilesystemType.folder,
      pickText: AppString.pickText,
    );

    if (path == null) return;
    if (path != null) {
      try {
        dataList = Directory(path).listSync().map((e) => e.path).toList();
        for (int i = 0; i < dataList.length; i++) {
          var file = await moveFile(
            File(dataList[i]),
            "${dirPath!}/${File(dataList[i]).path.split("/").last}",
          );
        }
      } catch (e) {}
    }

    print(path);
  }

  Future<File> moveFile(File sourceFile, String newPath) async {
    try {
      return await sourceFile.rename(newPath);
    } catch (e) {
      final newFile = await sourceFile.copy(newPath);
      await sourceFile.delete();
      return newFile;
    }
  }

  void ExcelFileUpload() async {
    final result = await FilePicker.platform.pickFiles(
      allowMultiple: false,
      type: FileType.any,
      allowedExtensions: [
        'xls',
        'xlsx',
      ],
    );
    if (result == null) return;
    if (result != null) {
      file = File(result.files.first.path!);
      ProductService().getUpload(file!);
    }
  }

  getProduct() async {
    final getData = await ProductService().getRequest();
    newItemAddList = getData!.data ?? [];
    if (getData.data != null && getData.data!.isNotEmpty) {
      databaseService.saveProduct(getData.data ?? []);
    }
    update();
    runFilter("");
    return productModel;
  }

  getDataFromDatabase() async {
    final data = await databaseService.getProductData();
    newItemAddList = data;
    productModel!.data = newItemAddList;
    update();
  }

  void sorting<T>(
    Comparable<T> Function(Dessert d) getField,
    int columnIndex,
    bool ascending,
  ) {
    sortColumnIndex = columnIndex;
    sortAscending = ascending;
    update();
  }

  @override
  onInit() async {
    filterImage();
    //  await getProduct();
    await getDataFromDatabase();
    itemAddList.add(ProductData(
      isSelected: true,
      isactive: "",
      id: "",
      company: "",
      category: "",
      skycode: "",
      name: "",
      hsn: "",
      description: "",
      mrp: "",
      v: 0,
    ));
    super.onInit();
  }

  getDataUpdate(
    ProductUpdateRequestModel? productUpdateRequestModel,
    context,
  ) async {
    productModel = await ProductService()
        .productUpdate(productUpdateRequestModel, context);

    update();
    getProduct();
    return productModel;
  }

  runFilter(String enteredKeyword) {
    productData = enteredKeyword.isEmpty
        ? productModel!.data
        : productModel!.data!
            .where((element) => element.skycode!
                .toLowerCase()
                .contains(enteredKeyword.toLowerCase()))
            .toList();
    update();
  }

  selectAllValue(bool value) {
    isSelected = value;
    newItemAddList.forEach((element) {
      if (isSelected) {
        element.isSelected = isSelected;
      } else {
        element.isSelected = isSelected;
      }
    });
    update();
  }
}





   Expanded(
                          child: Padding(
                            padding: const EdgeInsets.only(
                                top: 5, left: 20, right: 10),
                            child: GetBuilder<ProductController>(
                              init: ProductController(),
                              builder: (productController) {
                                return productController.productData != null &&
                                        productController.productData!.isEmpty
                                    ? Center(
                                        child: CircularProgressIndicator(),
                                      )
                                    : TableScreen(
                                        sortAscending: addQuatationController
                                            .sortAscending,
                                        sortColumnIndex: addQuatationController
                                            .sortColumnIndex,
                                        sortingTap: (index, ascending) {
                                          addQuatationController.sorting(
                                            (d) => d.name,
                                            index,
                                            ascending,
                                          );
                                        },
                                        dataColumnOne: AppString.area,
                                        dataColumnTwo: AppString.skuCode,
                                        dataColumnThree: AppString.image,
                                        dataColumnFour: AppString.description,
                                        dataColumnFive: AppString.mrp,
                                        dataColumnSix: AppString.qty,
                                        dataColumnSeven: AppString.gamut,
                                        dataColumnEight: AppString.disc,
                                        dataColumnNine: AppString.netAmt,
                                        dataColumnSizeSix: ColumnSize.S,
                                        dataColumnSizeFour: ColumnSize.M,
                                        dataColumnSizeSeven: ColumnSize.S,
                                        dataColumnSizeNine: ColumnSize.S,
                                        dataColumnSizeEight: ColumnSize.S,
                                        rows: List.generate(
                                          productController.itemAddList.length,
                                          (index) {
                                            productController
                                                .itemAddList[index]
                                                .mrpController
                                                .text = productController
                                                    .itemAddList[index].mrp ??
                                                0.toString();
                                            return DataRow(
                                              cells: [
                                                ///Area
                                                DataCell(TextField(
                                                  controller:
                                                      TextEditingController(
                                                    text: productController
                                                        .itemAddList[index]
                                                        .areaController
                                                        .text,
                                                  ),
                                                  onChanged: (val) {
                                                    productController
                                                        .itemAddList[index]
                                                        .areaController
                                                        .text = val;
                                                  },
                                                  style: Get.theme.textTheme
                                                      .displayLarge,
                                                )),

                                                ///SKU code
                                                DataCell(TextField(
                                                  readOnly: true,
                                                  onTap: () async {
                                                    List<ProductData>?
                                                        response =
                                                        await itemSelectList(
                                                      context,
                                                    );
                                                    if (response != null &&
                                                        response.isNotEmpty) {
                                                      productController
                                                          .itemAddList
                                                          .removeAt(
                                                        productController
                                                                .itemAddList
                                                                .length -
                                                            1,
                                                      );
                                                      productController
                                                          .itemAddList
                                                          .addAll(response);
                                                      productController
                                                          .itemAddList
                                                          .add(ProductData());
                                                      productController
                                                          .update();
                                                    }
                                                  },
                                                  controller:
                                                      TextEditingController(
                                                    text: productController
                                                        .itemAddList[index]
                                                        .skycode,
                                                  ),
                                                  style: Get.theme.textTheme
                                                      .displayLarge!
                                                      .copyWith(
                                                          color: Colors.red),
                                                )),

                                                ///Images
                                                DataCell(
                                                  SizedBox(
                                                    height: 120,
                                                    child: Image.file(
                                                      File(
                                                        productController
                                                                .itemAddList[
                                                                    index]
                                                                .img ??
                                                            AppImagePath
                                                                .emtyImg,
                                                      ),
                                                      height: 80,
                                                      width: 80,
                                                    ),
                                                  ),
                                                ),

                                                ///Description
                                                DataCell(TextField(
                                                  readOnly: true,
                                                  controller:
                                                      TextEditingController(
                                                    text: productController
                                                        .itemAddList[index]
                                                        .category,
                                                  ),
                                                  style: Get.theme.textTheme
                                                      .displayLarge,
                                                )),

                                                ///  Mrp
                                                DataCell(
                                                  TextField(
                                                    controller: productController
                                                                .itemAddList[
                                                                    index]
                                                                .mrpController
                                                                .text ==
                                                            "0"
                                                        ? TextEditingController()
                                                        : productController
                                                            .itemAddList[index]
                                                            .mrpController,
                                                    onChanged: (val) {
                                                      productController
                                                          .itemAddList[index]
                                                          .mrp = val;
                                                    },
                                                    style: Get.theme.textTheme
                                                        .displayLarge,
                                                  ),
                                                ),

                                                /// qty
                                                DataCell(TextField(
                                                  onChanged: (value) {
                                                    productController
                                                        .itemAddList[index]
                                                        .qtyController
                                                        .text = value;
                                                    productController
                                                            .itemAddList[index]
                                                            .qtyController
                                                            .selection =
                                                        TextSelection
                                                            .fromPosition(
                                                      TextPosition(
                                                        offset:
                                                            productController
                                                                .itemAddList[
                                                                    index]
                                                                .qtyController
                                                                .text
                                                                .length,
                                                      ),
                                                    );
                                                    productController.sum(
                                                      double.parse(
                                                        productController
                                                            .itemAddList[index]
                                                            .mrpController
                                                            .text,
                                                      ),
                                                      double.parse(value),
                                                      index,
                                                    );
                                                  },
                                                  controller: productController
                                                      .itemAddList[index]
                                                      .qtyController,
                                                  style: Get.theme.textTheme
                                                      .displayLarge,
                                                )),

                                                ///GAmt
                                                DataCell(TextField(
                                                  readOnly: true,
                                                  controller:
                                                      TextEditingController(
                                                    text: (productController
                                                                .itemAddList[
                                                                    index]
                                                                .gAmt ??
                                                            productController
                                                                .itemAddList[
                                                                    index]
                                                                .mrp ??
                                                            '')
                                                        .toString(),
                                                  ),
                                                  style: Get.theme.textTheme
                                                      .displayLarge,
                                                )),

                                                /// Discount
                                                DataCell(TextField(
                                                  onChanged: (value) {
                                                    productController
                                                        .itemAddList[index]
                                                        .dis = double.parse(
                                                      value.toString(),
                                                    );
                                                    productController
                                                            .itemAddList[index]
                                                            .nAmt =
                                                        productController.Disc(
                                                      dis_per: double.parse(
                                                        value ?? '0',
                                                      ),
                                                      mrp: double.parse(
                                                        productController
                                                            .itemAddList[index]
                                                            .gAmt
                                                            .toString(),
                                                      ),
                                                      index: index,
                                                    );
                                                  },
                                                  controller: productController
                                                      .itemAddList[index]
                                                      .discController,
                                                  style: Get.theme.textTheme
                                                      .displayLarge,
                                                )),

                                                ///net Amount
                                                DataCell(TextField(
                                                  readOnly: true,
                                                  controller:
                                                      TextEditingController(
                                                    text: (productController
                                                                .itemAddList[
                                                                    index]
                                                                .nAmt ??
                                                            productController
                                                                .itemAddList[
                                                                    index]
                                                                .mrp ??
                                                            '')
                                                        .toString(),
                                                  ),
                                                  style: Get.theme.textTheme
                                                      .displayLarge,
                                                )),
                                              ],
                                            );
                                          },
                                        ),
                                      );
                              },
                            ),
                          ),
                        ),
Editor is loading...