//
//  OrderDetailsViewController.m
//  Palmwms
//
//  Created by 曹云霄 on 16/9/12.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "OrderDetailsViewController.h"
#import "OrderDetailsTableViewCell.h"

#define FINISH @"已完成"

@interface OrderDetailsViewController ()<UITableViewDelegate,UITableViewDataSource>


@property (weak, nonatomic) IBOutlet UITableView *orderDetailsTableview;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@end

@implementation OrderDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.orderDetailsTableview.tableFooterView = [UIView new];
    [self uiConfigAction];
}

#pragma mark - UI
- (void)uiConfigAction
{
    //已完成
    NSInteger index = 0;
    for (BusbillDtl *model in self.orderDetails) {
        if ([model.state isEqualToString:FINISH]) {
            index ++;
        }
    }
    NSString *indexString = [NSString stringWithFormat:@"%ld",index?index:1];
    NSString *totalCount = [NSString stringWithFormat:@"%ld",self.orderDetails.count];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"本次应送%ld,已完成%ld",self.orderDetails.count,index]];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(attributedString.length-([indexString length] + 4 + [totalCount length]), [totalCount length])];
     [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(attributedString.length-[indexString length], [indexString length])];
    self.titleLabel.attributedText = attributedString;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderDetailsTableViewCell" forIndexPath:indexPath];
    BusbillDtl *model = self.orderDetails[indexPath.row];
    if (![model.customerLng length]&& ![model.customerLat length]) {
       cell.storeTitleLabel.text = [NSString stringWithFormat:@"%@ (暂无GPS数据)",model.customerName];
    }else
    {
        cell.storeTitleLabel.text = model.customerName;
    }
    if ([model.state isEqualToString:FINISH]) {
        [cell.arriveButton setTitle:@"送货完成" forState:UIControlStateNormal];
        [cell.arriveButton setTitleColor:RGBA(129, 196, 56, 1) forState:UIControlStateNormal];
        [cell.arriveButton setBackgroundColor:[UIColor whiteColor]];
        cell.arriveButton.enabled = NO;
    }else
    {
        [cell.arriveButton setTitle:@"送货到达" forState:UIControlStateNormal];
        [cell.arriveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [cell.arriveButton setBackgroundColor:[UIColor redColor]];
        cell.arriveButton.enabled = YES;
    }
    cell.storeAddressLabel.text = model.customerAddress;
    cell.arriveButton.tag = indexPath.row;
    [cell.arriveButton addTarget:self action:@selector(arriveButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.orderDetails.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

#pragma mark - 更新送货单某一详情状态
- (void)arriveButtonClickAction:(UIButton *)sender
{
    WS(weakSelf);
    BusbillDtl *model = self.orderDetails[sender.tag];
    [self CreateMBProgressHUDLoding:@"加载中"];
    NSString *urlString = [NSString stringWithFormat:SERVERREQUESTURL(ORDERDETAILSSTATE),model.fid,FINISH];
    NSString *UTF8String = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:UTF8String WithRequestType:NetworkRequestWithPOST WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        [weakSelf RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            model.state = FINISH;
            [sender setTitle:@"送货完成" forState:UIControlStateNormal];
            [sender setTitleColor:RGBA(129, 196, 56, 1) forState:UIControlStateNormal];
            [sender setBackgroundColor:[UIColor whiteColor]];
            sender.enabled = NO;
            [weakSelf refreshDeliveryOrderState];
        }else{
            [weakSelf SHOWPrompttext:returnValue[@"message"]];
        }
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf SHOWPrompttext:NETWORK];
    } WithFailureBlock:^(NSError *error) {
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf SHOWPrompttext:error.localizedDescription];
    }];
}

#pragma mark - 更新送货单列表
- (void)refreshDeliveryOrderState
{
    NSString *orderState = FINISH;
    for (BusbillDtl *model in self.orderDetails) {
        if (![model.state isEqualToString:FINISH]) {
            orderState = @"送货中";break;
        }
    }
    //更新状态
    [self uiConfigAction];
    WS(weakSelf);
    NSString *urlString = [NSString stringWithFormat:SERVERREQUESTURL(REFRESHORDERSTATE),self.billNumber,orderState];
    NSString *UTF8String = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:UTF8String WithRequestType:NetworkRequestWithPOST WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            if (weakSelf.refreshListDatasBlock) {
                weakSelf.refreshListDatasBlock();
            }
            if (weakSelf.refreshPinStateBlock) {
                weakSelf.refreshPinStateBlock(self.orderDetails);
            }
        }else
        {
            [weakSelf SHOWPrompttext:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [weakSelf SHOWPrompttext:NETWORK];
    } WithFailureBlock:^(NSError *error) {
        [weakSelf SHOWPrompttext:error.localizedDescription];
    }];
}

#pragma mark - 关闭
- (IBAction)turnoffButtonClickAction:(UIButton *)sender {
    if (self.ReturnoffButtonClickBlock) {
        self.ReturnoffButtonClickBlock();
    }
}

@end
