//
//  JCSwitchFormCell.m
//  EZOpenSDKDemo
//
//  Created by JuneCheng on 2026/3/12.
//  Copyright © 2026 hikvision. All rights reserved.
//

#import "JCSwitchFormCell.h"

#import "JCFormItem.h"
#import "JCFormSwitchItem.h"

static NSString * const ID = @"JCSwitchFormCell";

@interface JCSwitchFormCell()

@property (nonatomic, strong) UILabel *lab_title;
@property (nonatomic, strong) UISwitch *sw_switch;

@end

@implementation JCSwitchFormCell

+ (instancetype)cellWithTableView:(UITableView *)tableView cellStyle:(UITableViewCellStyle)style {
    JCSwitchFormCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[self alloc] initWithStyle:style reuseIdentifier:ID];
    }
    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setUI];
        [self setLayout];
    }
    return self;
}

/** 创建UI */
- (void)setUI {
    _lab_title = [[UILabel alloc] init];
    [self.contentView addSubview:_lab_title];
    
    _sw_switch = [[UISwitch alloc] init];
    _sw_switch.onTintColor = HEXColor(0x1890FF);
    _sw_switch.transform = CGAffineTransformMakeScale(0.8f, 0.8f);
    [_sw_switch addTarget:self action:@selector(switchAction) forControlEvents:UIControlEventValueChanged];
    [self.contentView addSubview:_sw_switch];
}

/** 设置约束 */
- (void)setLayout {
    [_lab_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(15);
        make.centerY.equalTo(self);
        make.right.equalTo(_sw_switch.mas_left);
    }];
    [_sw_switch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self);
        make.right.equalTo(self).offset(-15);
    }];
}

/** 按钮事件 */
- (void)switchAction {
    JCFormSwitchItem *item = (JCFormSwitchItem *)self.item;
    if (item.switchBlock) {
        item.switchBlock(self.sw_switch.on);
    }
}

/** UI赋值 */
- (void)setItem:(JCFormItem *)item {
    _item = item;
    [self fillData];
    [self changeUI];
}

/** 数据填充 */
- (void)fillData {
    self.lab_title.textColor = self.item.titleColor;
    // 是否必填
    if (self.item.isRequired) {
        NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"* %@", self.item.title]];
        [attrString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,2)];
        self.lab_title.attributedText = attrString;
    } else {
        self.lab_title.text = self.item.title;
    }
    self.sw_switch.on = ((JCFormSwitchItem *)self.item).status;
}

/** UI调整 */
- (void)changeUI {
    self.lab_title.font = self.item.titleFont;
    
}

@end
