//
//  SMClientViewController.m
//  SkinMagnifier
//
//  Created by nana on 2020/11/6.
//

#import "SMClientViewController.h"
#import "SMSearchBar.h"
#import "SMClientCell.h"
#import "SMCreateClientViewController.h"
#import "SMTakeImageViewController.h"
#import "SMClientListModel.h"
#import "SMClientDetailViewController.h"
#import "SMLinkDeviceView.h"


@interface SMClientViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic, strong)UITableView *mainTableView;

@property(nonatomic, strong)NSMutableArray *dataArray;
@property(nonatomic, assign)bool isRequest;
@property(nonatomic, strong)NSString *searchString;
@end

@implementation SMClientViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray  = [[NSMutableArray alloc] init];
    self.view.backgroundColor = [UIColor whiteColor];
    self.wb_titleLabel.text = @"档案列表";
    SMSearchBar *searchBar = [[SMSearchBar alloc] init];
    @weakify(searchBar);
    searchBar.valueChangeBlock = ^(NSString * _Nonnull value, bool endEdit) {
        @strongify(searchBar);
        [self tfValueChange:searchBar.inputTF];
    };
    [self.view addSubview:searchBar];
    [searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(safaTop(77.5));
        make.height.mas_equalTo(35);
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
    }];
    
    self.mainTableView = [[UITableView alloc] init];
    @weakify(self);
    self.mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self);
        [self requestDataWithCurrerPage:@"1"];
    }];
    self.mainTableView.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
        @strongify(self);
        int page =  (int)self.dataArray.count / KPageSize ;
        page += self.dataArray.count % KPageSize?1:0;;
        NSString *pageString = [NSString stringWithFormat:@"%d",page+1];
        [self requestDataWithCurrerPage:pageString];
    }];
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mainTableView.dataSource = self;
    self.mainTableView.delegate = self;
    [self.mainTableView registerClass:[SMClientCell class] forCellReuseIdentifier:NSStringFromClass([SMClientCell class])];
    [self.view addSubview:self.mainTableView];
    [self.mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@150);
        make.bottom.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
    }];
    
    UIButton *createBtn = [[UIButton alloc] init];
    [createBtn wb_setImageName:@"list_button_add"];
    [createBtn addTarget:self action:@selector(createBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:createBtn];
    [createBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-100);
        make.right.mas_equalTo(-15);
    }];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.mainTableView reloadData];
    if (!islinkDeviceWifi()) {
        [self requestDataWithCurrerPage:@"1"];
    }

}

- (void)requestDataWithCurrerPage:(NSString *)page {
    self.isRequest = YES;
    NSMutableDictionary *pDict = [[NSMutableDictionary alloc] init];
    pDict[@"pageSize"] = [NSString stringWithFormat:@"%d",KPageSize];
    pDict[@"mid"] = [SMGlobalModel share].mid;
    pDict[@"currentPage"] = page;
    pDict[@"searchtxt"] = self.searchString;
    @weakify(self);
    [self.view postFormDataWithUrl:@"/magnifier/client/findClientList" params:pDict success:^(NSDictionary * _Nonnull responseObject, JFResponseModel * _Nonnull JsonData) {
        @strongify(self);
        self.isRequest = NO;
        [self.mainTableView.mj_header endRefreshing];
        [self.mainTableView.mj_footer endRefreshing];
        if ([JsonData.code isEqualToString:@"200"]) {
            
            NSArray *dataArray = [SMClientListModel mj_objectArrayWithKeyValuesArray:JsonData.data];
            
            if ([page isEqualToString:@"1"]) {
                [self.dataArray removeAllObjects];
            }
            if (dataArray) {
                [self.dataArray addObjectsFromArray:dataArray];
            }

            [self.mainTableView reloadData];
        }

    }];
}
- (void)createBtnClick:(UIButton *)btn {
    SMCreateClientViewController *vc = [SMCreateClientViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)tfValueChange:(UITextField *)tf {
    self.searchString = tf.text;
    if (self.isRequest == NO) {
        [self requestDataWithCurrerPage:@"1"];
    }

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SMClientListModel *model =  self.dataArray[indexPath.row];
    SMClientCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SMClientCell class])];

    [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:model.clientimg] placeholderImage:[UIImage imageNamed:@"customer_logo"]];
    cell.nameLabel.attributedText = createAttString(model.cname, 18, rgba(76, 74, 66, 1));

    NSString *dateString = timestampString(model.createtime.longLongValue/1000,@"YYYY/MM/dd");
    cell.timeLabel.attributedText = createAttString([NSString stringWithFormat:@"建档 %@",dateString], 12, rgba(153, 153, 153, 1));

    @weakify(self);
    cell.cameraBlock = ^{
        @strongify(self)
//        NSMutableDictionary *pDict = [[NSMutableDictionary alloc] init];
//        pDict[@"mid"] = [SMGlobalModel share].mid
//        [self.view postFormDataWithUrl:@"/magnifier/member/verifyMemberInfo" params:pDict success:^(NSDictionary * _Nonnull responseObject, JFResponseModel * _Nonnull JsonData) {
//            @strongify(self);
//            if ([JsonData.code isEqualToString:@"200"]) {
//
//            }else {
//
//            }
//        }];

        if (islinkDeviceWifi()) {
            SMTakeImageViewController *vc = [[SMTakeImageViewController alloc] init];
            vc.clinetModel =model;
            [self.navigationController pushViewController:vc animated:YES];
        }else {
            SMLinkDeviceView *linkView = [[SMLinkDeviceView alloc] init];
            linkView.flishBlock = ^{
                @strongify(self);
                SMTakeImageViewController *vc = [[SMTakeImageViewController alloc] init];
                vc.clinetModel =model;
                [self.navigationController pushViewController:vc animated:YES];
            };
            [linkView wb_showFromSuperView: self.view];
        }



        
        

    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    SMClientDetailViewController *vc = [[SMClientDetailViewController alloc] init];
    vc.clinetModel = self.dataArray[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
    
}
//-trailingSwipeActionsConfigurationForRowAtIndexPat
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    SMClientListModel *model = self.dataArray[indexPath.row];
    @weakify(self);
    UIContextualAction *deleteRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"delete" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
          //左滑删除之后数据处理操作
        @strongify(self);

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定删除当前顾客吗？" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *conform = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            NSMutableDictionary *pDict = [[NSMutableDictionary alloc] init];
            pDict[@"mid"] = [SMGlobalModel share].mid;
            pDict[@"clientid"] = model.ID;
            [self.view postFormDataWithUrl:@"/magnifier/client/delClientMagnifier" params:pDict success:^(NSDictionary * _Nonnull responseObject, JFResponseModel * _Nonnull JsonData) {
                if ([JsonData.code isEqualToString:@"200"]) {
                    @strongify(self);
                    [self.dataArray removeObjectAtIndex:indexPath.row];
                    [self.mainTableView reloadData];
                };
            }];
        }];
        
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:cancleAction];
        [alert addAction:conform];
        
        [self presentViewController:alert animated:YES completion:nil];

      }];
      deleteRowAction.image = [UIImage imageNamed:@"client_list_button_ch_delete"];//给删除赋值图片
      deleteRowAction.backgroundColor = rgba(233, 147, 117, 1);//删除背景颜色
      UISwipeActionsConfiguration *Configuration = [UISwipeActionsConfiguration configurationWithActions:@[deleteRowAction]];
      return Configuration;
}

@end
