//
//  EZDeviceRecordDirectQueryVC.m
//  EZOpenSDKDemo
//
//  Created by JuneCheng on 2025/12/30.
//  Copyright © 2025 hikvision. All rights reserved.
//

#import "EZDeviceRecordDirectQueryVC.h"

#import "MJRefresh.h"

#import "EZDeviceRecordFile.h"
#import "EZDeviceRecordInfo.h"

static NSInteger const kPageSize = 20;

@interface EZDeviceRecordDirectQueryVC ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;///< 录像列表

@property (nonatomic, strong) NSMutableArray<EZDeviceRecordFile *> *deviceRecordArray;///< 录像数组
@property (nonatomic, strong) EZDeviceRecordInfo *lastestDeviceRecordInfo;///< 上一次录像查询对象
@property (nonatomic, strong) NSDate *beginTime;///< 录像查询开始时间
@property (nonatomic, strong) NSDate *endTime;///< 录像查询结束时间

@end

@implementation EZDeviceRecordDirectQueryVC

#pragma mark 生命周期

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"NVR下的IPC设备录像直查";
    
    [self.view addSubview:self.tableView];
    [self setUpRefresh];
}

#pragma mark - Request

/** 获取设备录像接口 */
- (void)getDeviceRecordList:(NSDate *)beginTime {
    [EZOpenSDK searchRecordFileFromDeviceEx:self.deviceSerial
                                   cameraNo:1
                                  beginTime:beginTime
                                    endTime:self.endTime
                          videoRecordTypeEx:EZVideoRecordTypeExNone
                             isQueryFromNvr:NO
                        videoRecordLocation:EZVideoRecordLocationLocal
                                   pageSize:kPageSize
                                 completion:^(EZDeviceRecordInfo * _Nonnull deviceRecordInfo, NSError * _Nullable error) {
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        if (error) {
            [EZToast show:[NSString stringWithFormat:@"%@", error]];
            [self.tableView.footer endRefreshingWithNoMoreData];
            return;
        }
        if ([beginTime isEqual:self.beginTime]) {
            [self.deviceRecordArray removeAllObjects];
        }
        self.lastestDeviceRecordInfo = deviceRecordInfo;
        [self.deviceRecordArray addObjectsFromArray:deviceRecordInfo.deviceRecordFileList];
        [self.tableView reloadData];
        if (!deviceRecordInfo.hasMore) {
            [self.tableView.footer endRefreshingWithNoMoreData];
        }
    }];
}

#pragma mark UITableView delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.deviceRecordArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"deviceRecordCellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleGray;

    EZDeviceRecordFile *deviceRecordFile = self.deviceRecordArray[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ - %@ (%@)", [deviceRecordFile.startTime formattedDateWithFormat:HmsFormat], [deviceRecordFile.stopTime formattedDateWithFormat:HmsFormat], [self getRecordDurationWithStopTime:deviceRecordFile.stopTime startTime:deviceRecordFile.startTime]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - Custom Methods

- (void)setUpRefresh {
    EZWeak(self);
    self.tableView.header.automaticallyChangeAlpha = YES;
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        EZStrong(self);
        [strongself getDeviceRecordList:strongself.beginTime];
    }];
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        EZStrong(self);
        [strongself getDeviceRecordList:strongself.lastestDeviceRecordInfo.nextFileTime];
    }];
    [self.tableView.header beginRefreshing];
}

/** 计算录像时长 */
- (NSString *)getRecordDurationWithStopTime:(NSDate *)stopTime startTime:(NSDate *)startTime {
    double _duringSeconds = [stopTime secondsLaterThan:startTime];
    int minute =  (int)_duringSeconds / 60;
    int seconds = (int)_duringSeconds % 60;
    
    return [NSString stringWithFormat:@"%d'%d\"", minute, seconds];
}

#pragma mark 懒加载

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kContentViewHeight) style:UITableViewStylePlain];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (NSMutableArray<EZDeviceRecordFile *> *)deviceRecordArray {
    if (!_deviceRecordArray) {
        _deviceRecordArray = [NSMutableArray array];
    }
    return _deviceRecordArray;
}

- (NSDate *)beginTime {
    // iOS15.4 + 设置-通用-日期与时间-24小时制关闭情况下，需要设置NSDateFormatter的local为zh_CN，否则转换有问题。本demo已在分类里做了统一设置
    NSString *beginTimeString = [NSString stringWithFormat:@"%@ 00:00:00", [[NSDate date] formattedDateWithFormat:yMdFormat]];
    _beginTime = [NSDate dateWithString:beginTimeString formatString:yMdHmsFormat];
    return _beginTime;
}

- (NSDate *)endTime {
    NSString *endTimeString = [NSString stringWithFormat:@"%@ 23:59:59", [[NSDate date] formattedDateWithFormat:yMdFormat]];
    _endTime = [NSDate dateWithString:endTimeString formatString:yMdHmsFormat];
    return _endTime;
}

@end
