import 'dart:convert';

import 'package:intl/intl.dart';
import 'package:logger/logger.dart';
import 'package:meta/meta.dart';
import 'package:redux/redux.dart';
import 'package:redux_thunk/redux_thunk.dart';
import 'package:satu/core/entity/transaction_entity.dart';
import 'package:satu/core/models/entity_data/transaction_data.dart';
import 'package:satu/core/models/flow/dao/transaction_dao.dart';
import 'package:satu/core/redux/state/journal_state.dart';
import 'package:satu/core/services/db_service.dart';
import 'package:satu/core/utils/locator.dart';
import 'package:satu/core/utils/logger.dart';

import '../store.dart';

@immutable
class SetJournalStateAction {
  const SetJournalStateAction(this.journalState);

  final JournalState journalState;
}

final Logger log = getLogger('SetJournalStateAction');

final DbService _dbService = locator<DbService>();

ThunkAction<AppState> navigateTab(int index) {
  return (Store<AppState> store) async {
    store.dispatch(SetJournalStateAction(JournalState(tabIndex: index)));
    loadJournalData(store);
  };
}

Future<void> loadJournalData(Store<AppState> store) async {
  try {
    log.i('loadJournalData');
    final int? appCompanyId = store.state.userState!.auth!.companyId;
    final List<Map<String, dynamic>> set = await _dbService.queryRowsWithWhere(
        transactionTableName,
        '$transactionColumnAppCompanyId = ?'
        ' and $transactionColumnStatus = ?'
        ' and $transactionColumnType in (?,?)',
        [
          appCompanyId,
          transactionStatusFinish,
          transactionTypeSell,
          transactionTypeReturnSell
        ],
        orderBy: '$transactionColumnCreatedAt asc');
    log.i(set.length);
    final List<TransactionDao> list = [];

    final DateFormat formatterDay = DateFormat('dd.MM.yyyy');
    final DateFormat formatterTime = DateFormat('Hms');

    for (final Map<String, dynamic> map in set) {
      final Transaction transaction = Transaction.fromMap(map);
      final TransactionData data =
          TransactionData.fromMap(jsonDecode(transaction.data!));
      final TransactionDao dao = TransactionDao();
      dao.id = transaction.id;
      final DateTime updateAt = DateTime.parse(transaction.updatedAt!);
      dao.day = formatterDay.format(updateAt);
      dao.date = formatterTime.format(updateAt);
      dao.contragentName = data.contragentName;
      dao.number = data.sellResponse?.journalId.toString() ?? '';
      dao.total = data.total;
      if (transaction.type == transactionTypeReturnSell) {
        dao.received = false;
      }

      list.add(dao);
    }
    store.dispatch(SetJournalStateAction(JournalState(
      items: list,
    )));
  } catch (e, stack) {
    log.e('loadJournalData', e, stack);
  }
}
