//
//  GasStationinvoiceVC.m
//  Open
//
//  Created by qinxuyang on 2021/11/29.
//  Copyright © 2021 QXY. All rights reserved.
//

#import "GasStationinvoiceVC.h"
#import "GasStationinvoiceCell.h"
#import "GasStationDetailsFooterView.h"
#import "AreaPickerView.h"
@interface GasStationinvoiceVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) GasStationDetailsFooterView *footerView;
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, assign) int titleIndex; //0公司，1个人
@property (nonatomic, copy) NSString *titleName;
@property (nonatomic, copy) NSString *buyerTaxNo;//购方纳税人识别号
@property (nonatomic, copy) NSString *buyerName;//购方单位名称
@property (nonatomic, copy) NSString *buyerAddress;//购方单位地址
//@property (nonatomic, copy) NSString *Address;//详细地址
@property (nonatomic, copy) NSString *buyerPhone;//购方单位电话
@property (nonatomic, copy) NSString *buyerBank;//购方单位开户行
@property (nonatomic, copy) NSString *buyerAccount;//购方单位账号'
@property (nonatomic, copy) NSString *buyerEmail;//购方客户邮箱
@property (nonatomic, strong) AreaPickerView *areaPickerView;
@end

@implementation GasStationinvoiceVC
- (NSArray *)titleArr{
    if (_titleArr == nil) {
        _titleArr = @[@"抬头类型",@"纳税人识别号",@"单位名称",@"所在地区",@"电话",@"邮箱",@"开户行",@"账号"];
    }
    return _titleArr;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self configNav];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.tableFooterView = self.footerView;
}
- (void)configNav
{
   UIView*nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    nav.backgroundColor = [UIColor colorWithHex:0x086ed7];
    [self.view addSubview:nav];
    
    UIButton*backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:backBtn];
    
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.top.offset(cl_kStatusBarHeight);
        make.width.offset(80);
        make.height.offset(44);
    }];
    
    UILabel*titleLabel = [[UILabel alloc]init];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"发票信息";
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [nav addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.offset(cl_kStatusBarHeight);
        make.width.offset(80);
        make.height.offset(44);
    }];
}
- (void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)setModel:(IoninvoiceModel *)model{
    _model = model;
    
    self.buyerTaxNo = model.buyerTaxNo;
    self.buyerName = model.buyerName;
    self.buyerAddress = model.buyerAddress;
    self.buyerPhone = model.buyerPhone;
    self.buyerBank = model.buyerBank;
    self.buyerAccount = model.buyerAccount;
    self.buyerEmail = model.buyerEmail;
}
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//推荐该方法
        [_tableView registerNib:[UINib nibWithNibName:@"GasStationinvoiceCell" bundle:nil] forCellReuseIdentifier:@"GasStationinvoiceCell"];
    }
    return _tableView;
}
- (GasStationDetailsFooterView *)footerView
{
    if (!_footerView) {
        _footerView = [[[NSBundle mainBundle] loadNibNamed:@"GasStationDetailsFooterView" owner:self options:nil] firstObject];
        _footerView.frame = CGRectMake(0, 0, ScreenWidth, 150);
        [_footerView.NextBtn setTitle:@"开发票" forState:UIControlStateNormal];
        [_footerView.NextBtn addTarget:self action:@selector(nextBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _footerView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleArr.count;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    GasStationinvoiceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GasStationinvoiceCell"];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"GasStationinvoiceCell" owner:self options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.contentTextField.delegate = self;
    cell.titleLab.text = self.titleArr[indexPath.row];
    if ([cell.titleLab.text isEqualToString:@"抬头类型"]) {
        cell.contentTextField.text = self.titleName;
        cell.contentTextField.placeholder = @"请选择";
    }
    if ([cell.titleLab.text isEqualToString:@"纳税人识别号"]) {
        cell.contentTextField.text = self.buyerTaxNo;
        if (self.titleIndex == 0) {
            cell.contentTextField.placeholder = @"请填写";
        }else{
            cell.contentTextField.placeholder = @"选填";
        }
    }
    if ([cell.titleLab.text isEqualToString:@"单位"]) {
        cell.contentTextField.text = self.buyerName;
        cell.contentTextField.placeholder = @"请填写";
    }
    if ([cell.titleLab.text isEqualToString:@"所在地区"]) {
        cell.contentTextField.text = self.buyerAddress;
        cell.contentTextField.placeholder = @"选填";
    }
    if ([cell.titleLab.text isEqualToString:@"电话"]) {
        cell.contentTextField.keyboardType = UIKeyboardTypePhonePad;
        cell.contentTextField.text = self.buyerPhone;
        cell.contentTextField.placeholder = @"选填";
    }
    if ([cell.titleLab.text isEqualToString:@"邮箱"]) {
        cell.contentTextField.text = self.buyerEmail;
        cell.contentTextField.placeholder = @"请填写";
    }
    if ([cell.titleLab.text isEqualToString:@"开户行"]) {
        cell.contentTextField.text = self.buyerBank;
        cell.contentTextField.placeholder = @"选填";
    }
    if ([cell.titleLab.text isEqualToString:@"账户"]) {
        cell.contentTextField.keyboardType = UIKeyboardTypePhonePad;
        cell.contentTextField.text = self.buyerAccount;
        cell.contentTextField.placeholder = @"选填";
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//    GasOrderModel *model = self.dataArr[indexPath.row];
  
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    GasStationinvoiceCell *cell = (GasStationinvoiceCell *)textField.superview.superview;
    if([[UIDevice currentDevice].systemVersion floatValue] < 8.0) {
        cell = (GasStationinvoiceCell *)textField.superview.superview.superview;
    }
    if (self.isNoEditor && ![cell.titleLab.text isEqualToString:@"邮箱"]) {
        return NO;
    }
    if ([cell.titleLab.text isEqualToString:@"抬头类型"]) {
        [self.view endEditing:YES];
        [self chooseType];
        return NO;
    }
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    GasStationinvoiceCell *cell = (GasStationinvoiceCell *)textField.superview.superview;
    if([[UIDevice currentDevice].systemVersion floatValue] < 8.0) {
        cell = (GasStationinvoiceCell *)textField.superview.superview.superview;
    }
    if ([cell.titleLab.text isEqualToString:@"纳税人识别号"]) {
        self.buyerTaxNo = textField.text;
    }
    if ([cell.titleLab.text isEqualToString:@"单位"]) {
        self.buyerName = textField.text;
    }
    if ([cell.titleLab.text isEqualToString:@"所在地区"]) {
        self.buyerAddress = textField.text;
    }
    if ([cell.titleLab.text isEqualToString:@"电话"]) {
        self.buyerPhone = textField.text;
    }
    if ([cell.titleLab.text isEqualToString:@"邮箱"]) {
        self.buyerEmail = textField.text;
    }
    if ([cell.titleLab.text isEqualToString:@"开户行"]) {
        self.buyerBank = textField.text;
    }
    if ([cell.titleLab.text isEqualToString:@"账号"]) {
        self.buyerAccount = textField.text;
    }
}
- (void)chooseType{
    typeof(self) wSelf = self;
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"个人" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        wSelf.titleIndex = 1;
        wSelf.titleName = @"个人";
        [wSelf.tableView reloadData];
    }];
    [alertVc addAction:takePhotoAction];
    UIAlertAction *imagePickerAction = [UIAlertAction actionWithTitle:@"公司" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        wSelf.titleIndex = 0;
        wSelf.titleName = @"公司";
        [wSelf.tableView reloadData];
    }];
    [alertVc addAction:imagePickerAction];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVc addAction:cancelAction];
    [self presentViewController:alertVc animated:YES completion:nil];
}
#pragma mark ---所在地区---
- (void)chooseAddress {
    typeof(self) wSelf = self;
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    _areaPickerView = [[[NSBundle mainBundle] loadNibNamed:@"AreaPickerView" owner:self options:nil] lastObject];
    [_areaPickerView setFrame:window.bounds];
    _areaPickerView.addressType = address_type;
    [_areaPickerView createPickerView];
    [window addSubview:_areaPickerView];
    _areaPickerView.selectProviceAndCityBlock = ^(NSDictionary * _Nonnull proviceDict, NSDictionary * _Nonnull cityDict, NSDictionary * _Nonnull areaDict) {
        NSLog(@"地址proviceDict: %@\ncityDict: %@\areaDict: %@",proviceDict,cityDict,areaDict);
//        wSelf.proviceDict = proviceDict;
//        wSelf.cityDict = cityDict;
//        wSelf.areaDict = areaDict;
//
//        wSelf.mercProv = [proviceDict objectForKey:@"code"];
//        wSelf.mercCity = [cityDict objectForKey:@"code"];
//        wSelf.mercArea = [areaDict objectForKey:@"code"];
//
//        wSelf.MerchantsAddress = [NSString stringWithFormat:@"%@ %@ %@",[proviceDict objectForKey:@"name"],[cityDict objectForKey:@"name"],[areaDict objectForKey:@"name"]];
        [wSelf.tableView reloadData];
        
    };
}
#pragma mark - 发票信息
- (void)requestData{
}
#pragma mark - 开具发票
- (void)nextBtn{
    if (self.buyerTaxNo.length == 0 && self.titleIndex == 0) {
        [XYProgressHUD showMessage:@"请填写购方纳税人识别号"];
        return;
    }
    if (self.buyerName.length == 0) {
        [XYProgressHUD showMessage:@"请填写购方单位名称"];
        return;
    }
    if (self.buyerEmail.length == 0) {
        [XYProgressHUD showMessage:@"请填写购方客户邮箱"];
        return;
    }
    
    NSMutableDictionary *parms = [NSMutableDictionary dictionary];
    if (self.isNoEditor) {
        [parms setValue:self.model.serialNo forKey:@"serialNo"];
        [parms setValue:self.buyerEmail forKey:@"email"];
        NSString *GasToken =  [UserDefault valueForKey:@"GasToken"];
        if ([UserDefault valueForKey:@"GasToken"] && GasToken.length > 0) {
            [parms setValue:GasToken forKey:@"token"];
        }
        NSString *url = [NSString stringWithFormat:@"%@tuanyou/invoice/repeat",[NetworkConfig ipGasStationConfig]];
        typeof(self) wSelf = self;
        [NetworkRequest PostGasStation:url Params:parms Success:^(id _Nonnull objc) {
            if ([objc isKindOfClass:[NSDictionary class]]) {
                NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
                NSString* describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
                if ([state isEqualToString:@"200"]) {
                    [XYProgressHUD showMessage:@"发送成功"];
                   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^(void) {
                        [wSelf.navigationController popViewControllerAnimated:YES];
                   });
                }else{
                    [wSelf alertShowMessage:describe];
                }
            }
        } Failure:^(NSError *error) {
            NSLog(@"error:%@",error);
        }];
        
        return;
    }
    [parms setValue:@(_titleIndex) forKey:@"title"];
    [parms setValue:self.buyerTaxNo forKey:@"buyerTaxNo"];
    [parms setValue:self.buyerName forKey:@"buyerName"];
    [parms setValue:[NSString stringWithFormat:@"%@|%@",self.buyerAddress,self.buyerPhone] forKey:@"buyerAddressPhone"];
    [parms setValue:[NSString stringWithFormat:@"%@|%@",self.buyerBank,self.buyerAccount] forKey:@"buyerBankAccount"];
    [parms setValue:self.buyerEmail forKey:@"buyerEmail"];
    [parms setValue:self.orders forKey:@"orders"];
    [parms setValue:self.buyerPhone forKey:@"tel"];
    NSString *GasToken =  [UserDefault valueForKey:@"GasToken"];
    if ([UserDefault valueForKey:@"GasToken"] && GasToken.length > 0) {
        [parms setValue:GasToken forKey:@"token"];
    }
    NSString *url = [NSString stringWithFormat:@"%@tuanyou/invoice/save",[NetworkConfig ipGasStationConfig]];
    typeof(self) wSelf = self;
    [NetworkRequest PostGasStation:url Params:parms Success:^(id _Nonnull objc) {
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
            NSString* describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                [XYProgressHUD showMessage:@"开票成功"];
               dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^(void) {
                    [wSelf.navigationController popViewControllerAnimated:YES];
               });
            }else{
                [wSelf alertShowMessage:describe];
            }
        }
    } Failure:^(NSError *error) {
        NSLog(@"error:%@",error);
    }];
}
#pragma mark - 提示
- (void)alertShowMessage:(NSString *)msg
{
    if (@available(iOS 9.0,*)) {
        
        UIAlertController * alertV = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertV addAction:confirm];
        
        [self presentViewController:alertV animated:YES completion:nil];
        
    }else{
        UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertV show];
    }
}
/*
#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
