//
//  PurchaseDetailViewController.m
//  XFFruit
//
//  Created by 陈俊俊 on 15/8/23.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "PurchaseDetailViewController.h"
#import "ProductBillViewController.h"
#import "PurchaseBillProduct.h"
#import "BottomPurchaseView.h"
#import "PurchaseReceiveProductViewController.h"
#import "TransferPdtDetail.h"
#import "NewReceiveProductViewController.h"
//#import "RejectView.h"
#define BottomHeight                                50
#define LeftMargin                                  15
#define LeftWidth                                   100
#define LeftHeight                                  30
#define TopMargin                                   15
#define OneWidth                                    (ScreenSize.width - LeftMargin * 2)
#define TwoWidth                                    ((ScreenSize.width - LeftMargin*3)/2)
typedef enum : NSUInteger {
    CancleTag = 3500,//作废
    EndTag,          //结束
    RejectTag,       //拒绝
    PassTag,         //审核
    SureTag,         //确定
    SaveTag,    //收货状态：保存
    ReceiveTag,//收货状态：收货
} BtnTag;

@interface PurchaseDetailViewController ()<UIAlertViewDelegate>
{
    UIScrollView *_scrollView;
    UIView *_purchaseView;
    //UIView *_bottomView;
    //ProductBillViewController *_pvc;
    NSArray *_leftArr;
    UIButton *_firstBtn;
    UIButton *_secondBtn;
    BottomPurchaseView *_aBottomView;
    UIView *_recieveBottomView;
    PurchaseReceiveProductViewController *_pvc;
    
}
@property (nonatomic,strong)UILabel *billNumberLabel;
@property (nonatomic,strong)UILabel *noticeNumberLabel;
@property (nonatomic,strong)UILabel *createOperNameLabel;
@property (nonatomic,strong)UILabel *checkNameLabel;
@property (nonatomic,strong)UILabel *stateLabel;
@property (nonatomic,strong)UILabel *lastModifyNameLabel;
@property (nonatomic, strong) UILabel *purchaserLabel;
@property (nonatomic,strong)UILabel *typeLabel;
@property (nonatomic,strong)UILabel *vendorNameLabel;
@property (nonatomic,strong)UILabel *vendorIsSureLabel;
@property (nonatomic,strong)UILabel *warehouseLabel;
@property (nonatomic,strong)UILabel *otherPriceLabel;
@property (nonatomic,strong)UILabel *totalPriceLabel;
@property (nonatomic,strong)UILabel *noteLabel;
/**
 *  创建时间
 */
@property (strong, nonatomic) UILabel *labelCreateTime;
/**
 *  审核人
 */
@property (strong, nonatomic) UILabel *labelInspector;
/**
 *  审核时间
 */
@property (strong, nonatomic) UILabel *labelInspectTime;
/**
 *  收货人
 */
@property (strong, nonatomic) UILabel *labelReciever;
/**
 *  收货时间
 */
@property (strong, nonatomic) UILabel *labelRecieveTime;
/**
 *  有效期
 */
@property (strong, nonatomic) UILabel *labelExpiredDate;
/**
 *  外部单据号
 */
@property (strong, nonatomic) UILabel *labelOutSideNum;

@property (nonatomic,strong)NSString *rejectCause;//拒接原因
@end

@implementation PurchaseDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self judgeType];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(editReceiveProduct:) name:KNOTIFICATION_EditReceiveProduct object:nil];
    [self bulidLayout];
    [self getDataFromServer];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)judgeType {
    if ([self.bill.state isEqualToString:PURCHASE_STATE_WAITE_RECIEVE] ||
        [self.bill.state isEqualToString:PURCHASE_STATE_RECEIVED] ||
        self.bill.receive_id != nil) {
        self.type = PurchaseTypeAfterVerify;
    }else{
        self.type = PurchaseTypeBeforeVerify;
    }
}
- (void)getDataFromServer{
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (data) {
            NSInteger success = [data[@"success"] integerValue];
            NSString *message  = data[@"message"] ;
            if (success == 1) {
                NSDictionary *dictData = data[@"data"];
                PurchaseBill *bill = [[PurchaseBill alloc]init];
                [bill setValuesForKeysWithDictionary:dictData];
                self.bill = bill;
                [strongSelf validAbort];
                [weakSelf judgeType];
                [_aBottomView refreshCost:dictData[@"accountDetails"]];
                [strongSelf fetchtPurchaseDetail];
            }else{
                [IBTLoadingView showTips:message];
            }
        }else{
            [IBTLoadingView showTips:@"     无记录     "];
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    [[ICRHTTPController sharedController] getPurchaseResultWithPurchaseUuid:self.bill.uuid success:succ failure:fail];
}


#pragma mark - 视图初始化
- (void)bulidLayout{
    [_scrollView removeAllSubViews];
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, ScreenHeight - 64 - BottomHeight)];
    _scrollView.showsHorizontalScrollIndicator  = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.backgroundColor = XXFBgColor;
    [self.view addSubview:_scrollView];
    //    [self createBtn];
    [self showBtnByPermissions];
    [self createBottomView];
    [self createPurchaseView];
    
}

//- (void)createBtn{
//    _firstBtn = [IBTCustomButtom creatButtonWithFrame:CGRectMake(LeftMargin, ScreenHeight  - 64 - BottomHeight +5, (ScreenSize.width - LeftMargin*3)/2, 40) target:self sel:@selector(btnClick:) tag:0 image:nil title:@"" titleColor: [UIColor whiteColor] isCorner:YES corner:5 bgColor:GXF_SAVE_COLOR];
//    [self.view addSubview:_firstBtn];
//
//    _secondBtn = [IBTCustomButtom creatButtonWithFrame:CGRectMake(CGRectGetMaxX(_firstBtn.frame)+ LeftMargin, ScreenHeight  - 64 - BottomHeight +5, (ScreenSize.width - LeftMargin*3)/2, 40) target:self sel:@selector(btnClick:) tag:0 image:nil title:@"" titleColor:[UIColor whiteColor] isCorner:YES corner:5 bgColor:GXF_COMMIT_COLOR];
//    [self.view addSubview:_secondBtn];
//    [self showBtnByPermissions];
//}

- (void)createBtnWithArr:(NSArray *)arrTitles{
    NSMutableArray *arr = [NSMutableArray arrayWithArray:arrTitles];
    
    CGFloat btnWidth = (ScreenSize.width - LeftMargin * (arr.count+1))/arr.count;
    for (NSInteger i = 0; i < arr.count; i++) {
        NSInteger btnTag = 0;
        if ([arr[i] isEqualToString:@"拒绝"]) {
            btnTag = RejectTag;
        }else if ([arr[i] isEqualToString:@"审核通过"]) {
            btnTag = PassTag;
        }else if ([arr[i] isEqualToString:@"确认"]) {
            btnTag = SureTag;
        }else if ([arr[i] isEqualToString:@"结束"]) {
            btnTag = EndTag;
        }else if ([arr[i] isEqualToString:@"作废"]) {
            btnTag = CancleTag;
        }else if ([arr[i] isEqualToString:@"保存"]) {
            btnTag = SaveTag;
        }else if ([arr[i] isEqualToString:@"收货"]) {
            btnTag = ReceiveTag;
        }
        CGRect btnFrame = CGRectMake(LeftMargin + (LeftMargin + btnWidth)*i,  ScreenHeight  - 64 - BottomHeight +5, btnWidth, 40);
        UIButton *perBtn = [IBTCustomButtom creatButtonWithFrame:btnFrame target:self sel:@selector(btnClick:) tag:btnTag image:nil title:arr[i] titleColor:[UIColor whiteColor] isCorner:YES corner:5 bgColor:GXF_COMMIT_COLOR];
        [self.view addSubview:perBtn];
    }
}

//判断是否可以作废
- (BOOL)validAbort {
    for (NSDictionary *pdt in self.bill.products) {
        PurchaseBillProduct *billProbuct = [PurchaseBillProduct new];
        [billProbuct setValuesForKeysWithDictionary:pdt];
        if (billProbuct.shippedQty.doubleValue > 0) {
            UIButton *btn = [self.view viewWithTag:CancleTag];
            btn.hidden = true;
            
            return false;
        }
    }
    return true;
}

//根据权限判断按钮显示
- (void)showBtnByPermissions{
    //逻辑判断按钮显示不显示
    if ([self.bill.state isEqualToString:PURCHASE_STATE_SUBMITTED]) {//状态已提交 未审批
        if([self checkIsPermission:PURCHASE_PERMISSIONS_MANAGEAPPROVE]){
            //显示拒绝和审批
            NSArray *arr = @[@"拒绝",@"审核通过"];
            [self createBtnWithArr:arr];
            
        }
    }else if([self.bill.state isEqualToString:PURCHASE_STATE_SHIPPING]){//状态是发运中即已审批
        NSMutableArray *arr = [NSMutableArray array];
        if([self checkIsPermission:PURCHASE_PERMISSIONS_VENDORAPPROVE] && (!self.bill.vendorConfirmTime || self.bill.vendorConfirmTime.length < 1)){//供应商审批权
            //显示确认按钮
            [arr addObject:@"确认"];
        }
        if ([self checkIsPermission:PURCHASE_PERMISSIONS_FINISH]){//结束权
            //显示结束按钮
            [arr addObject:@"结束"];
        }
//        if([self checkIsPermission:PURCHASE_PERMISSIONS_ABORT]){//作废权
//            //显示作废按钮
//            [arr addObject:@"作废"];
//        }
        [self createBtnWithArr:arr];
        if (arr.count == 0) {
            [self hiddenTwoBtn];
        }
    }else if([self.bill.state isEqualToString:PURCHASE_STATE_FINISHED]){//完成
//        if ([self checkIsPermission:PURCHASE_PERMISSIONS_ABORT]) {//有作废权的
//            //显示作废按钮
//            NSArray *arr = @[@"作废"];
//            [self createBtnWithArr:arr];
//            
//        }else{
            [self hiddenTwoBtn];
//        }
    }else if([self.bill.state isEqualToString:PURCHASE_STATE_PROCESSFAIL]){//系统处理失败的
        if ([self checkIsPermission:PURCHASE_PERMISSIONS_ABORT]) {//有作废权的
            //显示作废按钮
            NSArray *arr = @[@"作废"];
            [self createBtnWithArr:arr];
            
        }else{
            [self hiddenTwoBtn];
        }
    }else if ([self.bill.state isEqualToString:PURCHASE_STATE_WAITE_RECIEVE]){
        if ([IBTCommon checkIsPermission:PURCHASE_PERMISSIONS_REVCEIVE]) {
            [self createBtnWithArr:@[@"保存",@"收货"]];
        }else{
            [self hiddenTwoBtn];
        }
    }else if([self.bill.state isEqualToString:PURCHASE_STATE_ABORTED]){//已作废
        [self hiddenTwoBtn];
    }else if ([self.bill.state isEqualToString:PURCHASE_STATE_RECEIVED]){
        if([self checkIsPermission:PURCHASE_PERMISSIONS_ABORT]){//供应商审批权
            //显示确认按钮
            NSArray *arr = @[@"作废"];
            [self createBtnWithArr:arr];
        }else{
            [self hiddenTwoBtn];
        }
    }else{
        [self hiddenTwoBtn];
    }
}

- (void)hiddenTwoBtn{
    CGRect scrollViewFrame = _scrollView.frame;
    scrollViewFrame.size.height = ScreenHeight - 64;
    _scrollView.frame = scrollViewFrame;
}
//改变按钮的位置
- (void)changeBtnFrame:(UIButton *)btn title:(NSString *)title originX:(CGFloat)originX width:(CGFloat)width{
    CGRect btnFrame = btn.frame;
    btnFrame.origin.x = originX;
    btnFrame.size.width = width;
    btn.frame = btnFrame;
    [btn setTitle:title forState:UIControlStateNormal];
}
- (BOOL)checkIsPermission:(NSString *)permission{
    for (NSString *per in [ICRUserUtil sharedInstance].permissions) {
        if ([per isEqualToString:permission]) {
            return YES;
        }
    }
    return YES;
}

- (void)btnClick:(UIButton *)btn{
    CLog(@"%ld",(long)btn.tag);
    switch (btn.tag) {
        case CancleTag:
        {
            CLog(@"作废");
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请确认作废" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
            alertView.delegate = self;
            alertView.tag = CancleTag;
            [alertView show];
        }
            break;
        case EndTag:
        {
            CLog(@"结束");
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请确认结束" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
            alertView.delegate = self;
            alertView.tag = EndTag;
            [alertView show];
        }
            break;
        case RejectTag:
        {
            CLog(@"拒绝");
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请确认拒绝" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
            alertView.delegate = self;
            alertView.tag = RejectTag;
            [alertView show];
        }
            break;
        case PassTag:
        {
            CLog(@"审核通过");
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请确认通过" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
            alertView.delegate = self;
            alertView.tag = PassTag;
            [alertView show];
        }
            break;
        case SureTag:
        {
            CLog(@"确认");
            [self dealByAction:PURCHASE_ACTION_VENDORCONFIRM];
        }
            break;
        case SaveTag:
        {
            if ([self checkReceive]) {
                [self httpSave];
            }
        }
            break;
        case ReceiveTag:{
            if ([self checkReceive]) {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"收货后不能重复收货，请确认是否要收货？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
                alertView.delegate = self;
                alertView.tag = ReceiveTag;
                [alertView show];
            }
        }
            break;
        default:
            break;
    }
}
- (void)dealByAction:(NSString *)action{
    //保存
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        if (data) {
            NSInteger success = [data[@"success"] integerValue];
            NSString *message = data[@"message"];
            if (success == 1) {
                //是wms且非产品中心仓，审核时同时收货
//                if (self.isWms && self.isCenter == NO && [action isEqualToString:PURCHASE_ACTION_APPROVE]) {
//                    [self getDataFromServer];
//                }else{
                
                    [ICRUserUtil sharedInstance].needFresh = YES;
                    [self PopViewControllerAnimated:YES];
//                }
            }else{
                [IBTLoadingView showTips:message];
            }
        }else{
            [IBTLoadingView showTips:@"操作异常"];
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    [[ICRHTTPController sharedController]dealByActionWithPurchaseUuid:self.bill.uuid action:action remark:[IBTCommon checkString:self.rejectCause] version:self.bill.version success:succ failure:fail];
}

- (BOOL)checkReceive{
    for (NSString *isEdit in _pvc.defaultState) {
        if ([isEdit isEqualToString:@"NO"]) {
            ShowMessage(@"有商品行没有编辑过收货数量，请先编辑再收货");
            return NO;
        }
    }
    
    if (_pvc.productArr.count == 0) {
        ShowMessage(@"商品不能为空");
        return NO;
    }
    
    return YES;
}

- (void)createBottomView{
    _aBottomView = [[BottomPurchaseView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_purchaseView.frame) + TopMargin, ScreenSize.width,300) withHidden:YES];
    _aBottomView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_aBottomView];
    
    if (self.type == PurchaseTypeAfterVerify) {
        _recieveBottomView= [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_purchaseView.frame) + TopMargin, ScreenSize.width,300)];
        _recieveBottomView.backgroundColor = [UIColor redColor];
        [_scrollView addSubview:_recieveBottomView];
        
        _pvc = [[PurchaseReceiveProductViewController alloc]init];
        _pvc.viewFrame = _recieveBottomView.bounds;
        _pvc.isHiddenAdd = YES;
        [_recieveBottomView addSubview:_pvc.view];
    }
    
    
    CGRect frame = _aBottomView.productVC.view.frame;
    _recieveBottomView.frame = frame;
    
    [_aBottomView.productVC.view addSubview:_recieveBottomView];
}

- (void)createPurchaseView{
    _leftArr = @[@"单号:",@"采购通知单:",@"创建人:",@"创建时间:",@"审核人:",@"审核时间:",@"收货人:",@"收货时间:",@"有效期:",@"采购员:",@"状态:",@"类型:",@"供应商:",@"供应商确认:",@"收货仓库:",@"其他费用:",@"总金额:",@"外部单据号:",@"备注:"];
    
    _purchaseView= [[UIView alloc]initWithFrame:CGRectMake(0, TopMargin, ScreenSize.width, LeftHeight*_leftArr.count +LeftMargin)];
    _purchaseView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_purchaseView];
    
    for (NSString *title in _leftArr) {
        NSInteger i = [_leftArr indexOfObject:title];
        UILabel *leftLabel = [[UILabel alloc]initWithFrame:CGRectMake(LeftMargin, 10 + LeftHeight *i, LeftWidth, LeftHeight)];
        leftLabel.font = GXF_SEVENTEENTH_SIZE;
        leftLabel.text = _leftArr[i];
        leftLabel.textColor = GXF_DETAIL_COLOR;
        [_purchaseView addSubview:leftLabel];
        
        UILabel *rightLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(leftLabel.frame), 10 + LeftHeight *i, _purchaseView.frame.size.width - LeftMargin - LeftWidth, LeftHeight)];
        rightLabel.font = GXF_SEVENTEENTH_SIZE;
        rightLabel.textColor = GXF_DETAIL_COLOR;
        if ([title isEqualToString:@"单号:"]) {
            self.billNumberLabel = rightLabel;
        }else if ([title isEqualToString:@"采购通知单:"]){
            self.noticeNumberLabel = rightLabel;
        }else if ([title isEqualToString:@"创建人:"]){
            self.createOperNameLabel = rightLabel;
        }else if ([title isEqualToString:@"最后修改人:"]){
            self.lastModifyNameLabel = rightLabel;
        }else if ([title isEqualToString:@"采购员:"]){
            self.purchaserLabel = rightLabel;
        }else if ([title isEqualToString:@"状态:"]){
            self.stateLabel = rightLabel;
        }else if ([title isEqualToString:@"类型:"]){
            self.typeLabel = rightLabel;
        }else if ([title isEqualToString:@"供应商:"]){
            self.vendorNameLabel = rightLabel;
        }else if ([title isEqualToString:@"供应商确认:"]){
            self.vendorIsSureLabel = rightLabel;
        }else if ([title isEqualToString:@"收货仓库:"]){
            self.warehouseLabel = rightLabel;
        }else if ([title isEqualToString:@"其他费用:"]){
            self.otherPriceLabel = rightLabel;
        }else if ([title isEqualToString:@"总金额:"]){
            self.totalPriceLabel = rightLabel;
        }else if ([title isEqualToString:@"备注:"]){
            rightLabel.numberOfLines = 0;
            self.noteLabel = rightLabel;
        }else if ([title isEqualToString:@"创建时间:"]){
            self.labelCreateTime = rightLabel;
        }else if ([title isEqualToString:@"审核人:"]){
            self.labelInspector = rightLabel;
        }else if ([title isEqualToString:@"审核时间:"]){
            self.labelInspectTime = rightLabel;
        }else if ([title isEqualToString:@"收货人:"]){
            self.labelReciever = rightLabel;
        }else if ([title isEqualToString:@"收货时间:"]){
            self.labelRecieveTime = rightLabel;
        }else if ([title isEqualToString:@"有效期:"]){
            self.labelExpiredDate = rightLabel;
        }else if ([title isEqualToString:@"外部单据号:"]){
            self.labelOutSideNum = rightLabel;
        }
        
        [_purchaseView addSubview:rightLabel];
    }
}

- (void)fetchtPurchaseDetail{
    self.billNumberLabel.text = [IBTCommon checkString:self.bill.billNumber];
    if ([self.bill.state isEqualToString:PURCHASE_STATE_INITIAL]) {
        self.stateLabel.textColor = [UIColor redColor];
        self.stateLabel.text = @"未提交";
    }else if ([self.bill.state isEqualToString:PURCHASE_STATE_SUBMITTED]) {
        self.stateLabel.textColor = [UIColor greenColor];
        self.stateLabel.text = @"未审批";
    }else if ([self.bill.state isEqualToString:PURCHASE_STATE_REJECTED]) {
        self.stateLabel.textColor = [UIColor grayColor];
        self.stateLabel.text = @"已拒绝";
    }else if ([self.bill.state isEqualToString:PURCHASE_STATE_SHIPPING]) {
        self.stateLabel.textColor = [UIColor grayColor];
        self.stateLabel.text = @"发运中";
    }else if ([self.bill.state isEqualToString:PURCHASE_STATE_ABORTED]) {
        self.stateLabel.textColor = [UIColor grayColor];
        self.stateLabel.text = @"已作废";
    }else if ([self.bill.state isEqualToString:PURCHASE_STATE_FINISHED]) {
        self.stateLabel.textColor = [UIColor blackColor];
        self.stateLabel.text = @"已完成";
    }else if ([self.bill.state isEqualToString:PURCHASE_STATE_PROCESS]) {
        self.stateLabel.textColor = [UIColor greenColor];
        self.stateLabel.text = @"提交系统处理";
    }else if ([self.bill.state isEqualToString:PURCHASE_STATE_PROCESSFAIL]) {
        self.stateLabel.textColor = [UIColor blackColor];
        self.stateLabel.text = @"系统处理失败";
    }else if ([self.bill.state isEqualToString:PURCHASE_STATE_WAITE_RECIEVE]) {
        self.stateLabel.textColor = [UIColor blackColor];
        self.stateLabel.text = @"待收货";
    }else if ([self.bill.state isEqualToString:PURCHASE_STATE_RECEIVED]) {
        self.stateLabel.textColor = [UIColor blackColor];
        self.stateLabel.text = @"已收货";
    }
    
    _pvc.isHiddenEdit = ![self.bill.state isEqualToString:PURCHASE_STATE_WAITE_RECIEVE];
    self.noticeNumberLabel.text = (self.bill.noticeNumber.length == 0) ? @"无":(self.bill.noticeNumber);
    self.createOperNameLabel.text = [IBTCommon checkString:self.bill.create_operName];
    self.checkNameLabel.text = [IBTCommon checkString:self.bill.vendor_name];
    self.vendorNameLabel.text = [IBTCommon checkString:self.bill.vendor_name];
    self.totalPriceLabel.text = [IBTCommon checkString:[self.bill.total stringValue]];
    self.noteLabel.text = [NSString stringWithFormat:@"%@",self.bill.remark?self.bill.remark:@"无"];
    self.lastModifyNameLabel.text = [IBTCommon checkString:self.bill.lastModify_operName];
    NSString *type = [self.bill.type isEqualToString:GXF_Critical] ? @"紧急" : @"普通";
    self.typeLabel.text = type;
    self.purchaserLabel.text = [NSString stringWithFormat:@"%@[%@]",self.bill.purchaserName, self.bill.purchaserCode];
    self.vendorIsSureLabel.text = (self.bill.vendorConfirmTime.length > 0 && self.bill.vendorConfirmTime)? @"是":@"否";
    self.warehouseLabel.text = [IBTCommon checkString:self.bill.receiveWrh_name];
    self.otherPriceLabel.text = [self.bill.charge stringValue];
    self.labelCreateTime.text = [IBTCommon checkString:self.bill.create_time];
    self.labelInspector.text = [IBTCommon checkString:self.bill.approv_operName];
    self.labelInspectTime.text = [IBTCommon checkString:self.bill.approv_time];
    self.labelExpiredDate.text = [IBTCommon checkString:self.bill.expiredDate];
    self.labelOutSideNum.text = [IBTCommon checkString:self.bill.outSideBillNumber];
    self.labelReciever.text = [IBTCommon checkString:self.bill.receive_operName];
    self.labelRecieveTime.text = [IBTCommon checkString:self.bill.receive_time];
    NSMutableArray *productArr = [NSMutableArray array];
    
    if (self.type == PurchaseTypeAfterVerify) {
        for (NSDictionary *billDict in self.bill.products) {
            TransferPdtDetail *billProbuct = [TransferPdtDetail new];
            [billProbuct setValuesForKeysWithDictionary:billDict];
            PurchaseBillProduct *p = [PurchaseBillProduct new];
            [p setValuesForKeysWithDictionary:billDict];
            billProbuct.purchasePdt = p;
            
            //待收货的时候才可以显示默认值
            if ([self.bill.state isEqualToString:PURCHASE_STATE_WAITE_RECIEVE]  && self.bill.receive_id == nil && billProbuct.rctQty.floatValue == 0) {
                
                if (self.isCenter) {
                    [billProbuct z_setRctQty:p.qty.floatValue];
                }else if (self.isWms){
                    [billProbuct z_setRctQty:0];
                }else{
                        billProbuct.rctQty = nil;
                        billProbuct.rctBaseQty = nil;
                        billProbuct.rctTotal = nil;
                }
            }else{
                [billProbuct z_setRctQty:billProbuct.rctQty.floatValue];
            }
            [productArr addObject:billProbuct];
        }
        _pvc.productArr = productArr;
        [_pvc.tableView reloadData];
        
//        //如果是wms，非中心仓，则审核完加载详情的时候自动收货
//        if (self.isWms && self.isCenter == NO && [self.bill.state isEqualToString:PURCHASE_STATE_WAITE_RECIEVE]) {
//            [self httpRecieve];
//        }
        
    }else{
        for (NSDictionary *billDict in self.bill.products) {
            PurchaseBillProduct *billProbuct = [PurchaseBillProduct new];
            [billProbuct setValuesForKeysWithDictionary:billDict];
            [productArr addObject:billProbuct];
        }
        _aBottomView.productVC.productArr = productArr;
        [_aBottomView.productVC.tableView reloadData];
    }

    
    [self setNoteHeight];
}

- (void)setNoteHeight
{
    CGFloat height =  [self.noteLabel calculateHeight];
    
    CGRect noteFrame = self.noteLabel.frame;
    noteFrame.size.height = height;
    self.noteLabel.frame = noteFrame;
    
    CGFloat totalHeight = height + LeftHeight*_leftArr.count + LeftMargin;
    CGRect purchaseFrame = _purchaseView.frame;
    purchaseFrame.size.height = totalHeight;
    _purchaseView.frame = purchaseFrame;
    
//    if (self.type == PurchaseTypeAfterVerify) {
//        CGRect bottomFrame = _recieveBottomView.frame;
//        bottomFrame.origin.y = CGRectGetMaxY(_purchaseView.frame) + TopMargin;
//        _recieveBottomView.backgroundColor = [UIColor redColor];
//        _recieveBottomView.frame = bottomFrame;
//        _scrollView.contentSize = CGSizeMake(ScreenSize.width, totalHeight + CGRectGetHeight(_recieveBottomView.frame) + TopMargin*2 + 100);
//    }else{
        CGRect bottomFrame = _aBottomView.frame;
        bottomFrame.origin.y = CGRectGetMaxY(_purchaseView.frame) + TopMargin;
        _aBottomView.frame = bottomFrame;
        _scrollView.contentSize = CGSizeMake(ScreenSize.width, totalHeight + CGRectGetHeight(_aBottomView.frame) + TopMargin*2);
//    }
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == CancleTag) {
        if (buttonIndex == 1) {
            if (self.isWms) {
                ShowMessage(@"wms仓不允许作废！");
                return;
            }
            [self dealByAction:PURCHASE_ACTION_ABORT];//作废
        }
    }else if (alertView.tag == EndTag){
        if (buttonIndex == 1) {
            [self dealByAction:PURCHASE_ACTION_FINISH];//结束
        }
    }else if(alertView.tag == RejectTag){
        if (buttonIndex == 1) {
            [self dealByAction:PURCHASE_ACTION_REJECT];
        }
    }else if(alertView.tag == PassTag){
        if (buttonIndex == 1) {
            [self dealByAction:PURCHASE_ACTION_APPROVE];
        }
    }else if(alertView.tag == ReceiveTag){
        if (buttonIndex == 1) {
//            //提交
//            self.state = RECEIVE_STATE_RECEIVE;
//            [self getDataFromServer:RECEIVE_STATE_RECEIVE msg:@"收货中..."];
            [self httpRecieve];
        }
    }
}


- (void)httpRecieve{
    for (TransferPdtDetail *detail in _pvc.productArr) {
        if (detail.rctQty == nil) {
            ShowMessage(@"请选择商品实收数量后再提交！");
            return;
            
        }
    }
    
    NSString *receiveTime = [[NSDate date] httpParameterString];
    self.bill.receive_time = receiveTime;
    self.bill.receive_id = [ICRUserUtil sharedInstance].userId;
    self.bill.receive_operName = [ICRUserUtil sharedInstance].userName;
    
    NSMutableDictionary *param = [self.bill dictForCommit].mutableCopy;
    NSMutableArray *arrProduct = [NSMutableArray array];
    for (TransferPdtDetail *pdt in _pvc.productArr) {
        PurchaseBillProduct *pPdt = [pdt changeToPurchasePdt];
        NSDictionary *dict = [pPdt dictForCommit];
        [arrProduct addObject:dict];
    }
    
    [param setObject:arrProduct forKey:@"products"];
    
    
    
    [param setObject:self.bill.accountDetails forKey:@"accountDetails"];
    
    IBTLoadingView *hud = [IBTLoadingView showHUDAddedTo:self.view animated:YES];
    __weak UIViewController *weakSelf = self;
    [HTTP recievePurchase:param success:^(id succ) {
        [hud hide:YES];
        if ([succ[@"success"] boolValue]) {
            [ICRUserUtil sharedInstance].needFresh = YES;
            [IBTLoadingView showTips:@"   收货成功！   "];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(id fail) {
        [hud hide:YES];
        [IBTLoadingView showTips:fail];
    }];
    
}


- (void)editReceiveProduct:(NSNotification *)fination{
    NewReceiveProductViewController *nvc = [NewReceiveProductViewController new];
    NSInteger indexTag = [[[fination userInfo] objectForKey:@"indexPath"] integerValue];
    TransferPdtDetail *transferPdtDetail = [[fination userInfo] objectForKey:@"transferPdtDetail"];
    if (transferPdtDetail) {
        nvc.navTitle = @"商品明细";
        nvc.indexTag = indexTag;
        nvc.noticeProduct = transferPdtDetail;
    }
    nvc.editReceiveProduct = ^(TransferPdtDetail *transferPdtDetail,NSInteger indexTag){
        if (transferPdtDetail) {
            [_pvc.productArr replaceObjectAtIndex:indexTag withObject:transferPdtDetail];
            [_pvc.defaultState replaceObjectAtIndex:indexTag withObject:@"YES"];
            [_pvc.tableView reloadData];
        }
    };
    [self PushViewController:nvc animated:YES];
}

- (void)httpSave {
    for (TransferPdtDetail *detail in _pvc.productArr) {
        if (detail.rctQty == nil) {
            ShowMessage(@"请选择商品实收数量后再保存！");
            return;
            
        }
    }
    //保存
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        if (data) {
            NSInteger success = [data[@"success"] integerValue];
            NSString *message = data[@"message"];
            if (success == 1) {
                //成功
                [IBTLoadingView showTips:@"   保存成功！   "];
                [self PopViewControllerAnimated:YES];
            }else{
                [IBTLoadingView showTips:message];
            }
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    
    NSMutableDictionary *param = [self.bill dictForCommit].mutableCopy;
    NSMutableArray *arrProduct = [NSMutableArray array];
    for (TransferPdtDetail *pdt in _pvc.productArr) {
        PurchaseBillProduct *pPdt = [pdt changeToPurchasePdt];
        NSDictionary *dict = [pPdt dictForCommit];
        [arrProduct addObject:dict];
    }
    
    [param setObject:arrProduct forKey:@"products"];
    
    
    
    [param setObject:self.bill.accountDetails forKey:@"accountDetails"];
    
    
    [IBTLoadingView showProgressLabel:@"保存..."];
    [[ICRHTTPController sharedController] savePurchaseWithData:param success:succ failure:fail];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

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