//
//  FeedBackController.m
//  KKCivilAd
//
//  Created by 雷俊博 on 2020/8/20.
//  Copyright © 2020 雷俊博. All rights reserved.
//

#import "FeedBackController.h"
#import "FeedTopView.h"
#import "FeedInputView.h"
#import "FeedAddImageView.h"
#import "FeedTFPhoneView.h"
#import "UIImage+Extension.h"
#import <Reachability/Reachability.h>
#import "UIViewController+DismissKeyboard.h"

@interface FeedBackController ()<FeedTopViewDelegate,FeedAddImageViewDelegate,UITextViewDelegate,UITextFieldDelegate>
{
    int strTitleIndex;
}

@property (nonatomic, strong)UIScrollView* scrollView;

@property (nonatomic, strong)FeedTopView* topView;

@property (nonatomic, strong)FeedInputView* inputView;

@property (nonatomic, strong)FeedAddImageView* addView;

@property (nonatomic, strong)FeedTFPhoneView* phoneView;

@property (nonatomic, strong)NSMutableArray*base64StrArray;

@property (nonatomic, strong)UIButton* commitBtn;

@property (nonatomic, strong)UIView *redView;

@end

@implementation FeedBackController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
     self.view.backgroundColor = [UIColor whiteColor];
    self.base64StrArray = [NSMutableArray array];
    
    [self navConfig];
    
    [self.view addSubview:self.scrollView];
    
    [self.topView btnClick:self.topView.btn1];
    
    [self creatBottomView];
    
    [self.phoneView.tf_phone addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    [self setupForDismissKeyboard];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
    [self getUnreadState];
}

- (void)navConfig
{
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80, 40)];
       
    [rightBtn setTitle:@"反馈消息" forState:UIControlStateNormal];
       
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:17];
       
   [rightBtn addTarget:self action:@selector(goToMessageListVC) forControlEvents:UIControlEventTouchUpInside];
   
   
   UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 80, 40)];
   [view addSubview:rightBtn];
   
   UIView *redView = [[UIView alloc]initWithFrame:CGRectMake(72, 4, 8, 8)];
   redView.backgroundColor = [UIColor redColor];
   redView.layer.cornerRadius= 4;
   redView.layer.masksToBounds = YES;
   [view addSubview:redView];
   
   redView.hidden = YES;
   
   self.redView = redView;
   
   UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:view];
   
   self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)creatBottomView
{
    CGFloat padding = 0.0;
    if (cl_kNavigationBarHeight > 64) {
        padding = 20;
    }
    UIButton* submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    submitBtn.frame = CGRectMake(0, ScreenHeight  - 44 - padding, ScreenWidth, 44);
    [submitBtn setTitle:@"提交反馈" forState:UIControlStateNormal];
    [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    submitBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    submitBtn.backgroundColor = K_MainColor;
    [submitBtn addTarget:self action:@selector(submitBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    submitBtn.userInteractionEnabled = NO;
    submitBtn.alpha = 0.5;
    self.commitBtn = submitBtn;
    [self.view addSubview:submitBtn];
    
}

#pragma mark - 查询未读消息
- (void)getUnreadState
{
    NSInteger user_id = [getPeopleID PeopleID];
    NSDictionary *params = @{
                                    @"userId":@(user_id),
                                    @"appType":FeedAppType
                            };
    NSString *url =[NSString stringWithFormat:@"%@/socialsecurity/kankan/getUnreadState",[NetworkConfig ipKKSBConfig]];
    
    [NetworkRequest SBAuthPost:url Params:params Success:^(id _Nonnull objc) {
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *code = [objc[@"code"] stringValue];
            if ([code isEqualToString:@"0"]) {
                NSDictionary *dic = objc[@"result"];
                if ([dic[@"newUnread"] isKindOfClass:[NSNumber class]] ) {
                    NSNumber *newUnread = dic[@"newUnread"];
                    self.redView.hidden = newUnread.integerValue == 0;
                   
                }
            }
        }
    } Failure:^(NSError* error) {
        
    }];
          
}

#pragma mark - FeedTopViewDelegate
- (void)btnClick:(MarkBtn *)sender value:(NSNumber *)btnValue
{
    NSLog(@"sender:%@ btnValue:%@",sender,btnValue);
    strTitleIndex = btnValue.intValue;
}

#pragma mark - FeedAddImageViewDelegate
- (void)addImage
{
    [self selectPhoto];
}
- (void)deleteImgWithIndex:(NSInteger)index
{
    [self.addView.imagesArray removeObjectAtIndex:index];
    [self.base64StrArray removeObjectAtIndex:index];
    [self.addView.collectionView reloadData];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView
{
    self.inputView.descLab.hidden = YES;
    //self.sendBtn.userInteractionEnabled = YES;
    //self.sendBtn.backgroundColor = MainColor;
    
    
    
    //字数限制
    if (textView.text.length >= 250) {
        textView.text = [textView.text substringToIndex:250];
    }
    
    if (textView.text.length == 0) {
        [self setButtonState];
    }else{
        [self setButtonState];
    }
    
    //实时显示字数
    self.inputView.stringLengthLab.text = [NSString stringWithFormat:@"%ld/250",(long)textView.text.length];
   
   //取消按钮点击权限，并显示文字
   if (textView.text.length == 0) {
       self.inputView.descLab.hidden = NO;
       //self.sendBtn.userInteractionEnabled = NO;
       //self.sendBtn.backgroundColor = [UIColor lightGrayColor];
   }
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        
        [textView resignFirstResponder];
        
        return NO;
    }
    
    return YES;
}


#pragma mark - 刷新按钮状态
- (void)setButtonState {
    if ((self.inputView.FKTextView.text.length) != 0) {
        self.commitBtn.userInteractionEnabled = YES;
        self.commitBtn.alpha = 1;
    } else {
        self.commitBtn.userInteractionEnabled = NO;
        self.commitBtn.alpha = 0.5;
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - public methods
-(id)getXiblWithClassName:(NSString *)className
{
    return [[NSBundle mainBundle]loadNibNamed:className owner:self options:nil].lastObject;
}

#pragma mark - 选择拍照还是选择图片
- (void)selectPhoto
{
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    
    UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }]];
    
    [alertVC addAction:[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    image = [image scaleToWidth:480];
    
    NSData*data = UIImageJPEGRepresentation(image, 0.85);
    NSString*base64Str = [data base64EncodedStringWithOptions:0];
    
    [self.base64StrArray addObject:base64Str];
    [self.addView.imagesArray addObject:image];
    
    [self.addView.collectionView reloadData];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (error == nil){
        NSLog(@"Image was saved successfully.");
    } else {
        NSLog(@"An error happened while saving the image.");
        NSLog(@"Error = %@", error);
    }
}


#pragma mark - event response
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
- (void)goToMessageListVC
{

    
  
    
    
    WebVC * webVC = [[WebVC alloc]init];
    webVC.title = @"反馈记录";
    //外网http://nginx.weface.com.cn/lesson/award/src/award.html
    //内网@"http://172.16.10.121/award/src/award.html"
    //webVC.url = @"http://nginx.weface.com.cn/lesson/award/feedback/index.html";
    NSString *urlStr = [NSString stringWithFormat:@"http://nginx.weface.com.cn/lesson/award/feedback/index.html?userId=%ld&appType=%@",(long)[getPeopleID PeopleID],FeedAppType];//外网
     //NSString *urlStr = [NSString stringWithFormat:@"http://172.16.10.133/projects/html-nginx/html-nginx/lesson/award/feedback/index.html?userId=%ld&appType=%@",(long)[getPeopleID PeopleID],FeedAppType];//外网
    //NSString *urlStr = [NSString stringWithFormat:@"http://172.16.10.121/projects/html-nginx/html-nginx/lesson/award/feedback/index.html?userId=%ld",[getPeopleID PeopleID]];//内网
    webVC.url = urlStr;
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void) textFieldDidChange:(id) sender {

    [self setButtonState];

}

- (void)submitBtnClick:(UIButton *)sender
{
    if (strTitleIndex == 0) {
        [Tools showMessage:@"请选择问题类型"];
        return;
    }
    
    if (self.inputView.FKTextView.text.length == 0) {
        [Tools showMessage:@"请输入您的反馈问题"];
        return;
    }
    
    if (self.phoneView.tf_phone.text.length == 0) {
        [Tools showMessage:@"请输入您的手机号码或微信号"];
        return;
    }
    
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipKKSBConfig],CommitAdviceInfoRequest];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSInteger user_id = [getPeopleID PeopleID];
    
    //手机型号
    NSString* phoneModel = [[UIDevice currentDevice] model];
    
    //手机系统版本
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    //app版本号
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    NSDictionary* params = nil;
    
    if (self.base64StrArray.count > 0) {
        params =@{
        @"user_id":@(user_id),
        @"advice_type":@(strTitleIndex),
        @"content_text":[EnercryTool encryptUseDES:self.inputView.FKTextView.text key:DESKEY],
        @"contact_style":self.phoneView.tf_phone.text ? self.phoneView.tf_phone.text : @"",
        @"photostr":[self.base64StrArray componentsJoinedByString:@","],
        @"frommodel":@2,
        @"mobile_model":phoneModel,
        @"mobile_maker":@"apple",
        @"mobile_system":phoneVersion,
        @"version_no":app_Version,
        @"net_state":[self internetStatus],
        @"appType":FeedAppType
        };
    }else{
        params =@{
               @"user_id":@(user_id),
               @"advice_type":@(strTitleIndex),
               @"content_text":[EnercryTool encryptUseDES:self.inputView.FKTextView.text key:DESKEY],
               @"contact_style":self.phoneView.tf_phone.text ? self.phoneView.tf_phone.text : @"",
               @"frommodel":@2,
               @"mobile_model":phoneModel,
               @"mobile_maker":@"apple",
               @"mobile_system":phoneVersion,
               @"version_no":app_Version,
               @"net_state":[self internetStatus],
               @"appType":FeedAppType
        };
        
    }
    NSLog(@"意见反馈url:%@",url);
    NSLog(@"params:%@",params);
    [SVProgressHUD show];
    [NetworkRequest Post2:url Params:params Success:^(id _Nonnull objc) {
        [SVProgressHUD dismiss];
        NSLog(@"objc:%@",objc);
        NSString*code = [NSString stringWithFormat:@"%@",objc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            [SVProgressHUD showSuccessWithStatus:@"提交成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [SVProgressHUD showErrorWithStatus:@"提交失败"];
        }
    } Failure:^(NSError* error) {
        [SVProgressHUD dismiss];
        NSLog(@"error:%@",error);
        [SVProgressHUD showErrorWithStatus:@"提交失败"];
    }];
    
    
}
#pragma mark - 获取网络状态
//获取当前网络状态
- (NSNumber *)internetStatus {
    
    Reachability *reachability   = [Reachability reachabilityWithHostName:@"www.apple.com"];
    
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];
    
    NSNumber *net = nil;
    
    switch (internetStatus) {
            
        case ReachableViaWiFi:
            
            net = [NSNumber numberWithInt:1];
            
            break;
            
            
            
        case ReachableViaWWAN:
            
            
            net = [self getNetType];   //判断具体类型
            
            break;
            
            
            
        case NotReachable:
            
            net = [NSNumber numberWithInt:99];
            
            
            
        default:
            
            break;
            
    }
    
    
    
    return net;
    
}


- (NSNumber *)getNetType

{
    
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    
    NSNumber *netconnType = nil;
    
    NSString *currentStatus = info.currentRadioAccessTechnology;
   if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyWCDMA"]){
        
        netconnType = [NSNumber numberWithInt:3];
        
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMA1x"]){
        
        netconnType = [NSNumber numberWithInt:2];
        
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORev0"]){
        
        netconnType = [NSNumber numberWithInt:3];
        
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevA"]){
        
        netconnType = [NSNumber numberWithInt:3];
        
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevB"]){
        
        netconnType = [NSNumber numberWithInt:3];
        
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyLTE"]){
        
       netconnType = [NSNumber numberWithInt:4];
        
    }else{
        netconnType = [NSNumber numberWithInt:98];
    }
    
    return netconnType;
    
}


#pragma mark - getters
- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
        
        //顶部视图
        FeedTopView* topView = [self getXiblWithClassName:@"FeedTopView"];
        topView.delegate = self;
        [_scrollView addSubview:topView];
        self.topView = topView;
        [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(0);
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(ScreenWidth);
            make.height.mas_greaterThanOrEqualTo(50);
        }];
        //中部视图
        FeedInputView* inputView = [self getXiblWithClassName:@"FeedInputView"];
        inputView.FKTextView.delegate = self;
        [_scrollView addSubview:inputView];
        self.inputView = inputView;
        inputView.FKTextView.delegate = self;
        [inputView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(topView.mas_bottom).offset(4);
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(ScreenWidth);
            make.height.mas_greaterThanOrEqualTo(50);
        }];
        
        //添加图片视图
        FeedAddImageView* addView = [self getXiblWithClassName:@"FeedAddImageView"];
        addView.delegate = self;
        [_scrollView addSubview:addView];
        self.addView = addView;
        [addView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(inputView.mas_bottom).offset(5);
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(ScreenWidth);
            make.height.mas_greaterThanOrEqualTo(50);
        }];
        //添加手机号视图
        FeedTFPhoneView* phoneView = [self getXiblWithClassName:@"FeedTFPhoneView"];
        phoneView.tf_phone.delegate = self;
        [_scrollView addSubview:phoneView];
        self.phoneView = phoneView;
        [phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(addView.mas_bottom).offset(10);
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(ScreenWidth);
            make.height.offset(40);
            make.bottom.mas_equalTo(0);
        }];
        
        
    }
    
    
    return _scrollView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
