//
//  UserConterController.m
//  AIIM
//
//  Created by gan on 2025/4/6.
//

#import <Foundation/Foundation.h>
#import "UserConterController.h"
#import "SecurityController.h"
#import "FavoritesController.h"
#import "BlackListController.h"
#import "ChatSettingController.h"
#import "config.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "UDManager.h"
#import "UserNetApi.h"
#import "ZhanghaoCntroller.h"
#import "PersonalInfoController.h"
#import "GDBManager.h"
#import <AdSupport/AdSupport.h>
#import "WebViewController.h"

@interface UserConterController()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIImageView *avatar;
@property (weak, nonatomic) IBOutlet UILabel *nameLb;
@property (weak, nonatomic) IBOutlet UILabel *qianmLb;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property(nonatomic, strong) NSMutableArray *cellDatas;



@end

@implementation UserConterController

-(void)viewDidLoad{
    [super viewDidLoad];
    
    NSString *vendorIdentifier = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSLog(@"vendorIdentifier:%@",vendorIdentifier);
    
    [self initCellData];
    [self initsubView];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [self setNavigationBarHidden:YES animated:YES];
    NSLog(@"viewWillAppear------------");
    [self getUserinfo];
}

-(void)initsubView{
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellT"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"tuichu"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate =self;
    _tableView.dataSource = self;
    [self showUserData];
    
}


-(void)initCellData{
    
    NSDictionary *d1 =@{
        @"name":@"userCenter-gerenxinx",
        @"image":@"wgerenxx",
    };
    NSDictionary *d2 =@{
        @"name":@"userCenter-qiehuanyy",
        @"image":@"wqiehyy",
    };
    NSDictionary *d3 =@{
        @"name":@"userCenter-zitidax",
        @"image":@"wzitidx",
    };
    NSDictionary *d4 =@{
        @"name":@"userCenter-zhanghaoaq",
        @"image":@"wzitidx",
    };
    NSDictionary *d7 =@{
        @"name":@"userCenter-shoucjia",
        @"image":@"wscjia",
    };
    NSDictionary *d8 =@{
        @"name":@"userCenter-heimdan",
        @"image":@"wheimd",
    };
    NSDictionary *d9 =@{
        @"name":@"userCenter-liaotsz",
        @"image":@"wliaotsz",
    };
    NSDictionary *d10 =@{
        @"name":@"userCenter-yinsizhc",
        @"image":@"wyinsisz",
    };
    NSDictionary *d11 =@{
        @"name":@"userCenter-tianjiabmd",
        @"image":@"wbaimdan",
    };
    
    NSDictionary *d14 =@{
        @"name":@"userCenter-tuichudl",
        @"image":@"",
    };
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    
    NSDictionary *d15 =@{
        @"name":[NSString stringWithFormat:@"版本号:%@(%@)",app_Version,app_build],
        @"image":@"",
    };
    
    _cellDatas = [[NSMutableArray alloc] init];
    [_cellDatas addObject:d1];
//    [_cellDatas addObject:d2];
//    [_cellDatas addObject:d3];
    [_cellDatas addObject:d4];
    [_cellDatas addObject:d7];
    [_cellDatas addObject:d8];
    [_cellDatas addObject:d9];
    [_cellDatas addObject:d10];
//    [_cellDatas addObject:d11];
    [_cellDatas addObject:d14];
    [_cellDatas addObject:d15];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section =indexPath.section;
    NSString *cellT =@"cellT";
    if(section>=_cellDatas.count-2){
        cellT =@"tuichu";
    }
    
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellT forIndexPath:indexPath];
    
    if(cell==nil){
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellT];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    NSDictionary *time =_cellDatas[section];
    NSString *title = NSLocalizedString(time[@"name"], @"");
    
    if(section>=_cellDatas.count-2){
        CGRect ctfrm = cell.contentView.frame;
        UILabel *titleLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, ctfrm.size.width, 52)];
        titleLb.text =title;
        titleLb.textColor = [UIColor whiteColor];
        titleLb.textAlignment = NSTextAlignmentCenter;
        titleLb.font = [UIFont systemFontOfSize:17.0f];
        [cell.contentView addSubview:titleLb];
    }
    else{
        cell.imageView.image = [UIImage imageNamed:time[@"image"]];
        cell.textLabel.text =title;
        cell.textLabel.textColor = [UIColor whiteColor];
        UIImageView *right = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow-right"]];
        CGRect ctfrm = cell.contentView.frame;
        right.frame = CGRectMake(ctfrm.size.width-30, 21, 20, 20);
        [cell.contentView addSubview:right];
    }
    
    cell.contentView.layer.borderWidth = 0.5f;
    cell.contentView.layer.borderColor = [UIColor lightGrayColor].CGColor; //globalColor(GCTypeGreen);
    cell.contentView.layer.cornerRadius = 8.0f; // 可选，设置圆角
    return cell;

}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==_cellDatas.count-2){
        [self tuichudengl];
    }
    if (indexPath.section == 0) {
        NSLog(@"111111---------");
        PersonalInfoController * personalInfoVc = [[PersonalInfoController alloc] init];
        personalInfoVc.hidesBottomBarWhenPushed = YES;
       
//        personalInfoVc.infoRefreshBlock = ^{
//            NSDictionary *userinfo = [UDManager.shareInstance getDDManager:dkuserinfo];
//            weakself.nameLb.text = userinfo[@"name"];
//            [weakself.avatar sd_setImageWithURL:getURL(userinfo[@"avatar"]) placeholderImage:kImageMake(@"Avatar")];
//        };
        [self.navigationController pushViewController:personalInfoVc animated:YES];
    }
    if(indexPath.section==1){
        SecurityController * securityVc = [[SecurityController alloc] init];
        securityVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:securityVc animated:YES];

    }
    
    if (indexPath.section == 2) {
        FavoritesController * favoritesVc = [[FavoritesController alloc] init];
        favoritesVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:favoritesVc animated:YES];
    }
    
    if (indexPath.section == 3) {
        BlackListController * blackListVc = [[BlackListController alloc] init];
        blackListVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:blackListVc animated:YES];
    }
    
    if (indexPath.section == 4) {
        ChatSettingController * chatSettingVc = [[ChatSettingController alloc] init];
        chatSettingVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:chatSettingVc animated:YES];
    }
    
    if (indexPath.section == 5) {
        WebViewController *webVC = [[WebViewController alloc] initWithURL:getURL(privacyPolicy)];
        [self.navigationController pushViewController:webVC animated:YES];
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _cellDatas.count;
}

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

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    CGFloat height =10.0;
    if(section==1){
        height =0.0;
    }
    return height;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    CGFloat height =10.0;
    if(section==1){
        height =0.0;
    }
    UIView *view =[[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, height)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

#pragma mark allactions

-(void)tuichudengl{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认"
                                                                  message:@"确定要退出登录吗？"
                                                           preferredStyle:UIAlertControllerStyleAlert];
     
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"
                                                           style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * action) {
        // 点击取消后的操作
    }];
     
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定"
                                                     style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction * action) {
        [self logoutAccaut];
        // 点击确定后的操作
    }];
     
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}
-(void)logoutAccaut{
    [UserNetApi logout:nil succ:^(int code, NSDictionary * res) {
        NSLog(@"res:%@",res);
        [[NSNotificationCenter defaultCenter] postNotificationName: nkonLogoutSucc object:nil];
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"");
    }];
}


#pragma mark private

-(void)getUserinfo{
    NSString *token = [UDManager.shareInstance getSDManager:gkeytoken];
    if([token isKindOfClass:[NSString class]]&&token.length>10){
        [UserNetApi getUserinfo:^(int code, NSDictionary * res) {
            NSLog(@"%d", code);
            NSNumber *gcode=res[@"code"];
            NSDictionary *data=res[@"data"];
            NSLog(@"%@", res);
            if([gcode intValue]!=200){
                NSLog(@"%@",res[@"msg"]);
//                [MBProgressHUD showWithText:@"登录异常，请重新登录"];
                return;
            }
            NSDictionary *ps = @{@"avatar": data[@"avatar"]?:@"",
                                 @"deptId": data[@"deptId"]?:@"",
                                 //@"domainId":data[@"domainId"],
                                 @"email":data[@"email"]?:@"",
                                 @"id":data[@"id"]?:@"",
                                 @"mobile":data[@"mobile"]?:@"",
                                 @"name":data[@"name"]?:@"",
                                 //@"platformType":data[@"platformType"]?:@"",
                                 //@"registrationId":data[@"registrationId"]?:@"",
                                 @"sex":data[@"sex"]?:@"",
                                 //@"tgbotAdmin":data[@"tgbotAdmin"],
                                 //@"tgbotName":data[@"tgbotName"],
                                 //@"tgbotTk":data[@"tgbotTk"]?:@"",
                                 @"username":data[@"username"]?:@"",
                                 //@"uuid":data[@"uuid"],
                                 //@"voipTk":data[@"voipTk"]?:@""
                                };
            if([gcode intValue]==200){
                NSLog(@"ps:%@",ps);
                [UDManager.shareInstance setSDManager:ps[@"id"] key:dkuserId];
                [UDManager.shareInstance setDDManager:ps key:dkuserinfo];
                [self showUserData];
            }
            else{
                [self logoutAccaut];
            }
            
        } fail:^(NSError * _Nonnull error) {
            NSLog(@"%@", error);
        }];
    }
}

-(void)showUserData{
    NSDictionary *userinfo = [UDManager.shareInstance getDDManager:dkuserinfo];
    _nameLb.text = userinfo[@"name"];
    _qianmLb.alpha = 0;
    NSURL *av = [NSURL URLWithString:userinfo[@"avatar"]];
    _avatar.layer.cornerRadius = 41.0;
    _avatar.layer.borderWidth = 1.0;
    _avatar.layer.borderColor = [UIColor whiteColor].CGColor;
    [_avatar sd_setImageWithURL:av placeholderImage:[UIImage imageNamed:@"Avatar"]];
}

#pragma mark statusBar
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
@end
