// // SubmitOrderControllerViewController.m // FirstLink // // Created by jack on 15/6/18. // Copyright (c) 2015年 FirstLink. All rights reserved. // #import "SubmitOrderController.h" #import "SubmitAddNewCell.h" #import "SubmitDefaultAddressCell.h" #import "SubmitDefaultIDCardCell.h" #import "ConnectServiceHeaderCell.h" #import "ProductDetailTableCell.h" #import "FKSubmitDiscountView.h" #import "SubmitInputCell.h" #import "PindanCommonCell.h" #import "SubmitCarriageMoneyCell.h" #import "SubmitDiscountCardCell.h" #import "FKGroupStepCell.h" #import "SubmitBottomView.h" #import "SubmitSelectTransportView.h" #import "SubmitDiscountPickView.h" #import "FKAddressDetailController.h" #import "FKAddressListController.h" #import "FKAddIdCardController.h" #import "FKIdCardManageController.h" #import "ChatViewController.h" #import "FLControllerHelper.h" #import "OrderPayController.h" #import "WebViewController.h" #import "FKSubmitOrderRequest.h" #import "FKSubmitOrderReform.h" #import "FKBindIdCardRequest.h" #import "FKBindIdCardReform.h" #define kMessageTextFieldTag 40 #define kInviteTextFiedlTag 41 #define kInviteAlertTag 100 #define kDeleteSpecAlertTag 900 @interface SubmitOrderController () @property (nonatomic, strong) UITableView *tableView; @property (nonatomic, strong) SubmitBottomView *bottomView; @property (nonatomic, strong) FKSubmitDiscountView *discountView; @property (nonatomic, strong) SubmitDiscountPickView *pickerView; @end @implementation SubmitOrderController - (instancetype)initWithPurchaseCache:(FKPurchaseCache *)cache { self = [super init]; if (self) { self.viewModel.cache = cache; } return self; } - (void)viewDidLoad { [super viewDidLoad]; [self initializeLayout]; [self registerTableViewCells]; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; self.navigationItem.title = @"提交订单"; [self.navigationController setNavigationBarHidden:NO animated:YES]; // 如果有省份请求运费(地址选择页面回来) if ([self.viewModel hasAddressProvince]){ [self requestForCarriage]; } else { [self requestForInitalData]; } if (self.viewModel.cache.isPindanNeedIDCard && !self.viewModel.selectedIdCardItem) { [FKBindIdCardRequest requestIdCardListDelegate:self]; } } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; self.navigationItem.title = @" "; [self.view endEditing:YES]; if ([self.pickerView isShowing]) { [self.pickerView dismissAnimated]; } } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } #pragma mark - Request - (void)requestForInitalData { [self.hudView show:YES]; [FKSubmitOrderRequest requestUserAddressWithDelegate:self]; [FKSubmitOrderRequest requestDiscountDataWithPostID:self.viewModel.cache.postID delegate:self]; [FKSubmitOrderRequest requestPostageFreeWithDelegate:self]; } - (void)requestForCarriage { // 请求运费 NSString *province = [self.viewModel province]; if (!province || province.length == 0) return; [self.hudView show:YES]; long allWeight = [self.viewModel.cache getAllWeight]; NSString *allWeightString = [NSString stringWithFormat:@"%ld", allWeight]; [FKSubmitOrderRequest requestCarriagePriceWithProvince:province allWight:allWeightString delegate:self]; } - (void)requestToCreateOrder { [self.hudView show:YES]; [FKSubmitOrderRequest requestTradeNoWithJson:[self.viewModel getJsonStringForTradeNoRequset] subClassJsonStr:[self.viewModel getSubClassJsonStringForTradeNoRequset] delegate:self]; } #pragma mark - response - (void)networkDidReceiveError:(NSError*)error identify:(int)identify header:(MSGHeader*)header{ [self.hudView hide:NO]; if (identify == CARRIAGE_PRICE_REQ) { [self.tableView reloadData]; // 刷新代金券的bug [self refreshBottomView]; } else if (identify == INVITE_CHECK_REQ){ [FLProgressHUDHelper showText:@"邀请码验证失败" inView:self.view]; self.viewModel.isInviteTrue = NO; [self refreshBottomView]; return; } if (header.code.intValue == RESPONSE_MSG_BUSINESS_EXCEPTION) { [FLProgressHUDHelper showText:header.msg inView:self.view]; } else if (header.code.intValue == RESPONSE_MSG_ACCESS_EXCEPTION){ [FLProgressHUDHelper showText:@"请求失败" inView:self.view]; } } - (void)networkDidSuccessResponse:(NSDictionary*)response identify:(int)identify header:(MSGHeader*)header{ [self.hudView hide:NO]; if (identify == ID_CARD_LIST_REQUEST) { NSArray *idCardArray = [FKBindIdCardReform parserIdCardListWithData:response]; self.viewModel.selectedIdCardItem = [SubmitOrderViewModel validIdCardItemFromArray:idCardArray]; [self.tableView reloadData]; } else if (identify == USER_ADDRESS_REQ) { ShipAddress *addressModel = [FKSubmitOrderReform parserAddresModelWithDict:response]; if (addressModel) { self.viewModel.selectedAddress = addressModel; if ([self.viewModel isPostageFree]) { [self.tableView reloadData]; [self refreshBottomView]; return; } NSString *allWeightString = [NSString stringWithFormat:@"%ld", [self.viewModel.cache getAllWeight]]; [FKSubmitOrderRequest requestCarriagePriceWithProvince:[self.viewModel province] allWight:allWeightString delegate:self]; } else { [self.tableView reloadData]; [self refreshBottomView]; } } else if (identify == CARRIAGE_PRICE_REQ) { self.viewModel.carriagePrice = [FKSubmitOrderReform parserCarriagePriceWithDict:response]; [self.tableView reloadData]; [self refreshBottomView]; } else if (identify == DISCOUNT_DATA_REQ) { self.viewModel.discountModel = [FKSubmitOrderReform parserDiscountItemWithDict:response]; self.viewModel.inviteCutFee = [FKSubmitOrderReform parserInviteCutFeeWithDict:response]; [self.viewModel ruledDiscount]; [self.tableView reloadData]; [self refreshBottomView]; } else if (identify == TRADE_NO_REQ) { self.viewModel.paymentModel = [FKSubmitOrderReform parserPaymentItemWithDict:response]; if (!self.viewModel.paymentModel) { [FLProgressHUDHelper showText:header.msg inView:self.view]; return; } [self pushOrderPayController:self.viewModel.paymentModel]; } else if (identify == INVITE_CHECK_REQ) { self.viewModel.isInviteTrue = [FKSubmitOrderReform parserInviteResWithDict:response]; if (!self.viewModel.isInviteTrue) { [FLProgressHUDHelper showText:@"邀请码错误" inView:self.view]; } [self refreshBottomView]; } else if (identify == POSTAGE_FREE_REQ) { self.viewModel.isInternationalPostageFree = [FKSubmitOrderReform parseInternationalPostageFree:response]; self.viewModel.activityText = [FKSubmitOrderReform parseActivityText:response]; if (self.viewModel.isInternationalPostageFree) { [self.viewModel ruledDiscount]; [self.tableView reloadData]; self.discountView.hidden = NO; self.discountView.textLabel.text = self.viewModel.activityText; } else { self.discountView.hidden = YES; } } } #pragma mark - tableView dataSoure && delegate - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [self.viewModel numberOfSectionsInTableView]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.viewModel numberOfRowsInSection:section]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { int cellType = 0; UITableViewCell *cell = [self.viewModel buildCellWithTableView:tableView forIndexPath:indexPath cellType:&cellType]; switch (cellType) { case kSubmitCellTypeProductDetail:{ WeakSelf(weakSelf); ProductDetailTableCell *detailCell = (ProductDetailTableCell *)cell; detailCell.numberChangeAction = ^(NSInteger number, NSIndexPath *indexPath){ return [weakSelf refreshWithNewNumber:number indexPath:indexPath]; }; if (self.viewModel.cache.orderType == kOrderTypeGroup) { [detailCell configCellForGroup]; } else { [detailCell configCellForNormal]; } } break; case kSubmitCellTypeDiscount:{ SubmitDiscountCardCell *discountCell = (SubmitDiscountCardCell *)cell; [discountCell.actionButton addTarget:self action:@selector(disCountButtonClick) forControlEvents:UIControlEventTouchUpInside]; } break; case kSubmitCellTypeInvite:{ SubmitInputCell *inviteCell = (SubmitInputCell *)cell; inviteCell.inputField.delegate = self; inviteCell.inputField.tag = kInviteTextFiedlTag; return inviteCell; } break; case kSubmitCellTypeMessage:{ SubmitInputCell *messageCell = (SubmitInputCell *)cell; messageCell.inputField.delegate = self; messageCell.inputField.tag = kMessageTextFieldTag; return messageCell; } default: break; } return cell; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return [self.viewModel cellHeightForIndexPath:indexPath]; } - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 10; } - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section { if (section == ([self.viewModel numberOfSectionsInTableView] - 1)) { if ([self.viewModel isInternationalPostageFree]) { return 32; } return 10; } return CGFLOAT_MIN; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { kSubmitCellType type = [self.viewModel cellTypeForIndexPath:indexPath]; switch (type) { case kSubmitCellTypeAddAddress: { UIViewController *controller = [[FKAddressDetailController alloc] initWithAddress:nil type:FKAddressDetailControllerTypeAdd]; controller.hidesBottomBarWhenPushed = YES; [self.navigationController pushViewController:controller animated:YES]; break; } case kSubmitCellTypeAddress: { FKAddressListController *controller = [[FKAddressListController alloc] initWithType:FKAddressListControllerTypeChoice]; controller.dataSource = self; controller.delegate = self; controller.hidesBottomBarWhenPushed = YES; [self.navigationController pushViewController:controller animated:YES]; break; } case kSubmitCellTypeAddIDCard: { UIViewController *controller = [FKAddIdCardController new]; controller.hidesBottomBarWhenPushed = YES; [self.navigationController pushViewController:controller animated:YES]; break; } case kSubmitCellTypeIDCard: { FKIdCardManageController *controller = [FKIdCardManageController new]; controller.dataSource = self; controller.delegate = self; controller.hidesBottomBarWhenPushed = YES; [self.navigationController pushViewController:controller animated:YES]; break; } case kSubmitCellTypeGroupProgress: { WebViewController *web = [[WebViewController alloc]init]; web.url = [FKGroupStepCell pushExplainUrl]; web.hidesBottomBarWhenPushed = YES; [self.navigationController pushViewController:web animated:YES]; break; } default: break; } } #pragma mark - FKAddressListController DataSource & Delegate - (NSString *)currentSelectedAddressID { return self.viewModel.selectedAddress.addressID; } - (void)addressListController:(FKAddressListController *)controller didSelectAddress:(ShipAddress *)address { if (address){ self.viewModel.selectedAddress = address; [self.navigationController popToViewController:self animated:YES]; } } - (void)addressListController:(FKAddressListController *)controller didUpdateAddress:(ShipAddress *)address { self.viewModel.selectedAddress = address; } #pragma mark - FKIdCardManageController DataSource & Delegate - (NSString *)currentSelectedIDCard { return self.viewModel.selectedIdCardItem.itemID; } - (void)idCardManageController:(FKIdCardManageController *)controller didSelectItem:(FKIdCardItem *)item { if (item) { self.viewModel.selectedIdCardItem = item; [self.navigationController popToViewController:self animated:YES]; } } - (void)idCardManageController:(FKIdCardManageController *)controller didRemoveItem:(FKIdCardItem *)item { self.viewModel.selectedIdCardItem = nil; } - (void)idCardManageController:(FKIdCardManageController *)controller didUpdateItem:(FKIdCardItem *)item { self.viewModel.selectedIdCardItem = item; } #pragma mark - action - (void)disCountButtonClick { [self.view endEditing:YES]; NSArray *titleArray = [self.viewModel.discountModel getDiscountStringArray]; NSUInteger selectedIndex = [self.viewModel.discountModel usefulIndexWithDiscount:self.viewModel.selectedDiscount] + 1; [self.pickerView refreshTitleArray:titleArray withSelectedIndex:selectedIndex]; [self.pickerView showInView:self.navigationController.view animated:YES]; } - (void)submitConfirmBtnClick { // 判断收件地址是否为空 if (![self.viewModel hasAddress]){ [FLProgressHUDHelper showTipAlert:@"收货地址不能为空"]; return; } // 判断邀请码是否正确,是否需要提示 if ([self.viewModel shouldShowInviteAssert]) { UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"邀请码不正确,是否继续下单" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"继续", nil]; alertView.tag = kInviteAlertTag; [alertView show]; return; } [self requestToCreateOrder]; } #pragma mark - push controller - (void)pushLawList{ } - (void)pushOrderPayController:(SubmitPaymentItem *)paymentItem { [self.viewModel saveDataIntoCache:self.viewModel.cache]; if (self.viewModel.cache.isNeedBindIDCard) { paymentItem.successController = FKOrderPaymentSuccessControllerBindIDCard; } else { if (self.viewModel.cache.orderType == kOrderTypeGroup) { paymentItem.successController = FKOrderPaymentSuccessControllerGroupOrder; } else { paymentItem.successController = FKOrderPaymentSuccessControllerRedpacket; } } OrderPayController *payController = [[OrderPayController alloc] initWithPaymentItem:paymentItem]; NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:self.navigationController.viewControllers]; [viewControllers removeLastObject]; [viewControllers addObject:payController]; [self.navigationController setViewControllers:viewControllers animated:YES]; } #pragma mark - method - (void)discountSelectDoneWithIndex:(NSInteger)index { // 选择代金券 if (index == 0) { // 不使用代金券 self.viewModel.selectedDiscount = nil; }else{ self.viewModel.selectedDiscount = [self.viewModel.discountModel usefulDiscountAtIndex:index - 1]; } [self refreshBottomView]; [self.tableView reloadData]; } - (BOOL)refreshWithNewNumber:(NSInteger)number indexPath:(NSIndexPath *)indexPath { if (number == 0){ if (self.viewModel.cache.specArray.count <= 1) return NO; UIAlertView *alerView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确定要删除该规格吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil]; alerView.tag = (indexPath.row - 1) + kDeleteSpecAlertTag; [alerView show]; return NO; } NSInteger specIndex = indexPath.row - 1; NSInteger allCount = number; for (NSInteger i = 0; i < self.viewModel.cache.specArray.count; i++) { PindanSpecItem *item = self.viewModel.cache.specArray[i]; if (i != specIndex) allCount += item.selectedAmount; } if (allCount > [self.viewModel.cache getRealAmountLimit]) { NSString *warnString = [NSString stringWithFormat:@"每个账号只能购买%ld件哦", (long)[self.viewModel.cache getRealAmountLimit]]; [FLProgressHUDHelper showText:warnString inView:self.view]; return NO; } if (number > [self.viewModel.cache getStockLimitAtIndex:specIndex]) { NSString *warnString = [NSString stringWithFormat:@"该商品库存仅剩%ld件", (long)[self.viewModel.cache getStockLimitAtIndex:specIndex]]; [FLProgressHUDHelper showText:warnString inView:self.view]; return NO; } // 数量改变 [self refreshSpecNumber:number atIndex:specIndex]; return YES; } - (void)refreshSpecNumber:(NSUInteger)number atIndex:(NSInteger)index{ [self.viewModel.cache changeSpecAmount:number AtIndex:index]; [self.viewModel ruledDiscount]; // 对代金券重新判断 long allWeight = [self.viewModel.cache getAllWeight]; NSString *allWeightString = [NSString stringWithFormat:@"%ld", allWeight]; [self.tableView reloadData]; [self refreshBottomView]; // 如果改变数字时,用户并未选择收货地址,下条请求里面已经中断 [FKSubmitOrderRequest requestCarriagePriceWithProvince:[self.viewModel province] allWight:allWeightString delegate:self]; } - (void)refreshBottomView { CGFloat totalFee = [self.viewModel.cache getTotalPrice] + [self.viewModel getCountryInCarriage]; // 减去代金券 CGFloat discountFee = [self.viewModel getCurrentDiscountFee]; // 减去邀请码抵用 CGFloat inviteFee = [self.viewModel getCurrentInviteFee]; /** * 减去国际运费 */ CGFloat internationalPostageFee = [self.viewModel freeInternationalPostageFee]; CGFloat allFee = totalFee - discountFee - inviteFee - internationalPostageFee; if (allFee < 0) allFee = 0; long allCount = [self.viewModel.cache getAllAmount]; [self.bottomView refreshPriceWithAmount:allCount totalFee:allFee]; } - (void)initializeLayout { [self.view addSubview:self.tableView]; [self.view addSubview:self.bottomView]; [self.view addSubview:self.discountView]; [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) { make.left.right.bottom.equalTo(self.view); make.height.equalTo(@50); }]; [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.left.right.top.equalTo(self.view); make.bottom.equalTo(self.bottomView.mas_top); }]; [self.discountView mas_makeConstraints:^(MASConstraintMaker *make) { make.left.right.equalTo(self.bottomView); make.bottom.equalTo(self.bottomView.mas_top); make.height.mas_equalTo(22); }]; } - (void)registerTableViewCells { [self.tableView registerClass:[PindanBaseCell class] forCellReuseIdentifier:NSStringFromClass([PindanBaseCell class])]; [self.tableView registerClass:[PindanCommonCell class] forCellReuseIdentifier:NSStringFromClass([PindanCommonCell class])]; [self.tableView registerClass:[ProductDetailTableCell class] forCellReuseIdentifier:NSStringFromClass([ProductDetailTableCell class])]; [self.tableView registerClass:[SubmitAddNewCell class] forCellReuseIdentifier:NSStringFromClass([SubmitAddNewCell class])]; [self.tableView registerClass:[SubmitDefaultAddressCell class] forCellReuseIdentifier:NSStringFromClass([SubmitDefaultAddressCell class])]; [self.tableView registerClass:[SubmitDefaultIDCardCell class] forCellReuseIdentifier:NSStringFromClass([SubmitDefaultIDCardCell class])]; [self.tableView registerClass:[SubmitCarriageMoneyCell class] forCellReuseIdentifier:NSStringFromClass([SubmitCarriageMoneyCell class])]; [self.tableView registerClass:[SubmitInputCell class] forCellReuseIdentifier:NSStringFromClass([SubmitInputCell class])]; [self.tableView registerClass:[SubmitDiscountCardCell class] forCellReuseIdentifier:NSStringFromClass([SubmitDiscountCardCell class])]; [self.tableView registerClass:[FKGroupStepCell class] forCellReuseIdentifier:NSStringFromClass([FKGroupStepCell class])]; } #pragma mark - UIAlertView delegate -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if (alertView.tag >= kDeleteSpecAlertTag) { if (buttonIndex == 1) { NSInteger row = alertView.tag - kDeleteSpecAlertTag; // 数量改变 [self refreshSpecNumber:0 atIndex:row]; [self.tableView reloadData]; } return; } else if (buttonIndex == 1 && alertView.tag == kInviteAlertTag) { // 继续付款 [self requestToCreateOrder]; } } #pragma mark - textFieldDelegate - (void)textFieldDidEndEditing:(UITextField *)textField { if (textField.tag == kMessageTextFieldTag) { self.viewModel.messageText = textField.text; } else if (textField.tag == kInviteTextFiedlTag){ if (textField.text.length == 0) { self.viewModel.inviteText = nil; return; } self.viewModel.inviteText = textField.text; [FKSubmitOrderRequest requestToCheckInvite:textField.text withDelegate:self]; } } - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } #pragma mark - geter && setter - (UITableView *)tableView { if (_tableView == nil) { _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped]; _tableView.dataSource = self; _tableView.delegate = self; _tableView.separatorStyle = UITableViewCellSeparatorStyleNone; _tableView.sectionFooterHeight = 0; } return _tableView; } - (SubmitBottomView *)bottomView { if (_bottomView == nil) { _bottomView = [[SubmitBottomView alloc]init]; [_bottomView.confirmBtn addTarget:self action:@selector(submitConfirmBtnClick) forControlEvents:UIControlEventTouchUpInside]; } return _bottomView; } - (FKSubmitDiscountView *)discountView { if (_discountView == nil) { _discountView = [[FKSubmitDiscountView alloc]init]; _discountView.hidden = YES; } return _discountView; } - (SubmitDiscountPickView *)pickerView { if (_pickerView == nil) { _pickerView = [[SubmitDiscountPickView alloc] initWithFrame:CGRectZero]; [_pickerView refreshTitleArray:[self.viewModel.discountModel getDiscountStringArray] withSelectedIndex:0]; WeakSelf(weakSelf); _pickerView.selectDone = ^(NSInteger selectedIndex){ [weakSelf discountSelectDoneWithIndex:selectedIndex]; }; } return _pickerView; } - (SubmitOrderViewModel *)viewModel { if (_viewModel == nil) { _viewModel = [[SubmitOrderViewModel alloc]init]; } return _viewModel; } @end