//
//  GTOLicenceDetailViewController.m
//  total
//
//  Created by freecui on 15/10/30.
//  Copyright © 2015年 free. All rights reserved.
//

#import "GTOAlertInfoLicenceViewController.h"
#import "GTOAnswer.h"
#import "GTODisplayResult.h"
#import "GTOLicence.h"
#import "GTOLicenceListSimpleCellContentView.h"
#import "GTOLicenceNewViewController.h"
#import "GTOLiceneResultViewController.h"
#import "GTOPioneeringSurveyItem.h"
#import "GTORepair.h"
#import "GTORepairDetailTopCellView.h"
#import "GTORepairDetailViewController.h"
#import "GTORepairListCellContentView.h"
#import "GXFBottomView.h"
#import "GXFButtonAndLineView.h"

#import "GTOQuestionManager.h"
#import "GTORepairAddPhotoView.h"
#import "IBTImagePicker.h"
#import "ICRAttachmentView.h"
#import "ICRPostAttachment.h"
#import "JTImagePreviewer.h"
static NSString *cellIDTop = @"topCell";
static NSString *cellIDItem = @"itmeCell";
static NSString *headID = @"headID";

typedef NS_ENUM(NSUInteger, bottomViewTag) {

  kBottomViewOneApplicationTag = 0,
  kBottomViewOneFinishTag,
  kBottomViewOneBackTag

};
@interface GTORepairDetailViewController () <
    UITableViewDataSource, UITableViewDelegate, GXFBottomViewDelegate,
    GTOAlertInfoLicenceViewControllerDelegate, IBTImagePickerDelegate,
    ICRAttachmentViewDelegate, UIAlertViewDelegate>
@property(nonatomic, strong) UITableView *c_tableView;
@property(nonatomic, strong) NSMutableArray *d_muArrLicences;
@property(nonatomic, strong) GTORepair *d_repair;
@property(nonatomic, strong)
    GTOLicence *d_currentLicence; //当前点击的列表的cell
@property(nonatomic, strong) GTOAlertInfoLicenceViewController *alertInfoVC;
@property(nonatomic, strong) GTORepairAddPhotoView *c_addPhotoV;
@property(strong, nonatomic) IBTImagePicker *m_imagePicker;

@property(nonatomic, strong) NSMutableArray *d_muArrPhotos;
@property(nonatomic, strong) ICRPostAttachment *d_postAttachment;
@property(nonatomic, strong) GXFBottomView *c_bottomView;
@property(nonatomic, copy) NSString *d_repairUuid;
@property(assign, nonatomic) BOOL d_isDownLoadImg; //是否是从网络上下载的图片
@property(assign, nonatomic) NSUInteger d_removeIndex;
@property(assign, nonatomic) BOOL d_applyFinish;
@property (strong, nonatomic) UIImageView *imgNoData;
@end

@implementation GTORepairDetailViewController

#pragma mark - Getter
- (IBTImagePicker *)m_imagePicker {
  if (!_m_imagePicker) {
    self.m_imagePicker = [[IBTImagePicker alloc] init];
  }

  return _m_imagePicker;
}

- (instancetype)initWithRepairUuid:(NSString *)repairUuid {

  self = [super init];
  if (!self) {
    return nil;
  }
  self.d_repairUuid = repairUuid;
  [self p_repair];

  return self;
}
- (void)viewDidLoad {
  [super viewDidLoad];
  self.view.backgroundColor = [UIColor whiteColor];
  // Do any additional setup after loading the view.
  self.title = @"报修单详情";
}
- (void)viewWillAppear:(BOOL)animated {
  [self p_licences];
}
- (void)p_repair {
  ICRHTTPController *httpC = [ICRHTTPController sharedController];
  [httpC getRepairItemsWithRepairUuid:_d_repairUuid
      success:^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        NSInteger success = [data[@"success"] integerValue];
        NSString *message = data[@"message"];
        if (success == 1) {
          NSDictionary *dictRepair = data[@"data"];
          self.d_repair = [GTORepair DBObject];
          [_d_repair praseFromJsonDict:dictRepair];
          [self initSubViews];
          [_c_tableView reloadData];
        } else {
          [IBTLoadingView showTips:message];
        }
      }
      failure:^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
      }];
}
- (void)p_licences {
  __weak typeof(self) weakSelf = self;
  NSDictionary *dict = @{
    @"userUuid" : @"",
    @"state" : [NSNull null], //@"", //
    @"repairUuid" : _d_repairUuid,
    @"repairNumberLike" : @"",
    @"billNumberLike" : [NSNull null], //@"", //
    @"riskGrade" : @"",

    @"queryOrders" :
        @[ @{@"field" : @"billNumber", @"direction" : @"desc"} ], // orderArr,

    @"pageNumber" : @(0),
    @"pageSize" : @(200)
  };
  IBTLoadingView *hud = [IBTLoadingView showHUDAddedTo:self.view animated:YES];
  ICRHTTPController *httpC = [ICRHTTPController sharedController];
  [httpC getLicenceListWithData:dict success:^(id data) {
    [hud hide:YES];
    __strong __typeof(weakSelf) strongSelf = weakSelf;
    [strongSelf fetchtPuchaseList:data];
  } failure:^(id data) {
    [hud hide:YES];
    [IBTLoadingView showTips:data];
  }];
}
- (void)fetchtPuchaseList:(id)data {
  if (data) {
    NSInteger success = [data[@"success"] integerValue];
    NSString *message = data[@"message"];
    if (success == 1) {
      NSArray *recodesArr = data[@"data"][@"records"];
      if (!_d_muArrLicences) {
        self.d_muArrLicences = [NSMutableArray array];
      } else {
        [self.d_muArrLicences removeAllObjects];
      }

      for (NSDictionary *dictRepair in recodesArr) {
        GTOLicence *licence = [GTOLicence DBObject];
        [licence praseFromJsonDict:dictRepair];

        [self.d_muArrLicences addObject:licence];
      }
      if (self.d_muArrLicences.count == 0) {
        self.imgNoData.hidden = NO;
      }else{
        self.imgNoData.hidden = YES;
      }
      [self.c_tableView reloadData];
    } else {
      [IBTLoadingView showTips:message];
    }
  } else {
    [IBTLoadingView showTips:@"      无记录      "];
  }
}

- (void)initSubViews {
  self.view.backgroundColor = XXFBgColor;
  self.c_tableView = [[UITableView alloc]
      initWithFrame:CGRectMake(0, 0, self.view.width,
                               self.view.height - BottomViewHeight - 60 - 10)
              style:UITableViewStyleGrouped];
  [self.c_tableView registerClass:[UITableViewCell class]
           forCellReuseIdentifier:cellIDTop];
  [self.c_tableView registerClass:[UITableViewCell class]
           forCellReuseIdentifier:cellIDItem];
  [self.c_tableView registerClass:[UITableViewHeaderFooterView class]
      forHeaderFooterViewReuseIdentifier:headID];
  self.c_tableView.dataSource = self;
  self.c_tableView.delegate = self;
  [self.view addSubview:_c_tableView];
  [_c_tableView reloadData];

  self.c_addPhotoV = [[GTORepairAddPhotoView alloc]
      initWithFrame:(CGRect){.origin.x = 0,
                             .origin.y = _c_tableView.bottom + 5,
                             .size.width = self.view.width,
                             .size.height = 60}];
  _c_addPhotoV.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
  _c_addPhotoV.backgroundColor = XXFBgColor;
  _c_addPhotoV.m_photoAttachView.delegate = self;
  if ([_d_repair.state isEqualToString:GTO_REPAIR_STATE_FINISHED]) {
    [self p_getAttachmentUrls];
    [_c_addPhotoV.m_photoAttachView.m_addButton removeFromSuperview];
  } else {
    [_c_addPhotoV.m_photoAttachView.m_addButton
               addTarget:self
                  action:@selector(onShowImagePicker:)
        forControlEvents:UIControlEventTouchUpInside];
  }
  [self.view addSubview:_c_addPhotoV];

  CGRect rect = CGRectMake(0, _c_addPhotoV.bottom + 10, self.view.width,
                           BottomViewHeight);
  GXFBottomView *bottomV =
      [[GXFBottomView alloc] initOneButtonWithFrame:rect
                                        buttonColor:GTO_RED_COLOR
                                        buttonTitle:@""];
  BOOL finishPermission = [GTOCommonTools hasPermissionWithPermissionId:500304];
  if ([_d_repair.state isEqualToString:GTO_REPAIR_STATE_FINISHED] ||
      !finishPermission) { //加载下载的图片
    bottomV.tag = kBottomViewOneBackTag;
    [bottomV.f_oneBtn setTitle:@"返回" forState:UIControlStateNormal];

    //显示后台上面的附件
    if (_d_repair.attachmentUrls.count > 0) {
      for (NSDictionary *dict in _d_repair.attachmentUrls) {
        ICRPostAttachment *postAttachment = [ICRPostAttachment DBObject];
        [postAttachment praseFromJsonDict:dict];
        self.d_isDownLoadImg = YES;
        [self addAttachment:[NSURL
                                URLWithString:[NSString
                                                  stringWithFormat:
                                                      @"%@%@",
                                                      HTTP_LOCAL_BASE_URL,
                                                      postAttachment.fileUrl]]];
      }
    }

  } else if ([_d_repair.state isEqualToString:GTO_REPAIR_STATE_SUBMITTED] ||
             [_d_repair.state isEqualToString:GTO_REPAIR_STATE_PROCESSING]) {
    self.c_addPhotoV.hidden = YES;
    bottomV.tag = kBottomViewOneApplicationTag;
    [bottomV.f_oneBtn setTitle:@"申请结束报修" forState:UIControlStateNormal];
  } else if ([_d_repair.state isEqualToString:GTO_REPAIR_STATE_APPLICATION]) {
    bottomV.tag = kBottomViewOneFinishTag;
    [bottomV.f_oneBtn setTitle:@"结束报修" forState:UIControlStateNormal];

    [self addLocalPhotos];
  } else {
  }
  bottomV.delegate = self;
  self.c_bottomView = bottomV;
  [self.view addSubview:_c_bottomView];

  if ([_d_repair.state isEqualToString:GTO_REPAIR_STATE_SUBMITTED] ||
      [_d_repair.state isEqualToString:GTO_REPAIR_STATE_PROCESSING]) {
    self.c_tableView.height = self.view.height - BottomViewHeight - 10;
  }
}
//加载本地图片
- (void)addLocalPhotos {
  // _d_muArrPhotos  _d_postAttachment
  //加载本地图片
  ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
    NSString *sql =
        [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? ORDER BY %@",
                                   [ICRPostAttachment TableName], @"repairUuid",
                                   @"addTime"];
    return [db executeQuery:sql, _d_repair.uuid];
  };

  __weak typeof(self) weakSelf = self;
  ICRDatabaseFetchResultsBlock fetchResultBlk = ^(NSArray *fetchedObjects) {
    __strong __typeof(weakSelf) strongSelf = weakSelf;
    if (fetchedObjects.count > 0) {
      if (!_d_postAttachment) {
        self.d_postAttachment = fetchedObjects[0];
      }
      if (!_d_muArrPhotos.count) {
        self.d_muArrPhotos = [NSMutableArray arrayWithArray:fetchedObjects];
        for (ICRPostAttachment *postAttachment in fetchedObjects) {
          if (postAttachment.content) {
            NSData *imageData =
                [NSData dataFromBase64String:postAttachment.content];
            UIImage *image = [UIImage imageWithData:imageData];
            [self addAttachment:image];
          }
        }
      }
    }
  };

  ICRDataBaseController *dbCtl = [ICRDataBaseController sharedController];
  [dbCtl runFetchForClass:[ICRPostAttachment class]
               fetchBlock:fetchBlk
        fetchResultsBlock:fetchResultBlk];
}
//从网络上获取图片
- (UIImage *)p_getImageFromURL:(NSString *)fileURL {
  UIImage *result;
  NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
  result = [UIImage imageWithData:data];
  return result;
}

- (void)p_getAttachmentUrls {
  void (^succ)(id) = ^(id data) {
    CLog(@"%@", data);
    [IBTLoadingView hideHUDWithText:nil];
    NSInteger success = [data[@"success"] integerValue];
    NSString *message = data[@"message"];
    if (success == 1) {
    }
  };
  void (^fail)(id) = ^(id data) {
    CLog(@"%@", data);
    [IBTLoadingView hideHUDWithText:nil];

  };
  ICRHTTPController *httpC = [ICRHTTPController sharedController];
  [httpC getAttachmentUrlsWithEntityType:GTO_ENTITYTYPE_REPAIR
                           andEntityUuid:_d_repair.attachmentId
                                 success:succ
                                 failure:fail];
}
#pragma ICRAttachmentViewDelegate
- (void)attachmentView:(ICRAttachmentView *)attachmentView
    removeContentAttachmentViewAtIndex:(NSUInteger)uiIndex {

  UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"是否删除图片"
                                                   message:@""
                                                  delegate:self
                                         cancelButtonTitle:@"取消"
                                         otherButtonTitles:@"确定", nil];
  self.d_removeIndex = uiIndex;
}

- (void)removePhotoAtIndex:(NSUInteger)uiIndex {
  ICRPostAttachment *postAttachment = _d_muArrPhotos[uiIndex];
  ICRDataBaseController *dataBaseC = [ICRDataBaseController sharedController];
  [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
    NSString *sql =
        [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = ?",
                                   [ICRPostAttachment TableName], @"fileName"];
    [db executeUpdate:sql, postAttachment.fileName];
  }];

  [self.d_muArrPhotos removeObjectAtIndex:uiIndex];
}
- (void)alertView:(UIAlertView *)alertView
    clickedButtonAtIndex:(NSInteger)buttonIndex {
  if (buttonIndex == 1) {
    CLog(@"delet");
    [self removePhotoAtIndex:self.d_removeIndex];
  }
}
#pragma UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
  return section == 0 ? 1 : _d_muArrLicences.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 2;
}
- (CGFloat)tableView:(UITableView *)tableView
    heightForHeaderInSection:(NSInteger)section {
  return section == 0 ? 0.1 : 44;
}
- (CGFloat)tableView:(UITableView *)tableView
    heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (indexPath.section == 0) {
    return 210;
  } else {
    GTOLicence *licence = _d_muArrLicences[indexPath.row];
    return [licence.state isEqualToString:@"rejected"] ? 110 + 20 : 110;
  }
}
- (UIView *)tableView:(UITableView *)tableView
    viewForHeaderInSection:(NSInteger)section {
  if (section == 0) {
    return nil;
  } else {
    UITableViewHeaderFooterView *headerView =
        [tableView dequeueReusableHeaderFooterViewWithIdentifier:headID];
    [self configureHeaderView:headerView forHeaderInSection:section];
    return headerView;
  }
}
- (void)configureHeaderView:(UITableViewHeaderFooterView *)headerView
         forHeaderInSection:(NSInteger)section {
  UIView *contentView = headerView.contentView;
  CLog(@"%lf", contentView.height); //为什么为0？？
  contentView.backgroundColor = XXFBgColor;
  GXFButtonAndLineView *headLineV =
      [contentView viewWithClass:[GXFButtonAndLineView class]];
  if (!headLineV) {
    headLineV = [[GXFButtonAndLineView alloc]
        initViewLineAndButtonWithFrame:CGRectMake(0, 0, self.view.width * 0.5,
                                                  44)
                             isSeleted:YES
                           buttonTitle:@"许可证列表"
                           selectColor:GTO_RED_COLOR];
    headLineV.f_btn.userInteractionEnabled = NO;

    BOOL createPermission =
        [GTOCommonTools hasPermissionWithPermissionId:500303];
    BOOL condition =
        ([_d_repair.state isEqualToString:GTO_REPAIR_STATE_INITIAL] ||
         [_d_repair.state isEqualToString:GTO_REPAIR_STATE_SUBMITTED] ||
         [_d_repair.state isEqualToString:GTO_REPAIR_STATE_PROCESSING]) &&
        createPermission;
    if (condition) {
      UIButton *addBtn = [[UIButton alloc]
          initWithFrame:CGRectMake(headLineV.right + 5, headLineV.y,
                                   headLineV.width, headLineV.height)];
      [addBtn addTarget:self
                    action:@selector(addLicenceClicked)
          forControlEvents:UIControlEventTouchUpInside];
      [addBtn setImage:[UIImage imageNamed:@"add_icon"]
              forState:UIControlStateNormal];
      [addBtn setTitle:@"新增" forState:UIControlStateNormal];
      [addBtn setTitleColor:GTO_GRAY_TINT_COLOR forState:UIControlStateNormal];
      [contentView addSubview:addBtn];
    }
    [contentView addSubview:headLineV];
  }
}
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:YES];
  UITableViewCell *cell = nil;
  if (indexPath.section == 0) {
    cell = [tableView dequeueReusableCellWithIdentifier:cellIDTop
                                           forIndexPath:indexPath];
  } else {
    cell = [tableView dequeueReusableCellWithIdentifier:cellIDItem
                                           forIndexPath:indexPath];
  }
  [self configureCell:cell forRowAtIndexPath:indexPath];
  return cell;
}
- (void)configureCell:(UITableViewCell *)cell
    forRowAtIndexPath:(NSIndexPath *)indexPath {
  UIView *contentView = cell.contentView;
  if (indexPath.section == 0) {
    GTORepairDetailTopCellView *topView =
        [contentView viewWithClass:[GTORepairDetailTopCellView class]];
    if (!topView) {
      topView = [[GTORepairDetailTopCellView alloc] init];
      [topView autoresizingWithStrechFullSize];
      [contentView addSubview:topView];
    }
    [topView updateWithRepair:_d_repair];

  } else {
    GTOLicenceListSimpleCellContentView *view =
        [contentView viewWithClass:[GTOLicenceListSimpleCellContentView class]];

    if (!view) {
      view = [[GTOLicenceListSimpleCellContentView alloc]
          initWithFrame:contentView.bounds];
      // view.m_bHiddenNumLabel = m_bIsInHome;
      [view autoresizingWithStrechFullSize];
      [contentView addSubview:view];
    }
    GTOLicence *licence = _d_muArrLicences[indexPath.row];
    [view updateWithLicence:licence];
  }
}
- (void)tableView:(UITableView *)tableView
    didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:NO];
  GTOLicence *licence = _d_muArrLicences[indexPath.row];
  self.d_currentLicence = licence;
  [self p_httpGetLicenceItems];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
           editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
  /*
   UITableViewCellEditingStyleNone,
   UITableViewCellEditingStyleDelete,
   UITableViewCellEditingStyleInsert
   */
  GTOLicence *licence = _d_muArrLicences[indexPath.row];
  if ([licence.state isEqualToString:GTO_LICENCE_STATE_INITIAL]) {
    return UITableViewCellEditingStyleDelete;
  }

  // return UITableViewCellEditingStyleDelete;
  return UITableViewCellEditingStyleNone;
}
- (void)tableView:(UITableView *)tableView
    commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
     forRowAtIndexPath:(NSIndexPath *)indexPath {
  if (editingStyle == UITableViewCellEditingStyleDelete) {

    GTOLicence *licence = _d_muArrLicences[indexPath.row];
    [self p_deleteLicenceWithLicence:licence];

    [_d_muArrLicences removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:@[ indexPath ]
                     withRowAnimation:UITableViewRowAnimationFade];
  }
}
- (void)p_deleteLicenceWithLicence:(GTOLicence *)licence {

  //后台删除
  void (^succ)(id) = ^(id data) {
    [IBTLoadingView hideHUDWithText:nil];
    if ([data[@"success"] integerValue] == 1) {
      //本地删除 许可证
      ICRDataBaseController *dataBaseC =
          [ICRDataBaseController sharedController];
      [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql =
            [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?",
                                       [GTOLicence TableName], @"uuid"];
        [db executeUpdate:strSql, licence.uuid];
      }];

      [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql =
            [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?",
                                       [GTOQuestion TableName], @"licenceUuid"];
        [db executeUpdate:strSql, licence.uuid];
      }];
      [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql =
            [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?",
                                       [GTOAnswer TableName], @"licenceUuid"];
        [db executeUpdate:strSql, licence.uuid];
      }];

    } else {
      [IBTLoadingView showTextOnly:data[@"message"] inView:self.view];
    }
  };
  void (^fail)(id) = ^(id data) {
    [IBTLoadingView hideHUDWithText:nil];
    [IBTLoadingView showTips:data];
  };
  [IBTLoadingView showProgressLabel:@"正在加载..."];
  ICRHTTPController *httpC = [ICRHTTPController sharedController];
  [httpC doLicenceRemoveWithLicenceUuid:licence.uuid
                                version:licence.version
                                success:succ
                                failure:fail];
}

- (void)p_httpGetLicenceItems {
  __weak typeof(self) weakSelf = self;
  void (^succ)(id) = ^(id data) {
    [IBTLoadingView hideHUDWithText:nil];
    __strong __typeof(weakSelf) strongSelf = weakSelf;
    [strongSelf p_saveLicenceItemsWithData:data];
  };
  void (^fail)(id) = ^(id data) {
    [IBTLoadingView hideHUDWithText:nil];
    [IBTLoadingView showTips:data];
  };
  [IBTLoadingView showProgressLabel:@"正在加载..."];
  ICRHTTPController *httpC = [ICRHTTPController sharedController];
  [httpC getLicenceItemsWithLicenceUuid:_d_currentLicence.uuid
                                success:succ
                                failure:fail];
}
- (void)p_saveLicenceItemsWithData:(id)data {

  NSInteger intSucc = [data[@"success"] integerValue];
  if (intSucc == 1) {
  }
  NSArray *arrItems = [data[@"data"] objectForKey:@"items"];
  NSMutableArray *muArrQuestions = [NSMutableArray array];
  NSMutableArray *muArrAnswers = [NSMutableArray array];
  NSMutableArray *muArrCategory = [NSMutableArray array];
  for (NSDictionary *dictItem in arrItems) {

    GTOPioneeringSurveyItem *item = [GTOPioneeringSurveyItem DBObject];
    [item praseFromJsonDict:dictItem];
    GTOQuestion *question = [GTOQuestion DBObject];
    [question praseFromJsonDict:dictItem];
    question.licenceUuid = _d_currentLicence.uuid;
    [question saveToDBWithHandleData:NULL complete:NULL fail:NULL];
    CLog(@"%@", question.uuid);
    [muArrQuestions addObject:[question dictForCommit]];

    /*
     @property (assign, nonatomic) NSUInteger resultScore; //打分结果
     @property (copy, nonatomic) NSString *resultContent;
     @property (copy, nonatomic) NSString *resultRemark;
     @property (copy, nonatomic) NSArray *resultDetails;

     @property (copy, nonatomic) NSString *resultAttachmentId;  //结果附件id
     没做
     */
    GTOAnswer *answer = [GTOAnswer DBObject];
    [answer praseFromJsonDict:dictItem];

    NSUInteger count = 0; //记录是否被回答：根据答案有无
    if (answer.resultScore)
      count++;
    if (answer.resultContent)
      count++;
    if (answer.resultRemark)
      count++;
    if (answer.resultDetails.count)
      count++;
    if (count > 0) {
      answer.resultAttachmentUrls = item.resultAttachmentUrls;
      answer.resultAttachmentId = item.resultAttachmentId;
      answer.bIsAnswered = YES;
      answer.questionUuid = item.uuid;
      answer.licenceUuid = _d_currentLicence.uuid;
      if (answer.resultAttachmentUrls.count > 0)
        answer.bIsDownLoadImgs = YES;
      for (NSDictionary *dict in answer.resultAttachmentUrls) {
        ICRPostAttachment *postAttachment = [ICRPostAttachment DBObject];
        [postAttachment praseFromJsonDict:dict];
        postAttachment.is_localPhoto = NO;
        postAttachment.is_delete = NO;
        postAttachment.addTime = [[NSDate date] httpParameterString];
        postAttachment.licenceUuid = _d_currentLicence.uuid;
        postAttachment.questionUuid = answer.questionUuid;
        postAttachment.entityType = GTO_ENTITYTYPE_PIONEER_ANSWER;
        postAttachment.entityUuid = answer.resultAttachmentId;
        [postAttachment saveToDBWithHandleData:NULL complete:NULL fail:NULL];
      }
      [answer saveToDBWithHandleData:NULL complete:NULL fail:NULL];
    }

    [muArrCategory addObject:item.category];
  }
  _d_currentLicence.questions = muArrQuestions;
  // GTODisplayResult
  NSSet *setCategory = [NSSet setWithArray:muArrCategory];
  NSMutableArray *muArrDisplayRs = [NSMutableArray array];
  for (NSString *category in setCategory) {
    NSMutableArray *muArrQuestions = [NSMutableArray array];
    for (NSDictionary *dictQ in _d_currentLicence.questions) {
      GTOQuestion *question = [GTOQuestion DBObject];
      [question praseFromJsonDict:dictQ];
      if ([question.category isEqualToString:category]) {
        [muArrQuestions addObject:dictQ];
      }
    }
    GTODisplayResult *displayR = [GTODisplayResult DBObject];
    displayR.arrQuestions = muArrQuestions;
    displayR.arrAnswers = muArrAnswers;
    displayR.category = category;
    displayR.isDisplay = NO;
    [muArrDisplayRs addObject:[displayR dictForCommit]];
  }

  _d_currentLicence.arrDisplayResults = muArrDisplayRs;
  [_d_currentLicence saveToDBWithHandleData:NULL
      complete:^{
        [self fetchResult];
      }
      fail:^(NSError *error) {

        [IBTLoadingView hideHUDWithText:error.localizedDescription];
      }];
}
- (void)p_addAlerInfoLicenceView {
  GTOAlertInfoLicenceViewController *alertInfoVC =
      [[GTOAlertInfoLicenceViewController alloc]
          initWithLicence:_d_currentLicence];
  self.alertInfoVC = alertInfoVC;
  alertInfoVC.delegate = self;
  [[UIApplication sharedApplication].keyWindow addSubview:_alertInfoVC.view];
}
//找到对应的答案并跳转结果页面
- (void)fetchResult { //答案的个数
  ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
    NSString *sql = [NSString
        stringWithFormat:@"SELECT *  FROM %@ WHERE %@ = ? ORDER BY %@",
                         [GTOAnswer TableName], @"licenceUuid",
                         @"questionUuid"];
    //答案的排序按照问题的uuid来，（此事的排序关系到结果页中答案的显示，按道理应该是根据答题的顺序，是不是后台给的问题应该排序？？？？？）
    NSLog(@"%@", sql);
    return [db executeQuery:sql, _d_currentLicence.uuid];
  };

  __weak typeof(self) weakSelf = self;
  ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
    __strong __typeof(weakSelf) strongSelf = weakSelf;

    NSMutableArray *muArrDisplayRs = [NSMutableArray array];
    for (int count = 0; count < _d_currentLicence.arrDisplayResults.count;
         count++) {
      // NSInteger finiseNumber = 0;
      GTODisplayResult *displayR = [GTODisplayResult DBObject];
      [displayR praseFromJsonDict:_d_currentLicence.arrDisplayResults[count]];
      // displayR.answerNumber = 0;
      NSMutableArray *muArrAnswers = [NSMutableArray array];
      for (GTOAnswer *answer in fetchedObjects) {
        if ([answer.category isEqualToString:displayR.category])
          // displayR.answerNumber++;
          [muArrAnswers addObject:[answer dictForCommit]];
      }
      displayR.arrAnswers = muArrAnswers;

      [muArrDisplayRs addObject:[displayR dictForCommit]];
    }
    _d_currentLicence.arrDisplayResults = muArrDisplayRs;
    [_d_currentLicence
        saveToDBWithHandleData:nil
                      complete:^{
                        GTOLiceneResultViewController *resultVC =
                            [[GTOLiceneResultViewController alloc]
                                initWithLicence:_d_currentLicence];
                        // resultVC.
                        [self PushViewController:resultVC animated:YES];
                      }
                          fail:nil];

  };

  ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
  [dbCtrl runFetchForClass:[GTOAnswer class]
                fetchBlock:fetchBlk
         fetchResultsBlock:fetchResultsBlk];
}

#pragma button Action
- (void)addLicenceClicked {
  GTOLicenceNewViewController *newVC =
      [[GTOLicenceNewViewController alloc] init];
  newVC.d_repair = _d_repair;
  [self PushViewController:newVC animated:NO];
}

- (void)onShowImagePicker:(__unused id)sender {
  [self.m_imagePicker showImagePickerTitle:nil
                                 mediaType:kIBTMediaBImage
                                  editable:NO
                        fromViewController:self];
}
- (void)onTapImage:(ICRAttachmentUnit *)unit {

  CGRect rect =
      [self.view.window convertRect:unit.frame fromView:unit.superview];

  UIImage *img = unit.m_oAttachmentWrap;
  JTImagePreviewer *ipv =
      [[JTImagePreviewer alloc] initWithViewController:self
                                             tempImage:img
                                                   url:nil
                                             startRect:rect];
  [ipv show];
}
- (void)onTapImageView:(ICRAttachmentUnit *)unit {

  CGRect rect =
      [self.view.window convertRect:unit.frame fromView:unit.superview];

  UIImage *img = unit.m_imageView.image;
  JTImagePreviewer *ipv =
      [[JTImagePreviewer alloc] initWithViewController:self
                                             tempImage:img
                                                   url:nil
                                             startRect:rect];
  [ipv show];
}

#pragma mark - IBTImagePickerDelegate
- (void)imagePicker:(IBTImagePickerController *)picker
     didImagePicked:(UIImage *)image
       referenceURL:(NSURL *)imageUrl {
  IBTFileData *imgFile = [IBTCommon saveImageToLocal:image];

  ICRPostAttachment *attE = [[ICRPostAttachment alloc] init];

  attE.entityType = GTO_ENTITYTYPE_REPAIR;
  attE.fileName = imgFile.fileName;
  attE.content = [imgFile.fileData base64EncodedString];
  attE.filePath = imgFile.filePath;
  if (!self.d_postAttachment) {
    self.d_postAttachment = attE;
    self.d_postAttachment.entityUuid = [[ICRUserUtil sharedInstance] mobileID];
  }
  attE.entityUuid = self.d_postAttachment.entityUuid;
  if (!self.d_muArrPhotos) {
    self.d_muArrPhotos = [NSMutableArray array];
  }

  attE.uuid = [[ICRUserUtil sharedInstance] mobileID];
  attE.repairUuid = _d_repair.uuid;
  attE.addTime = [[NSDate date] httpParameterString];
  [attE saveToDBWithHandleData:NULL complete:NULL fail:NULL];

  [self.d_muArrPhotos addObject:attE];
  [self addAttachment:image];
}

- (void)imagePicker:(IBTImagePickerController *)picker
    didVideoPickedWithURL:(NSURL *)videoUrl {
}
- (void)addAttachment:(id)oAtt { // oAtt 可以为图片，也可以为url

  SEL selector = NULL;

  UIImage *iconImg;
  ICRAttachmentView *attachView = nil;

  if ([oAtt isKindOfClass:[UIImage class]]) { //
    iconImg = oAtt;
    selector = @selector(onTapImage:);
    attachView = self.c_addPhotoV.m_photoAttachView;
  } else {
    iconImg = oAtt;
    selector = @selector(onTapImageView:);
    attachView = self.c_addPhotoV.m_photoAttachView;
  }

  ICRAttachmentUnit *attV = [[ICRAttachmentUnit alloc]
      initWithFrame:(CGRect){.origin.x = 0,
                             .origin.y = 0,
                             .size.width = IBT_ATTACH_UNIT_DEFAULT_WIDTH,
                             .size.height =
                                 IBT_ATTACH_UNIT_DEFAULT_WIDTH + 10}];
  if (_d_isDownLoadImg) {
    attachView.isDownImg = YES;
    attV.m_imageView.backgroundColor = [UIColor grayColor];
    dispatch_async(
        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
          [attV updateWithType:kATTNormal
                        masker:nil
                   placeHolder:nil
                         image:iconImg
                         title:nil];
        });
  } else {
    [attV updateWithType:kATTCloseBtn
                  masker:nil
             placeHolder:nil
                   image:iconImg
                   title:nil];
  }

  attV.m_oAttachmentWrap = oAtt;

  [attV addTarget:self
                action:selector
      forControlEvents:UIControlEventTouchUpInside];

  [attachView addContentAttachmentView:attV];
}

// 将字典或者数组转化为JSON串
- (NSString *)toJSONData:(id)theData {

  NSError *error = nil;
  NSData *jsonData =
      [NSJSONSerialization dataWithJSONObject:theData
                                      options:NSJSONWritingPrettyPrinted
                                        error:&error];

  if ([jsonData length] > 0 && error == nil) {
    return
        [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

  } else {
    return nil;
  }
}

#pragma GXFBottomViewDelegate
- (void)bottomView:(GXFBottomView *)bottomView
  oneButtonClicked:(UIButton *)oneBtn {

  switch (bottomView.tag) {
  case kBottomViewOneBackTag: {
    [self PopViewControllerAnimated:YES];

  }

  break;
  case kBottomViewOneApplicationTag: {
    [self httpApplicationRepair]; //
  } break;
  case kBottomViewOneFinishTag: {
    //结束报修前，应先添加图片
    [self httpUploadPhoto];
  } break;

  default:
    break;
  }
}
//申请结束报修
- (void)httpApplicationRepair {

  for (GTOLicence *licence in _d_muArrLicences) {
    if ([licence.state isEqualToString:@"submitted"] ||
        [licence.state isEqualToString:@"initial"] ||
        [licence.state isEqualToString:@"askforapprove"]) {
      [IBTLoadingView
          hideHUDWithText:
              @"有未提交或待审批的许可证,请处理完成后重试"];
      return;
    }
  }
  void (^succ)(id) = ^(id data) {
    if ([data[@"success"] integerValue] == 1) {
      [IBTLoadingView hideHUDForView:self.view];
      self.c_addPhotoV.hidden = NO;
      self.c_bottomView.tag = kBottomViewOneFinishTag;
      self.d_applyFinish = YES;
      [self.c_bottomView.f_oneBtn setTitle:@"结束报修"
                                  forState:UIControlStateNormal];
    } else {
      [IBTLoadingView hideHUDWithText:data[@"message"]];
    }

  };

  void (^fail)(id) = ^(id data) {
    [IBTLoadingView hideHUDWithText:nil];
    [IBTLoadingView showTips:data];
  };
  [IBTLoadingView showProgressLabel:@"申请结束报修 ..."];
  ICRHTTPController *httpC = [ICRHTTPController sharedController];
  [httpC dorepairApplicationWithRepairUuid:_d_repair.uuid
                                   version:_d_repair.version
                                   success:succ
                                   failure:fail];
}
// 上传报修图片
- (void)httpUploadPhoto {
  if (_d_muArrPhotos.count == 0) {

    [IBTLoadingView showTextOnly:@"结束报修前，请先添加图片" inView:self.view];
    return;
  }
  void (^succ)(id) = ^(id data) {
    if ([data[@"success"] integerValue] == 1) {

      [IBTLoadingView hideHUDForView:self.view];

      [self httpFinishRepair];

    } else {
      [IBTLoadingView hideHUDWithText:data[@"message"]];
    }
  };

  void (^fail)(id) = ^(id data) {

    [IBTLoadingView hideHUDWithText:nil];

    [IBTLoadingView showTips:data];

  };

  //    [IBTLoadingView showProgressLabel:@"正在上传图片"];

  ICRHTTPController *httpC = [ICRHTTPController sharedController];

  [httpC multiPartUploadWithEntityType:_d_postAttachment.entityType
                            entityUuid:_d_postAttachment.entityUuid
                  arrayPostAttachments:_d_muArrPhotos
                               success:succ
                               failure:fail];
}

//结束报修
- (void)httpFinishRepair {
  void (^succ)(id) = ^(id data) {
    if ([data[@"success"] integerValue] == 1) {
      [IBTLoadingView hideHUDForView:self.view];
      ICRDataBaseController *dataBaseC =
          [ICRDataBaseController sharedController];
      //删除本地图片
      [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString
            stringWithFormat:@"DELETE FROM %@ WHERE %@ = ?",
                             [ICRPostAttachment TableName], @"repairUuid"];
        [db executeUpdate:sql, _d_repair.uuid];
      }];
      [self PopViewControllerAnimated:YES];
    } else {
      [IBTLoadingView hideHUDWithText:data[@"message"]];
    }
  };

  void (^fail)(id) = ^(id data) {
    [IBTLoadingView hideHUDWithText:nil];
    [IBTLoadingView showTips:data];
  };
  [IBTLoadingView showProgressLabel:@"结束报修 ..."];
  ICRHTTPController *httpC = [ICRHTTPController sharedController];
  NSInteger version = 0;
  version = _d_applyFinish ? _d_repair.version + 1 : _d_repair.version;
  [httpC
      dorepairFinishWithRepairUuid:_d_repair.uuid
                           version:version
                      attachmentId:_d_postAttachment.entityUuid
                           success:succ
                           failure:
                               fail]; //在这里传的报修单的版本应该说是后台那边直接增加我拿到，然后传，但是“申请结束报修后”version增加了：要不直接重新拿数据
}
#pragma GTOAlertInfoLicenceViewControllerDelegate
- (void)alertInfoLicenceViewController:
            (GTOAlertInfoLicenceViewController *)alertInfoLicence
                 closeClickedWithBtton:(UIButton *)btn {
  // self.d_isClosed = YES;
  [_alertInfoVC.view removeFromSuperview];
}
- (void)alertInfoLicenceViewController:
            (GTOAlertInfoLicenceViewController *)alertInfoLicence
             seeResultClickedWithBtton:(UIButton *)btn {

  GTOLiceneResultViewController *resultVC =
      [[GTOLiceneResultViewController alloc] initWithLicence:_d_currentLicence];

  // self.d_isClosed = YES;
  [_alertInfoVC.view removeFromSuperview];
  [self PushViewController:resultVC animated:YES];
}
- (void)alertInfoLicenceViewController:
            (GTOAlertInfoLicenceViewController *)alertInfoLicence
                  nextClickedWithBtton:(UIButton *)btn {
  BOOL isAllFinished = YES;
  for (NSDictionary *dict in _d_currentLicence.arrDisplayResults) {
    GTODisplayResult *displayR = [GTODisplayResult DBObject];
    [displayR praseFromJsonDict:dict];
    if (displayR.arrAnswers.count < displayR.arrQuestions.count) {
      GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
      mgr.d_category = displayR.category;
      [mgr openQuestionVCFromViewControler:self
                                   Licence:_d_currentLicence
                                Pioneering:nil];
      [self alertInfoLicenceViewController:alertInfoLicence
                     closeClickedWithBtton:nil];
      isAllFinished = NO;
      break;
    }
  }

  if (isAllFinished) {
    NSDictionary *dictR = [_d_currentLicence.arrDisplayResults lastObject];
    GTODisplayResult *displayR = [GTODisplayResult DBObject];
    [displayR praseFromJsonDict:dictR];
    GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
    mgr.d_category = displayR.category;
    [mgr openQuestionVCFromViewControler:self
                                 Licence:_d_currentLicence
                              Pioneering:nil];
    [self alertInfoLicenceViewController:alertInfoLicence
                   closeClickedWithBtton:nil];
  }
}
- (void)alertInfoLicenceViewController:
            (GTOAlertInfoLicenceViewController *)alertInfoLicence
               didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
  GTODisplayResult *displayR = [GTODisplayResult DBObject];
  [displayR
      praseFromJsonDict:_d_currentLicence.arrDisplayResults[indexPath.row]];
  mgr.d_category =
      displayR.category; // alertInfoPioneering.d_arrCategorys[indexPath.row];
  [mgr openQuestionVCFromViewControler:self
                               Licence:_d_currentLicence
                            Pioneering:nil];

  [self alertInfoLicenceViewController:alertInfoLicence
                 closeClickedWithBtton:nil];
}

- (UIImageView *)imgNoData {
  if (!_imgNoData) {
    _imgNoData = [[UIImageView alloc] initWithFrame:CGRectMake(0, 300, 200, 100)];
    _imgNoData.contentMode = UIViewContentModeScaleAspectFit;
    _imgNoData.image = [UIImage imageNamed:@"no_data"];
    [self.c_tableView addSubview:_imgNoData];
    [_imgNoData mas_makeConstraints:^(MASConstraintMaker *make) {
      make.centerX.equalTo(self.view);
      make.centerY.mas_equalTo(@100);
    }];
    _imgNoData.hidden = YES;
  }
  return _imgNoData;
  
}

//原生的多图片上传
//- (BOOL)sendPhotoToTumblr: (NSString *)photo withCaption: (NSString *)caption
//{
//    //get image data from file
//    //photo为文件的
//    NSData *imageData = [NSData dataWithContentsOfFile:photo];
//    if (!imageData) return NO;
//
//    //create dictionary of post arguments
//    NSArray *keys = [[NSArray
//    alloc]initWithObjects:@"email",@"password",@"type",@"caption", nil];
//
//    NSArray *objects = [[NSArray alloc] initWithObjects:
//                        [NSString
//                        stringWithFormat:@"%@",CFPreferencesCopyAppValue(CFSTR("TumblrEmail"),
//                        kCFPreferencesCurrentApplication)],
//
//                        [NSString
//                        stringWithFormat:@"%@",CFPreferencesCopyAppValue(CFSTR("TumblrPassword"),
//                        kCFPreferencesCurrentApplication)],
//
//                        @"photo", caption, nil];
//    NSDictionary *keysDict = [[NSDictionary alloc]initWithObjects:objects
//    forKeys:keys];
//
//    //create tumblr photo post
//    NSURLRequest *tumblrPost = [self createTumblrRequest:keysDict
//    withData:imageData];
//
//
//    //send request, returen YES if successful
//    NSURLConnection *tumblrConnection = [[NSURLConnection
//    alloc]initWithRequest:tumblrPost delegate:self];
//    if (!tumblrConnection) {
//        CLog(@"Fail to submit request");
//    } else {
//        CLog(@"Request submitted");
//       // NSMutableData *receiveDate = [[NSMutableData data] retain];
//    }
//    return YES;
//
//}
//
//
//- (NSURLRequest *)createTumblrRequest: (NSDictionary *)postKeys withData:
//(NSData *)data {
////tumblr:微博客
//    //create the URL POST Request to tumblr
//    NSURL *tumblrURL = [NSURL URLWithString:@""];//url
//    NSMutableURLRequest *tumblrPost = [NSMutableURLRequest
//    requestWithURL:tumblrURL];
//    [tumblrPost setHTTPMethod:@"POST"];   //请求
//
//    //Add the header info
//    NSString *stringBoundary = @"0xKhTmLbOuNdArY";//?????
//    NSString *contentType = [NSString
//    stringWithFormat:@"multipart/form-data;boundary=%@",stringBoundary];
//    [tumblrPost addValue:contentType forHTTPHeaderField:@"Content-Type"];
//
//
//    //create the body
//    NSMutableData *postBody = [NSMutableData data];
//    [postBody appendData:[[NSString
//    stringWithFormat:@"--%@\r\n",stringBoundary]
//    dataUsingEncoding:NSUTF8StringEncoding]];
//
//    //add key values from the NSDictionary object
//    NSEnumerator *keys = [postKeys keyEnumerator];
//    int i;
//    for (i = 0; i < [postKeys count]; i++) {
//        NSString *tempKey = [keys nextObject];
//        [postBody appendData:[[NSString
//        stringWithFormat:@"Content-Disposition: form-data;
//        name=\"%@\"\r\n\r\n",tempKey]
//        dataUsingEncoding:NSUTF8StringEncoding]];
//        [postBody appendData:[[NSString stringWithFormat:@"%@",[postKeys
//        objectForKey:tempKey]] dataUsingEncoding:NSUTF8StringEncoding]];
//        [postBody appendData:[[NSString
//        stringWithFormat:@"\r\n--%@\r\n",stringBoundary]
//        dataUsingEncoding:NSUTF8StringEncoding]];
//    }
//
//    //add data field and file data
//  //  [NSString
//  stringWithString:@"Content-Type:application/octet-stream\r\n\r\n"];
//    [postBody appendData:[@"Content-Disposition: form-data; name=\"data\"\r\n"
//    dataUsingEncoding:NSUTF8StringEncoding]];
//    [postBody appendData:[@"Content-Type:application/octet-stream\r\n\r\n"
//    dataUsingEncoding:NSUTF8StringEncoding]];
//    [postBody appendData:[NSData dataWithData:data]];
//    [postBody appendData:[[NSString
//    stringWithFormat:@"\r\n--%@--\r\n",stringBoundary]
//    dataUsingEncoding:NSUTF8StringEncoding]];
//
//    //add the body to the post
//    [tumblrPost setHTTPBody:postBody];
//
//    return tumblrPost;
//}
//

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

@end
