//
//  feedbackViewController.m
//  Open
//
//  Created by 看看智能 on 2017/2/13.
//  Copyright © 2017年 黄江涛 . All rights reserved.
//

#import "feedbackViewController.h"
#import "adviceInfoNetModel.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "XWLocationManager.h"
#import <AddressBookUI/AddressBookUI.h>
#import "LQPhotoPickerViewController.h"

#import "HXProvincialCitiesCountiesPickerview.h"
#import "HXAddressManager.h"


#import "UITextView+ZWPlaceHolder.h"
#define MHSafeString(str) (str == nil ? @"" : str)
#define SCREENHEIGHT [UIScreen mainScreen].bounds.size.height//获取设备高度
#define SCREENWIDTH [UIScreen mainScreen].bounds.size.width//获
@interface feedbackViewController ()<UITextFieldDelegate,UITextViewDelegate,MKMapViewDelegate,CLLocationManagerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,LQPhotoPickerViewDelegate,UIAlertViewDelegate>
{
    NSInteger unreadCount;
}
@property (weak, nonatomic) IBOutlet UITextField *textFieldTitle;
@property (weak, nonatomic) IBOutlet UITextView *textFieldContent;
@property (weak, nonatomic) IBOutlet UIButton *editButton;

//按钮一
@property (weak, nonatomic) IBOutlet CLMarkButton *gongneng;

//按钮二
@property (weak, nonatomic) IBOutlet CLMarkButton *chanping;

//按钮三
@property (weak, nonatomic) IBOutlet CLMarkButton *qita;

@property (weak, nonatomic) IBOutlet UIView *picView;

@property (weak, nonatomic) IBOutlet UITextField *weixinContactTextField;
@property (strong, nonatomic) UITextField *weixinContactTextField1;

//s选择图片s的属性
@property(nonatomic,strong)NSMutableArray *picArr;

@property(nonatomic,strong)UIButton *buttomWithImage;

@property (nonatomic, strong)UIView *redView;


@end

@implementation feedbackViewController


-(NSMutableArray *)picArr{
    if (!_picArr) {
        _picArr =[NSMutableArray new];
    }
    return _picArr;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
//  CGRect yP=  [self LQPhotoPicker_getPickerViewFrame];
//    if (yP.size.height >100) {
//        self.tex
//    }
    
    self.picArr = [self LQPhotoPicker_getBigImageArray];
    if (self.LQPhotoPicker_selectedAssetArray.count == 4) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"choosePic_four" object:@"failure"];

    }
    
    
    self.navigationController.navigationBar.barTintColor = K_MainColor;
    
    [self.transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        self.navigationController.navigationBar.barTintColor = K_MainColor;
    } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
    }];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
    [self getUnreadState];
    
    
}
-(void)ageAchanges:(NSNotification*)notifi {
    NSLog(@"sdsad%@",notifi.object);
    
    NSString * ingsf =(NSString *)notifi.object;
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if ([ingsf isEqualToString:@"failure"] && self.LQPhotoPicker_selectedAssetArray.count == 4) {
   
                CGRect picFrame =  [self LQPhotoPicker_getPickerViewFrame];
                self.weixinContactTextField1.frame= CGRectMake(0, picFrame.origin.y+picFrame.size.height +15,SCREEN_HEIGHTL, 45);
//                [self.view layoutIfNeeded];
            
            
            
        }else if([ingsf isEqualToString:@"success"]){
            CGRect picFrame =  [self LQPhotoPicker_getPickerViewFrame];
            self.weixinContactTextField1.frame= CGRectMake(0, picFrame.origin.y+picFrame.size.height +15,SCREEN_HEIGHTL, 45);
            [self.view layoutIfNeeded];
      
            
      
            
        }
        
    });
    
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //s字数
    self.labelasas.text =@"0";

     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ageAchanges:) name:@"choosePic_four" object:nil];
    self.gongneng.layer.borderColor = [UIColor colorWithRed:201/255.0 green:201/255.0 blue:201/255.0 alpha:0.5].CGColor;
    [self.gongneng setTitleColor:[UIColor colorWithRed:201/255.0 green:201/255.0 blue:201/255.0 alpha:0.5] forState:0];
    self.gongneng.layer.borderWidth = 1.0f;
    self.gongneng.layer.cornerRadius = 10.0;
    self.gongneng.enabled =YES;
    
    self.chanping.layer.borderColor = [UIColor colorWithRed:201/255.0 green:201/255.0 blue:201/255.0 alpha:0.5].CGColor;
    self.chanping.layer.borderWidth = 1.0f;
    [self.chanping setTitleColor:[UIColor colorWithRed:201/255.0 green:201/255.0 blue:201/255.0 alpha:0.5] forState:0];
    self.chanping.layer.cornerRadius = 10.0;
    
    self.qita.layer.borderColor = [UIColor colorWithRed:201/255.0 green:201/255.0 blue:201/255.0 alpha:0.5].CGColor;
    self.qita.layer.borderWidth = 1.0f;
    [self.qita setTitleColor:[UIColor colorWithRed:201/255.0 green:201/255.0 blue:201/255.0 alpha:0.5] forState:0];
    self.qita.layer.cornerRadius = 10.0;
  
    
    NSArray *arr = @[_gongneng,_chanping,_qita];
    [self  buttonUse:arr andID:235452];
    __weak __typeof(self)weakSelf = self;
    
    self.buttonX = ^(CLMarkButton *isNext) {
           weakSelf.gongneng.backgroundColor = [UIColor whiteColor];
          weakSelf.chanping.backgroundColor = [UIColor whiteColor];
          weakSelf.qita.backgroundColor = [UIColor whiteColor];
        [weakSelf.gongneng setTitleColor:[UIColor colorWithRed:201/255.0 green:201/255.0 blue:201/255.0 alpha:0.5] forState:0];
       [weakSelf.chanping setTitleColor:[UIColor colorWithRed:201/255.0 green:201/255.0 blue:201/255.0 alpha:0.5] forState:0];
         [weakSelf.qita setTitleColor:[UIColor colorWithRed:201/255.0 green:201/255.0 blue:201/255.0 alpha:0.5] forState:0];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            

            
            if (isNext == weakSelf.gongneng) {
                //t颜色
                weakSelf.gongneng.backgroundColor = kRGBColor(27, 132, 208);
                [weakSelf.gongneng setTitleColor:[UIColor whiteColor] forState:0];
                weakSelf.strTitle=1;
            }else if (isNext == weakSelf.chanping){
                weakSelf.chanping.backgroundColor =  kRGBColor(27, 132, 208);
                [weakSelf.chanping setTitleColor:[UIColor whiteColor] forState:0];
                weakSelf.strTitle=2;
            }else if (isNext == weakSelf.qita){
                weakSelf.qita.backgroundColor = kRGBColor(27, 132, 208);
                 [weakSelf.qita setTitleColor:[UIColor whiteColor] forState:0];
                weakSelf.strTitle=3;
            }
        });
    };
   
    
    
    
    
    self.title =@"意见反馈";
    //[self.view openKeyboardOffsetView];

    [self.editButton addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
    self.textFieldTitle.delegate =self;
    self.textFieldTitle.borderStyle= UITextBorderStyleRoundedRect;
    self.textFieldTitle.textAlignment= NSTextAlignmentLeft;
    
    //微信号

    
    
    self.textFieldContent.delegate =self;
    self.textFieldContent.returnKeyType = UIReturnKeyDefault;
    //self.textFieldContent.selectedRange=NSMakeRange(20,0) ;   //起始位置
    self.textFieldContent.placeholder = @"请写下您的宝贵意见";
    //按钮
  self.editButton.backgroundColor =kRGBColor(153, 153, 153);
//    self.editButton.layer.cornerRadius  =10;
//    self.editButton.layer.masksToBounds =YES;
   

    
    //图片选择器
    [self.view addSubview:self.LQPhotoPicker_superView];
     self.LQPhotoPicker_imgMaxCount = 4;
    [self LQPhotoPicker_initPickerView];
    self.LQPhotoPicker_delegate = self;
    UITapGestureRecognizer *get =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(asdasd)];
    [self.LQPhotoPicker_superView addGestureRecognizer:get];
    [self.pickerCollectionView addGestureRecognizer:get];
    [self.showActionSheetViewController.view addGestureRecognizer:get ];
    CGFloat XX = self.picView.frame.origin.y;
    CGFloat Heigh = self.picView.bounds.size.height;
    NSLog(@"Width:%f\nHeigh:%f",XX,Heigh);
    [self LQPhotoPicker_updatePickerViewFrameY:CGRectGetMaxY(self.picView.frame) + 10];
    
    
    CGRect picFrame =  [self LQPhotoPicker_getPickerViewFrame];
    
    
    
    self.weixinContactTextField1= [[UITextField alloc]initWithFrame:CGRectMake(0, picFrame.origin.y+picFrame.size.height +15,SCREEN_HEIGHTL, 45)];
    _weixinContactTextField1.placeholder=@" 请输入手机号和微信号码";
    _weixinContactTextField1.font=[UIFont systemFontOfSize:14];
    _weixinContactTextField1.clearButtonMode=UITextFieldViewModeWhileEditing;
//    self.weixinContactTextField.delegate =self;
//    self.weixinContactTextField.borderStyle= UITextBorderStyleRoundedRect;
//    self.weixinContactTextField.textAlignment= NSTextAlignmentLeft;
//    self.weixinContactTextField.keyboardGap =100;
    _weixinContactTextField1.backgroundColor= [UIColor whiteColor];
    _weixinContactTextField1.delegate=self;
    _weixinContactTextField1.textAlignment= NSTextAlignmentLeft;
    _weixinContactTextField1.keyboardGap =100;
    
    [self.view addSubview:_weixinContactTextField1];
    [self textFieldAddTwoBlackPlaceinTextFiled:_weixinContactTextField1];
    
    
    
    //键盘弹起
//        double delayInSeconds = 0.3;
//    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);    //    dispatch_after(popTime,
//        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//                [self.textFieldTitle becomeFirstResponder];
//        });
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];//在这里注册通知
    
    
    //kvo
   // [self.textFieldContent addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
    
    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;
    
  
    self.buttonX(self.gongneng);
    
    
}
//当key路径对应的属性值发生改变时，监听器就会回调自身的监听方法，如下
//- (void)observeValueForKeyPath:(NSString *)keyPath
//                      ofObject:(id)object
//                        change:(NSDictionary<NSKeyValueChangeKey,id> *)change
//                       context:(void *)context{
//    NSLog(@"=====新值=%@",[change objectForKey:@"new"]);


//}
- (void)textViewDidChange:(UITextView *)textView

{
   //设置不超过250个字符
 
    self.labelasas.text =[NSString stringWithFormat:@"%lu",(unsigned long)self.textFieldContent.text.length];
    if(self.textFieldContent.text.length >= 250){
        self.labelasas.text =[NSString stringWithFormat:@"%d",250];
    }
    if (self.textFieldContent.text.length > 260)
    {
      self.textFieldContent.text = [self.textFieldContent.text substringToIndex:250];
      
    }

}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"choosePic_four" object:nil];

}



- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    self.editButton.backgroundColor =kRGBColor(153, 153, 153);
    self.editButton.userInteractionEnabled =NO;
//    NSDictionary *userInfo = notification.userInfo;
    

//    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 执行动画
 
        // 工具条的Y值 == 键盘的Y值 - 工具条的高度
        if(self.textFieldContent.text.length >1 && self.strTitle >0){
            self.editButton.backgroundColor =kRGBColor(27, 132, 208);
            self.editButton.userInteractionEnabled =YES;
            return;
        }
    
}
- (void)submitToServer{
    [self.picArr removeAllObjects];
    self.picArr = [self LQPhotoPicker_getBigImageArray];
    //大图数据
    //    NSMutableArray *bigImageDataArray = [self LQPhotoPicker_getBigImageDataArray];
    //小图数组
    //    NSMutableArray *smallImageArray = [self LQPhotoPicker_getSmallImageArray];
    //小图数据
    //    NSMutableArray *smallImageDataArray =
    //    self.picArr= [self LQPhotoPicker_getSmallDataImageArray];
}

-(void)action:(UIButton*)button
{
    
    
    button.userInteractionEnabled = NO;
    [self submitToServer];
    if (!self.strTitle) {
        [SVProgressHUD doneShow];
        return [SVProgressHUD showErrorWithStatus:@"请选择类型"];
}
    if (!self.weixinContactTextField1.text && self.weixinContactTextField1.text.length >250) return;
 if (!self.textFieldContent.text) return;
    [KKLoadingAnimationView show];
[adviceInfoNetModel getAdvideInfoUserId:[getPeopleID PeopleID] andTitle_name:self.strTitle andContent_text:self.textFieldContent.text andImage:self.picArr andcontact_style:self.weixinContactTextField1.text Handle:^(postMessageModel *model, NSError *error) {
    [KKLoadingAnimationView dismiss];
    if(error){
        [KKLoadingAnimationView dismiss];
        [SVProgressHUD showErrorWithStatus:@"提交失败"];
        return;
    }
    
    
    if ([model.code isEqualToString:@"0"]) {
        [SVProgressHUD showSuccessWithStatus:@"提交成功"];
        [self.navigationController popViewControllerAnimated:YES];
    }else
    {
        [SVProgressHUD showErrorWithStatus:@"提交失败"];
    }
   button.userInteractionEnabled = YES;
    
}];


}
//
//- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
//{
// 
//    self.textFieldContent.contentOffset = (CGPoint){.x = 0,.y = 0};
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

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


#pragma mark - event response

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    [self.LQPhotoPicker_superView 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",[getPeopleID PeopleID]];//外网
    //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];
}
//test

-(void)asdasd{
    [self.view endEditing:YES];
    [self.LQPhotoPicker_superView endEditing:YES];

}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];

    
    
    
    return YES;

}

//控制清除按钮的位置

-(CGRect)clearButtonRectForBounds:(CGRect)bounds

{
    
    return CGRectMake(bounds.origin.x + bounds.size.width - 50, bounds.origin.y + bounds.size.height -20, 16, 16);
    
}


//控制placeHolder的位置，左右缩20

-(CGRect)placeholderRectForBounds:(CGRect)bounds

{
    
    
    
    //return CGRectInset(bounds, 20, 0);
    
    CGRect inset = CGRectMake(bounds.origin.x+100, bounds.origin.y, bounds.size.width -10, bounds.size.height);//更好理解些
    
    return inset;
    
}

//控制显示文本的位置

-(CGRect)textRectForBounds:(CGRect)bounds

{
    
    //return CGRectInset(bounds, 50, 0);
    
    CGRect inset = CGRectMake(bounds.origin.x+190, bounds.origin.y, bounds.size.width -10, bounds.size.height);//更好理解些
    
    
    
    return inset;
    
    
}

//控制编辑文本的位置

-(CGRect)editingRectForBounds:(CGRect)bounds

{
    
    
    CGRect inset = CGRectMake(bounds.origin.x +10, bounds.origin.y, bounds.size.width -10, bounds.size.height);
    
    return inset;
    
}











@end
