//
//  ShopDetaileViewController.m
//  XFFruit
//
//  Created by mac on 15/8/19.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "ShopDetaileViewController.h"
#import "SurveyCell.h"
#import "HPGrowingTextView.h"
#import "StartTimeView.h"
#import "ChosePersonViewController.h"
#import "ChooseProductViewController.h"
#import "ChooseProductUnitViewController.h"
#import "GXFSearchVendorViewController.h"
#import "GXFProductUnit.h"
#import "CalculateHelper.h"
#import "ProductStockModel.h"
#define LeftMargin 15
#define BtnHeight 44
#define TableHeight 46
#define CornerRadius 5
#define TitleSize 15
#define BtnSize 19
#define TotalHeight 432
#define KeyboardHeight 258
#define DateViewHeight 300
typedef enum : NSUInteger {
    SaveTag = 2000,
    CommitTag,
} BtnTag;
@interface ShopDetaileViewController ()<UITableViewDataSource,UITableViewDelegate,HPGrowingTextViewDelegate,UITextFieldDelegate,UIAlertViewDelegate>
{
    UITableView *_tableView;
    NSMutableArray *_dataArr;
    UILabel *_productLabel;
    UILabel *_PackagingLable;
    UITextField *packageSpecification;//包装规格
    UITextField *packageQuantity;     //包装数量
    UITextField *foundationQuantity;  //基础数量
    UITextField *foundationUnitPrice; //基础单价
    UITextField *packageUnitPrice;    //包装单价
    UITextField *totalMoney;          //总金额
    UITextField *counterNum;//柜台
    /** 考核单价 */
    UITextField *_checkPriceTextField;
    /** 考核总金额 */
    UITextField *_checkTotalTextField;
    HPGrowingTextView *remark;        //备注
    UILabel *_measureUnitLabel;  //默认规格单位
    UILabel *_packageCountLabel; //包装数量
    UILabel *_baseCountLabel;    //基础数量
    UILabel *_counterNum;//柜台
    /** 考核单价 */
    UILabel *_checkPriceLabel;
    /** 考核总金额 */
    UILabel *_checkTotalLabel;
    
}
@property (nonatomic,strong)NSString *productCodeStr;//商品代码
@property (nonatomic,strong)NSString *productNameStr;//商品名字
@property (nonatomic,strong)NSString *productUuidStr;//商品code
@property (nonatomic,strong)NSString *productMeasureUnit;//默认规格单位
@property (nonatomic,strong)NSString *packageQpcStr;    //规格描述
@property (nonatomic,strong)NSString *packageUintStr;    //包装单位

@property (nonatomic,strong)NSNumber *packPrice;//包装单价
@property (nonatomic,strong)NSNumber *basePrice;//基础单价
@property (nonatomic,strong)NSNumber *totalPrice;//总金额

/** 考核单价 */
@property (strong, nonatomic) NSNumber *checkPrice;

/** 考核总金额 */
@property (strong, nonatomic) NSNumber *checkTotal;
@property (nonatomic,strong)NSMutableArray *selectProducts;
@property (nonatomic,strong)NSString *selectUnit;

@end

@implementation ShopDetaileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.navTitle;
    [self initData];
    [self setupSubviews];
}
- (void)initData{
    _dataArr = [NSMutableArray array];
    self.selectProducts = [NSMutableArray array];
    [_dataArr addObject:@"商品"];
    [_dataArr addObject:@"包装单位"];
    [_dataArr addObject:@"包装规格"];
    [_dataArr addObject:@"包装数量"];
    [_dataArr addObject:@"基础数量"];
    [_dataArr addObject:@"基础单价"];
    [_dataArr addObject:@"包装单价"];
    [_dataArr addObject:@"总金额"];
    if (self.intertype == ShopDetailInterTypePurchase) {
        [_dataArr addObject:@"柜号"];
    }
    [_dataArr addObject:@"备注"];
    
    if (self.intertype == ShopDetailInterTypeTransport) {
        [_dataArr addObject:@"考核单价"];
        [_dataArr addObject:@"考核总金额"];
    }
    
}

-(void)setupSubviews
{
    _tableView = [[UITableView alloc]initWithFrame:(CGRectMake(0, 0,ScreenSize.width, ScreenHeight - 64 - LeftMargin)) style:(UITableViewStylePlain)];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.bounces = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, 50)];
    
    
    UIButton *saveBtn =  [IBTCustomButtom creatButtonWithFrame:CGRectMake(LeftMargin, 10, (ScreenSize.width - LeftMargin*3)/2, BtnHeight) target:self sel:@selector(btnClick:) tag:SaveTag image:nil title:@"删除" titleColor: [UIColor whiteColor] isCorner:YES corner:CornerRadius bgColor:GXF_SAVE_COLOR];
    [footView addSubview:saveBtn];
    
    UIButton *commitBtn = [IBTCustomButtom creatButtonWithFrame:CGRectMake(saveBtn.frame.origin.x + saveBtn.frame.size.width + LeftMargin, 10, (ScreenSize.width - LeftMargin*3)/2, BtnHeight) target:self sel:@selector(btnClick:) tag:CommitTag image:nil title:@"保存" titleColor: [UIColor whiteColor] isCorner:YES corner:CornerRadius bgColor:GXF_COMMIT_COLOR];
    [footView addSubview:commitBtn];
    
    _tableView.tableFooterView = footView;
    [self.view addSubview:_tableView];
    
}
- (void)setviewsData
{
    if (self.shopDetail!=nil) {
        //商品
        _productLabel.text = [NSString stringWithFormat:@"%@[%@]",self.shopDetail.merchandise,self.shopDetail.product_code];
        [self.selectProducts addObject:_shopDetail.product_uuid];
        //包装单位
        _PackagingLable.text = self.shopDetail.packageUnit;
        _packageCountLabel.text = self.shopDetail.packageUnit;
        self.selectUnit = self.shopDetail.packageUnit;
        
        //包装规格
        packageSpecification.text=self.shopDetail.packageSpecification;
        
        //包装规格单位
        self.shopDetail.packageQpcUnit ? (_measureUnitLabel.text =  self.shopDetail.packageQpcUnit) : (_measureUnitLabel.text = @"斤");
        self.shopDetail.packageQpcUnit ? (_baseCountLabel.text =  self.shopDetail.packageQpcUnit) : (_baseCountLabel.text = @"斤");
        
        //包装数量
        if ([self.shopDetail.packageQuantity floatValue] > 0) {
            packageQuantity.text=self.shopDetail.packageQuantity;
        }
        //基础数量
        foundationQuantity.text=self.shopDetail.foundationQuantity;
        //基础单价
        //        if ([self.shopDetail.foundationUnitPrice floatValue] > 0) {
        foundationUnitPrice.text= [self.shopDetail.foundationUnitPrice stringValue];
        //        }
        self.basePrice = self.shopDetail.foundationUnitPrice;
        
        //包装单价
        //        if ([self.shopDetail.packageUnitPrice floatValue] > 0) {
        packageUnitPrice.text=[self.shopDetail.packageUnitPrice stringValue];
        //        }
        self.packPrice = self.shopDetail.packageUnitPrice;
        //总金额
        if ([self.shopDetail.totalMoney floatValue] <= 0) {
            totalMoney.text=@"0.0000";
        }else{
            totalMoney.text=[self.shopDetail.totalMoney stringValue];
        }
        
        _checkTotalTextField.text = self.shopDetail.checkTotal.doubleValue > 0 ? self.shopDetail.checkTotal.stringValue : @"0.0000";
        self.checkTotal = self.shopDetail.checkTotal;
        _checkPriceTextField.text = self.shopDetail.checkPrice.doubleValue > 0 ? self.shopDetail.checkPrice.stringValue : @"0.0000";
        self.checkPrice = self.shopDetail.checkPrice;
        
        self.totalPrice = self.shopDetail.totalMoney;
        //备注
        remark.text=self.shopDetail.remark;
        
        _productLabel.textColor=GXF_CONTENT_COLOR;
        _PackagingLable.textColor=GXF_CONTENT_COLOR;
        counterNum.text = self.shopDetail.vnum;
        self.productCodeStr = self.shopDetail.product_code;
        self.productUuidStr = self.shopDetail.product_uuid;
        self.productNameStr = self.shopDetail.merchandise;
        self.packageQpcStr =  self.shopDetail.packageQpcStr;
        self.packageUintStr = self.shopDetail.packageUnit;
        
        
        
        self.productMeasureUnit = self.shopDetail.packageQpcUnit.length > 0 ? self.shopDetail.packageQpcUnit : @"斤";
    }
}
#pragma mark - 按钮点击事件
- (void)btnClick:(UIButton *)btn{
    switch (btn.tag) {
        case SaveTag://删除
        {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请确认删除" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
            alertView.delegate = self;
            [alertView show];
        }
            break;
        case CommitTag:
        {
            
            if ([self informationComplete]) {
                
                //只有发运单才需要差库存
                if (self.intertype == ShopDetailInterTypeTransport || self.intertype == ShopDetailInterTypeTranfer) {
                    __weak ShopDetaileViewController *weakSelf = self;
                    [self stockValidWithBillNumber:self.shopDetail.sourceBillNumber complete:^{
                        
                        ShopDetail *shopDetail=self.shopDetail;
                        shopDetail.IsDeleted=NO;
                        weakSelf.choseShopDetail(shopDetail);//回调
                        [weakSelf PopViewControllerAnimated:YES];
                    }];
                }else{
                    ShopDetail *shopDetail=self.shopDetail;
                    shopDetail.IsDeleted=NO;
                    self.choseShopDetail(shopDetail);//回调
                    [self PopViewControllerAnimated:YES];
                }
            }
        }
            break;
        default:
            break;
    }
}

- (void)stockValidWithBillNumber:(NSString *)billNumber complete:(void (^)(void))complete {
    __weak ShopDetaileViewController *weakSelf = self;
    IBTLoadingView *hud = [IBTLoadingView showHUDAddedTo:self.view animated:YES];
    [HTTP purchaseStockWithPurchaseUuid:billNumber product:self.shopDetail.product_code success:^(id succ) {
        [hud hide:YES];
        [IBTLoadingView hideHUDForView:weakSelf.view];
        if (![succ[@"data"] isKindOfClass:[NSArray class]]) {
            NSString *msg = [NSString stringWithFormat:@"采购单<%@>在总部系统的库存不足!", billNumber];
            ShowMessage(msg);
            return ;
        }
        
        for (NSDictionary *dict in succ[@"data"]) {
            ProductStockModel *model = [ProductStockModel new];
            [model setValuesForKeysWithDictionary:dict];
            if ([self.shopDetail.product_code isEqualToString:model.productCode]) {
                
                if ([[CalculateHelper decimalNumber:self.shopDetail.foundationQuantity] compare:decimalNumberWithDouble(model.qty)] == NSOrderedDescending) {
                    CLog(@"库存不足");
                    NSString *msg = [NSString stringWithFormat:@"采购单<%@>在总部系统的库存不足!", billNumber];
                    ShowMessage(msg);
                    return ;
                }
            }
            
        }
        
        complete();
        
    } failure:^(id fail) {
        [hud hide:YES];
        [IBTLoadingView showTips:fail];
    }];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        if (self.shopDetail!=nil) {
            ShopDetail *shopDetail=self.shopDetail;
            
            if (shopDetail.IsXiuGai==YES) {
                shopDetail.IsDeleted=YES;
                self.choseShopDetail(shopDetail);//回调
                [self PopViewControllerAnimated:YES];
            }else
            {
                [self  clearShopDetail];
            }
        }else
        {
            [self  clearShopDetail];
        }
        
    }
}

- (void)clearShopDetail
{
    _productLabel.text = @"选择商品";//商品
    
    _PackagingLable.text = @"选择包装单位";//包装单位
    packageSpecification.text = @"";//包装规格
    packageQuantity.text = @"";     //包装数量
    
    foundationQuantity.text = @"0";  //基础数量
    foundationUnitPrice.text = @""; //基础单价
    packageUnitPrice.text = @"0";    //包装单价
    totalMoney.text = @"0";          //总金额
    remark.text = @"";
    _productLabel.textColor=GXF_PLACEHOLDER_COLOR;
    _PackagingLable.textColor=GXF_PLACEHOLDER_COLOR;
}
- (BOOL)informationComplete{
    if (!self.shopDetail) {
        self.shopDetail=[[ShopDetail alloc]init];
    }
    self.shopDetail.product_code = self.productCodeStr;
    self.shopDetail.product_uuid = self.productUuidStr;
    self.shopDetail.merchandise = self.productNameStr;
    
    self.shopDetail.packageSpecification = packageSpecification.text;
    self.shopDetail.packageQpcStr = [NSString stringWithFormat:@"1*%@",packageSpecification.text];
    self.shopDetail.packageQpcUnit = self.productMeasureUnit;
    
    self.shopDetail.packageUnit = self.packageUintStr;
    self.shopDetail.packageQuantity = packageQuantity.text;
    self.shopDetail.packageUnitPrice = self.packPrice;
    
    self.shopDetail.foundationQuantity = foundationQuantity.text;
    self.shopDetail.foundationUnitPrice = self.basePrice;
    NSString *totalPrices = totalMoney.text;
    self.shopDetail.totalMoney = [NSDecimalNumber decimalNumberWithString:totalPrices];
    self.shopDetail.remark = remark.text;
    self.shopDetail.vnum = counterNum.text;
    self.shopDetail.checkPrice = self.checkPrice;
    self.shopDetail.checkTotal = self.checkTotal;
    
    
    if (self.productNameStr.length == 0 ) {
        ShowMessage(@"商品不能为空");
        return NO;
    }
    if (packageSpecification.text.length == 0 ) {
        ShowMessage(@"包装规格不能为空");
        return NO;
    }
    if (packageQuantity.text.length == 0 ) {
        ShowMessage(@"包装数量不能为空");
        return NO;
    }
    
    //    double max = self.shopDetail.receivedQty.doubleValue - self.shopDetail.shippedQty.doubleValue;
    //    if (packageQuantity.text.doubleValue > max && self.shopDetail.receivedQty != nil && self.shopDetail.shippedQty != nil){
    //        NSString *info = [NSString stringWithFormat:@"包装数量不得大于可运包装数[%.0f]", max];
    //        ShowMessage(info);
    //        return NO;
    //    }
    if (self.packageUintStr.length == 0) {
        ShowMessage(@"包装单位不能为空");
        return NO;
    }
    if (foundationQuantity.text.length == 0) {
        ShowMessage(@"基础数量不能为空");
        return NO;
    }
    if (foundationUnitPrice.text.length == 0) {
        ShowMessage(@"基础单价不能为空");
        return NO;
    }if (packageUnitPrice.text.length == 0) {
        ShowMessage(@"总金额不能为空");
        return NO;
    }
    
    if ([packageQuantity.text floatValue] <= 0 || [foundationQuantity.text floatValue] <= 0 || [packageSpecification.text floatValue] <= 0) {
        ShowMessage(@"商品数量不能为0");
        return NO;
    }
    //    if ([packageUnitPrice.text floatValue] <=0 || [foundationUnitPrice.text floatValue] <= 0 || [totalMoney.text floatValue]<= 0) {
    //        ShowMessage(@"商品价格不能0");
    //        return NO;
    //    }
    return YES;
}
#pragma mark - 协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return TableHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellID";
    SurveyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[SurveyCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row==0||indexPath.row==1) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        [self createViewInCell:cell indexPath:indexPath];
    }
    [cell setTitleStr:_dataArr[indexPath.row]];
    
    
    return cell;
}

-  (void)createViewInCell:(SurveyCell *)cell indexPath:(NSIndexPath *)indexPath{
    if (self.intertype == ShopDetailInterTypeTransport || self.intertype == ShopDetailInterTypeTranfer){
        cell.userInteractionEnabled = NO;
    }
    NSString *title = _dataArr[indexPath.row];
    if ([title isEqualToString:@"商品"] || [title isEqualToString:@"包装单位"]) {
        
        UILabel *contentLabel = [[UILabel alloc]initWithFrame:(CGRectMake(100+LeftMargin, 0, ScreenSize.width - 100 - LeftMargin*2-15, TableHeight))];
        contentLabel.textAlignment= NSTextAlignmentRight;
        contentLabel.textColor = GXF_PLACEHOLDER_COLOR;
        contentLabel.font = FontSize(TitleSize);
        [cell.contentView addSubview:contentLabel];
        if (indexPath.row==0) {
            _productLabel = contentLabel;
            contentLabel.text = @"选择商品";
        }else if (indexPath.row==1)
        {
            _PackagingLable = contentLabel;
            contentLabel.text = @"选择包装单位";
        }
    }else if ([title isEqualToString:@"备注"]){
        
        HPGrowingTextView * remarkTextView = [[HPGrowingTextView alloc] initWithFrame:CGRectMake(100+LeftMargin, 0, ScreenSize.width - 100 - LeftMargin*2-15, TableHeight)];
        remarkTextView.contentInset = UIEdgeInsetsMake(5, 5, 5, 0);
        remarkTextView.minNumberOfLines = 1;
        remarkTextView.maxNumberOfLines = 1;
        remarkTextView.isScrollable = YES;
        remarkTextView.font = GXF_FIFTEENTEN_SIZE;
        remarkTextView.textAlignment = NSTextAlignmentRight;
        remarkTextView.delegate = self;
        remarkTextView.returnKeyType = UIReturnKeyDone;
        remarkTextView.placeholder = @"输入备注内容";
        [cell.contentView addSubview:remarkTextView];
        remark=remarkTextView;              //备注
        
        if (self.intertype == ShopDetailInterTypeTransport || self.intertype == ShopDetailInterTypeTranfer){
            cell.userInteractionEnabled = YES;
        }
    }else{
        UITextField  *textField = [[UITextField alloc] initWithFrame:CGRectMake(100+LeftMargin, 0, ScreenSize.width - 100 - LeftMargin*2-30, TableHeight)];
        textField.textAlignment = NSTextAlignmentRight;
        textField.textColor = GXF_CONTENT_COLOR;
        textField.font = FontSize(15);
        textField.returnKeyType = UIReturnKeyDone;
        textField.keyboardType = UIKeyboardTypeDecimalPad;
        textField.delegate = self;
        [cell.contentView addSubview:textField];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(textField.frame)+ 5, 0, 30, TableHeight)];
        label.textColor = GXF_CONTENT_COLOR;
        label.font = GXF_FIFTEENTEN_SIZE;
        [cell.contentView addSubview:label];
        if ([title isEqualToString:@"包装规格"]) {
            UILabel *labelTwo = [[UILabel alloc]initWithFrame:CGRectMake(100+LeftMargin, 0, 50, TableHeight)];
            labelTwo.text = @"1*";
            labelTwo.textAlignment = NSTextAlignmentRight;
            [cell.contentView addSubview:labelTwo];
            textField.left = labelTwo.right;
            textField.width = textField.width - 50;
            label.left = textField.right+ 5;
            _measureUnitLabel = label;
            textField.placeholder = @"输入包装规格";
            textField.tag =111;
            
            textField.userInteractionEnabled = self.intertype != ShopDetailInterTypeTranfer;
            
            [textField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventAllEditingEvents];
            packageSpecification=textField;//包装规格
        }else if ([title isEqualToString:@"包装数量"]) {
            _packageCountLabel = label;
            textField.placeholder = @"输入包装数量";
            [textField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventAllEditingEvents];
            packageQuantity=textField;     //包装数量
            
            if (self.intertype == ShopDetailInterTypeTransport || self.intertype == ShopDetailInterTypeTranfer) {
                cell.userInteractionEnabled = YES;
            }
        }else if ([title isEqualToString:@"基础数量"]) {
            _baseCountLabel = label;
            [textField setEnabled:NO];
            textField.placeholder = @"基础数量";
            textField.textColor = GXF_NAVIGAYION_COLOR;
            foundationQuantity=textField;  //基础数量
        }else if ([title isEqualToString:@"基础单价"]) {
            label.text = @"元";
            textField.placeholder = @"输入基础单价";
            [textField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventAllEditingEvents];
            foundationUnitPrice=textField; //基础单价
            if (self.intertype == ShopDetailInterTypeTranfer){
                cell.userInteractionEnabled = !self.isLockBasePrice;
            }
        }else if ([title isEqualToString:@"包装单价"]) {
            label.text = @"元";
            [textField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventAllEditingEvents];
            textField.placeholder = @"输入包装单价";
            packageUnitPrice=textField;    //包装单价
            
        }else if ([title isEqualToString:@"总金额"]) {
            label.text = @"元";
            [textField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventAllEditingEvents];
            textField.placeholder = @"输入总金额";
            totalMoney=textField;          //总金额
        }else if ([title isEqualToString:@"柜号"]) {
            _counterNum = label;
            textField.placeholder = @"输入柜号";
            [textField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventAllEditingEvents];
            textField.keyboardType = UIKeyboardTypeDefault;
            counterNum=textField;     //包装数量
        }else if ([title isEqualToString:@"考核单价"]) {
            _checkPriceLabel = label;
            textField.placeholder = @"输入考核单价";
            [textField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventAllEditingEvents];
            textField.keyboardType = UIKeyboardTypeDefault;
            _checkPriceTextField=textField;
            cell.userInteractionEnabled = YES;
        }else if ([title isEqualToString:@"考核总金额"]) {
            _checkTotalLabel = label;
            textField.placeholder = @"输入考核总金额";
            [textField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventAllEditingEvents];
            textField.keyboardType = UIKeyboardTypeDefault;
            _checkTotalTextField=textField;
        }
    }
    
    
    
    
    
    
    [self  setviewsData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //选择商品
    if(indexPath.row == 0){
        ChooseProductViewController *cvc = [ChooseProductViewController new];
        if (self.selectProducts.count > 0) {
            cvc.selectArr = self.selectProducts;
        }
        cvc.choseBaseInfo = ^(NSArray  *products){
            Product *product=products [0];
            _productLabel.text = [NSString stringWithFormat:@"%@[%@]",product.name,product.code];
            _productLabel.textColor = GXF_CONTENT_COLOR;
            self.productNameStr = product.name;
            self.productUuidStr = product.uuid;
            self.productCodeStr = product.code;
            self.productMeasureUnit = product.measureUnit;
            if (self.selectProducts.count > 0) {
                [self.selectProducts removeAllObjects];
            }
            [self.selectProducts addObject:product.uuid];
            
            if (self.productMeasureUnit.length == 0) {
                _measureUnitLabel.text = @"斤";
                _baseCountLabel.text = @"斤";
            }else{
                _measureUnitLabel.text = self.productMeasureUnit;
                _baseCountLabel.text = self.productMeasureUnit;
            }
            [self setPackageUnit:product.purMeasureUnit];
        };
        cvc.isMoreChose = NO;
        [self PushViewController:cvc animated:YES];
    }else if (indexPath.row ==1)
    {
        ChooseProductUnitViewController *cvc = [ChooseProductUnitViewController new];
        if (self.selectUnit.length > 0) {
            cvc.selectStr = self.selectUnit;
        }
        cvc.choseBaseInfo = ^(NSArray  *products){
            if (products.count > 0) {
                GXFProductUnit *productUnit=products [0];
                [self setPackageUnit:productUnit.name];
            }
        };
        cvc.isMoreChose = NO;
        [self PushViewController:cvc animated:YES];
    }
}

/**
 *  设置包装单位
 *
 *  @param packageUnit 包装单位
 */
- (void)setPackageUnit:(NSString *)packageUnit {
    _PackagingLable.text = packageUnit;
    _PackagingLable.textColor = GXF_CONTENT_COLOR;
    _packageCountLabel.text = packageUnit;
    self.packageUintStr = packageUnit;
    self.selectUnit = packageUnit;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField.tag != 111) {
        return YES;
    }
    
    NSMutableString * futureString = [NSMutableString stringWithString:textField.text];
    //    kLOG(@"%@", futureString);
    [futureString  insertString:string atIndex:range.location];
    //    kLOG(@"----%@", futureString);
    NSInteger flag = 0;
    NSInteger pointNum = 0;//用于标记小数点的数量,只能有一个小数点
    const NSInteger limited = 4;//限制小数点后面的位数
    
    for (int i = (int)futureString.length - 1; i>=0; i--) {
        
        if ([futureString characterAtIndex:i] == '.') {
            pointNum++;
            //            kLOG(@"----->>>%ld",pointNum);
            if (pointNum == 2) {
                
                return NO;
                
            }
        }
    }
    
    for (int i = (int)futureString.length - 1; i>=0; i--) {
        
        if ([futureString characterAtIndex:i] == '.') {
            
            if (flag > limited) {
                
                return NO;
                
            }
            
            break;
            
        }
        
        flag++;
        
    }
    
    
    return YES;
}

#pragma mark - textFiled事件
- (void)textChange:(UITextField *)textField{
    //包装规格和包装数量
    if (textField == packageSpecification || textField == packageQuantity) {
        if (packageSpecification.text.length > 0 && packageQuantity.text.length > 0 ) {
            //计算基础数量  和 总金额和包装单价
            float baseCount = [packageSpecification.text floatValue] * [packageQuantity.text floatValue];
            foundationQuantity.text = [NSString stringWithFormat:@"%.2f",baseCount];
            //如果基础单价有  会计算出包装单价和总价
            //如果包装单价有 会计算出基础单价和总价
            [self setTotalMoney];
        }
    }else if(textField == foundationUnitPrice){
        //基础单价
        self.basePrice = [CalculateHelper decimalNumber:foundationUnitPrice.text];
        [self setPacktAndTotalPrice];
        //如果基础数量和包装数量有的话计算出包装单价和和总价
    }else if (textField == packageUnitPrice){
        //包装单价
        self.packPrice = [CalculateHelper decimalNumber:packageUnitPrice.text];
        [self setUnitAndTotalPrice];
    }else if(textField == totalMoney){
        //总金额
        self.totalPrice = [CalculateHelper decimalNumber:totalMoney.text];
        [self setUnitAndPackPrice];
    }else if (textField == _checkPriceTextField){
        self.checkPrice = [CalculateHelper calculateNum1:_checkPriceTextField.text num2:@(1) type:CalculateTypeMul roundingType:NSRoundBankers cutLenth:2];
        
        self.checkTotal = [CalculateHelper calculateNum1:_checkPriceTextField.text num2:foundationQuantity.text type:CalculateTypeMul roundingType:NSRoundBankers cutLenth:2];
        _checkTotalTextField.text = self.checkTotal.stringValue;
        
        
    }
}

- (void)setTotalMoney{
    //计算总金额和包装单价
    [self setPacktAndTotalPrice];
    [self setUnitAndTotalPrice];
}
- (void)setPacktAndTotalPrice{
    if (self.basePrice && foundationUnitPrice.text.length > 0) {
        if (foundationQuantity.text.length > 0) {
            NSDecimalNumber *multiplyResult = [CalculateHelper calculateNum1:self.basePrice num2:foundationQuantity.text type:CalculateTypeMul roundingType:NSRoundBankers cutLenth:2];
            totalMoney.text = [multiplyResult stringValue];
            self.totalPrice = multiplyResult;
            if (packageQuantity.text.length > 0 && [packageQuantity.text floatValue] > 0) {
                
                NSDecimalNumber *packagePrice = [CalculateHelper calculateNum1:multiplyResult num2:packageQuantity.text type:CalculateTypeDiv roundingType:NSRoundBankers cutLenth:2] ;
                
                packageUnitPrice.text = [packagePrice stringValue];
                self.packPrice = packagePrice;
            }
        }
    }
}
//输入包装单价(包装数量和基础数量)计算基础单价和总金额
- (void)setUnitAndTotalPrice{
    if (self.packPrice&&packageUnitPrice.text.length > 0) {
        if (packageQuantity.text.length > 0) {
            NSDecimalNumber *totalPrice = [CalculateHelper calculateNum1:self.packPrice num2:packageQuantity.text type:CalculateTypeMul roundingType:NSRoundBankers cutLenth:2];
            totalMoney.text = [totalPrice stringValue];
            self.totalPrice = totalPrice;
            if (foundationQuantity.text.length > 0 && [foundationQuantity.text integerValue] > 0) {
                NSDecimalNumber *packagePrice = [CalculateHelper calculateNum1:totalPrice num2:foundationQuantity.text type:CalculateTypeDiv roundingType:NSRoundBankers cutLenth:2];
                //                float packagePrice = totalPrice / [foundationQuantity.text floatValue];
                foundationUnitPrice.text = packagePrice.stringValue;
                self.basePrice = packagePrice;            }
        }
    }
}
//输入总金额(包装数量和基础数量)计算基础单价和包装单价
- (void)setUnitAndPackPrice{
    if (totalMoney.text.length > 0) {
        if (packageQuantity.text.length > 0 && [packageQuantity.text floatValue] > 0) {
            NSDecimalNumber *packagePrice = [CalculateHelper calculateNum1:self.totalPrice num2:packageQuantity.text type:CalculateTypeDiv roundingType:NSRoundBankers cutLenth:4];
            
            packageUnitPrice.text = packagePrice.stringValue;
            self.packPrice = packagePrice;
        }
        if (foundationQuantity.text.length > 0 && [foundationQuantity.text floatValue] > 0) {
            NSDecimalNumber *packagePrice = [CalculateHelper calculateNum1:self.totalPrice num2:foundationQuantity.text type:CalculateTypeDiv roundingType:NSRoundBankers cutLenth:4];
            foundationUnitPrice.text = packagePrice.stringValue;
            self.basePrice = packagePrice;
        }
    }
}
#pragma mark delegate
- (BOOL)growingTextViewShouldReturn:(HPGrowingTextView *)growingTextView{
    [remark resignFirstResponder];
    return YES;
}
- (void)keyboardHidden{
    [remark resignFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}

/*
 #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