//
//  GTORe ultViewController.m
//  total
//
//  Created by freecui on 15/10/19.
//  Copyright (c) 2015年 free. All rights reserved.
//

#import "GTOLiceneResultViewController.h"
#import "ICRAttachmentView.h"
#import "ICRQuestionHelperView.h"
#import "HttpRequestManager.h"
#import "GTOLicence.h"

#import "GTOAnswer.h"
#import "GTODisplayResult.h"
#import "GTOQuestion.h"

#import "GTOPatrolPlanResultHeaderItem.h"
#import "GTOPatrolPlanResultProblemItem.h"
//#import "GTOPatrolPlanResultTopItem.h"
#import "GTOLicenceResultTopCellContentView.h"

//#import "GTOPioneeringListViewController.h"
#import "GTOPioneeringSurveyItem.h"
//#import "GTOPioneeringResult.h"
#import "GTOEditPioneeringViewController.h"
#import "GTOLicenceResult.h"
#import "GXFBottomView.h"

#import "GTOButtonHeaderContentView.h"
#import "GTOLicenceCheckListViewController.h"
#import "GTOLicenceListViewController.h"
#import "GTOLicenceResultHeaderContentView.h"
#import "GTOQuestionBaseViewController.h"
#import "GTOQuestionManager.h"
#import "GTORepair.h"
#import "GTORepairDetailViewController.h"
#import "ICRPostAttachment.h"
#define GXF_DETAIL_COLOR HexColor(@"888888")
#define GXF_CONTENT_COLOR HexColor(@"444444")
#define KEY_IS_DISPLAY @"isDisplay"


typedef NS_ENUM(NSUInteger, bottomViewTag) {
    kBottomViewOneSaveTag = 0,
    kBottomViewTwoSaveSubmitTag,
    kBottomViewTwoRejectedApprovedTag,
    kBottomViewOneBackTag,
    kBOttomViewAskForApprove
};
typedef NS_ENUM(NSUInteger, alertViewTag) {
    kAlertViewSubmiteTag = 0,
    kAlertViewApprovedTag,
    kAlertViewRejectedTag,
    kAlertViewAskForApprove,
    kAlertViewClose
};
static NSString *cellID = @"cellID";
//只有标题
static NSString *headerTitleItemID = @"headerID";
static NSString *headerBtnItemID = @"headerBtnItem";
//可以点击(存放问题的header)
static NSString *headerProblemItemID = @"headerItem";

@interface GTOLiceneResultViewController () <UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, GTOPatrolPlanResultHeaderItemDelegate, GXFBottomViewDelegate, UIAlertViewDelegate>

@property (strong, nonatomic) ICRQuestionHelperView *m_helperView;
@property (nonatomic, strong) NSIndexPath *m_clickedIndexPath;
/////
@property (strong, nonatomic) GTOLicence *d_licence;
//@property (strong, nonatomic) GTORepair *d_repair;
@property (nonatomic, strong) UITableView *c_tableView;

@property (nonatomic, strong) NSMutableArray *d_arrPostAttachments;

@end

@implementation GTOLiceneResultViewController

#pragma mark - Life Cycle

- (instancetype)initWithLicence:(GTOLicence *)licence
{// andRepair: (GTORepair *)repair {
    self = [super init];
    if (!self) {
        return nil;
    }

    if ([licence isKindOfClass:[GTOLicence class]]) {
        self.d_licence = licence;
        // self.d_repair = repair;
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.title = @"许可证结果";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doHttp:) name:@"doHttp" object:nil];
    [self initSubViews];
}
- (void)viewWillAppear:(BOOL)animated
{
    [self updateAnswer];
}

- (void)updateAnswer
{
    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_licence.uuid];
    };

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

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

            [muArrDisplayRs addObject:[displayR dictForCommit]];
        }
        strongSelf.d_licence.arrDisplayResults = muArrDisplayRs;
        [strongSelf.d_licence saveToDBWithHandleData:nil
                                  complete:^{
                                      [strongSelf.c_tableView reloadData];
                                  }
                                      fail:nil];

    };

    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[GTOAnswer class] fetchBlock:fetchBlk fetchResultsBlock:fetchResultsBlk];
}
- (void)initSubViews
{
    // tableView
    self.c_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 60 - 64) style:UITableViewStylePlain];
    self.c_tableView.delegate = self;
    self.c_tableView.dataSource = self;
    self.c_tableView.tableFooterView = [UIView new];
    [self.c_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellID];
    [self.c_tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:headerBtnItemID];
    [self.c_tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:headerTitleItemID];
    [self.c_tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:headerProblemItemID];
    [self.view addSubview:_c_tableView];

    // bottomView
    BOOL highApprovePermission = [GTOCommonTools hasPermissionWithPermissionId:500403];  //高级审批权
    BOOL middleApprovePermission = [GTOCommonTools hasPermissionWithPermissionId:500404];//中级审批权
    BOOL approvePermission = NO;
    if (highApprovePermission) {
        approvePermission = YES;
    } else if (!highApprovePermission && middleApprovePermission) {
        if ([_d_licence.riskGrade isEqualToString:GTO_LICENCE_RISK_HIGHT]) {
            approvePermission = NO;
        }else if ([_d_licence.riskGrade isEqualToString:GTO_LICENCE__RISK_MIDDLE]) {
            approvePermission = YES;
        }
    }

    CGRect rect = CGRectMake(0, _c_tableView.bottom, self.view.width, 60);
    GXFBottomView *bottomV;
    
    //判断是否在时间区间内
    BOOL bet = [GTOCommonTools nowInTimeDuringMinTime:_d_licence.beginDate maxTime:_d_licence.endDate];
    
    //是已提交状态 && 有权限
    BOOL isSubmitted = [_d_licence.state isEqualToString:GTO_LICENCE__STATE_SUBMITTED] && [GTOCommonTools hasPermissionWithPermissionId:500405];
    
    //申请审批状态 && 有审批权
    BOOL isAskForApprove = [_d_licence.state isEqualToString:GTO_LICENCE__STATE_ASKFORAPPROVE] && approvePermission;
    
    if ([_d_licence.state isEqualToString:GTO_LICENCE_STATE_INITIAL] || [_d_licence.state isEqualToString:GTO_LICENCE_STATE_LOCAL]) {
        NSUInteger noFinishNumber = 0;
        for (NSDictionary *dictDisplayR in _d_licence.arrDisplayResults) {
            GTODisplayResult *displayR = [GTODisplayResult DBObject];
            [displayR praseFromJsonDict:dictDisplayR];
            if (displayR.arrAnswers.count != displayR.arrQuestions.count) noFinishNumber++;
        }
        if (noFinishNumber > 0) {
            bottomV = [[GXFBottomView alloc] initOneButtonWithFrame:rect buttonColor:GTO_BLUE_DEEP_COLOR buttonTitle:@"返回"];
            bottomV.tag = kBottomViewOneBackTag;

        } else {
            bottomV = [[GXFBottomView alloc] initWithFrame:rect
                                           leftButtonColor:GTO_BLUE_DEEP_COLOR
                                          rightButtonColor:GTO_RED_COLOR
                                              LeftBtnTitle:@"保存"
                                             rightBtnTitle:@"提交"];
            bottomV.tag = kBottomViewTwoSaveSubmitTag;
        }

    } else if (isSubmitted) {
        bottomV = [[GXFBottomView alloc] initOneButtonWithFrame:rect buttonColor:GTO_RED_COLOR buttonTitle:@"申请审批"];
        bottomV.tag = kBOttomViewAskForApprove;
    }else if (isAskForApprove) {
        bottomV = [[GXFBottomView alloc] initWithFrame:rect
                                       leftButtonColor:GTO_BLUE_DEEP_COLOR
                                      rightButtonColor:GTO_RED_COLOR
                                          LeftBtnTitle:@"审批拒绝"
                                         rightBtnTitle:@"审批通过"];
        bottomV.tag = kBottomViewTwoRejectedApprovedTag;
        
    }else {
        bottomV = [[GXFBottomView alloc] initOneButtonWithFrame:rect buttonColor:GTO_BLUE_DEEP_COLOR buttonTitle:@"返 回"];
        bottomV.tag = kBottomViewOneBackTag;
    }

    //这三种状态有权限的时候添加关闭按钮
    if ([_d_licence.state isEqualToString:GTO_LICENCE__STATE_APPROVED] ||
        [_d_licence.state isEqualToString:GTO_LICENCE__STATE_ASKFORAPPROVE] ||
        [_d_licence.state isEqualToString:GTO_LICENCE__STATE_SUBMITTED]) {
        if ([GTOCommonTools hasPermissionWithPermissionId:500406]) {
            [bottomV addCloseButton];
        }
    }
    
    bottomV.backgroundColor = XXFBgColor;
    bottomV.delegate = self;
    [self.view addSubview:bottomV];
}

#pragma UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2 + _d_licence.arrDisplayResults.count;//_d_arrDisplayResults.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    CLog(@"indexpath section = %ld", section);
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 0;
    } else {

        for (int count = 0; count < _d_licence.arrDisplayResults.count; count++) {//
            if (section == count + 2) {
                GTODisplayResult *displayR = [GTODisplayResult DBObject];
                [displayR praseFromJsonDict:_d_licence.arrDisplayResults[count]];
                return displayR.isDisplay ? displayR.arrQuestions.count : 0;
            }
        }

        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    [self configureCell:cell forRowAtIndexPath:indexPath];
    // cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)configureCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{

    UIView *contentView = cell.contentView;
    if (indexPath.section == 0) {
        GTOLicenceResultTopCellContentView *topItem = [contentView viewWithClass:[GTOLicenceResultTopCellContentView class]];
        if (!topItem) {
            topItem = [[GTOLicenceResultTopCellContentView alloc] initWithFrame:contentView.bounds];
            [topItem autoresizingWithStrechFullSize];
            [contentView addSubview:topItem];
        }
        [topItem updateWithLicence:_d_licence arrayDictDisplayResults:_d_licence.arrDisplayResults];

    } else if (indexPath.section > 1) {

        GTOPatrolPlanResultProblemItem *problemItem = [contentView viewWithClass:[GTOPatrolPlanResultProblemItem class]];
        if (!problemItem) {
            problemItem = [[GTOPatrolPlanResultProblemItem alloc] initWithFrame:contentView.bounds];
            self.m_clickedIndexPath = indexPath;
            problemItem.m_modifyBtn.tag = indexPath.row;
            [problemItem.m_modifyBtn addTarget:self action:@selector(modifyClicked:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:problemItem];
        }
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:_d_licence.arrDisplayResults[indexPath.section - 2]];
        GTOQuestion *question = [GTOQuestion DBObject];
        [question praseFromJsonDict:displayR.arrQuestions[indexPath.row]];
        [self uploadePatrolPlanResultProblemItemAnswer:problemItem question:question cellForRowAtIndexPath:indexPath];
    } else {
    }
}

- (void)uploadePatrolPlanResultProblemItemAnswer:(GTOPatrolPlanResultProblemItem *)problemItem question:(GTOQuestion *)question cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db)
    {
        NSString *sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE %@ = ? AND %@ = ? AND %@ = ?", [GTOAnswer TableName], @"licenceUuid", @"questionUuid", @"category"];
        //答案的排序按照问题的uuid来，（此事的排序关系到结果页中答案的显示，按道理应该是根据答题的顺序，是不是后台给的问题应该排序？？？？？）
        NSLog(@"%@", sql);
        return [db executeQuery:sql, _d_licence.uuid, question.uuid, question.category];
    };
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {

        if (fetchedObjects) {
            GTOAnswer *answer = fetchedObjects[0];
            [problemItem updateWithQuestion:question answer:answer index:indexPath.row];
        } else {
            [problemItem updateWithQuestion:question answer:nil index:indexPath.row];
        }
    };
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[GTOAnswer class] fetchBlock:fetchBlk fetchResultsBlock:fetchResultsBlk];
}
#pragma UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section < 2) {
        return;
    }

    GTODisplayResult *displayR = [GTODisplayResult DBObject];
    [displayR praseFromJsonDict:_d_licence.arrDisplayResults[indexPath.section - 2]];
    GTOQuestion *question = [GTOQuestion DBObject];
    [question praseFromJsonDict:displayR.arrQuestions[indexPath.row]];
    GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
    mgr.d_category = question.category;

    BOOL notEdit = NO;
    if ([_d_licence.state isEqualToString:GTO_LICENCE_STATE_INITIAL] || [_d_licence.state isEqualToString:GTO_LICENCE_STATE_LOCAL]) {
        notEdit = NO;
    } else {
        notEdit = YES;
    }
    [mgr openQuestionVCFromViewControler:self Licence:_d_licence Pioneering:nil IsNotEdit:notEdit ProblemIndex:indexPath.row + 1];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 156;
    } else {
        return 55;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return HEADER_HEIGHT;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UITableViewHeaderFooterView *headerView = nil;
    if (section == 0) {
        headerView = [self tableHeaderFooterViewWithTableView:tableView andHeaderID:headerBtnItemID];
    } else if (section == 1) {
        headerView = [self tableHeaderFooterViewWithTableView:tableView andHeaderID:headerTitleItemID];
    } else {
        headerView = [self tableHeaderFooterViewWithTableView:tableView andHeaderID:headerProblemItemID];
    }
    CGRect rect = CGRectMake(0, 0, tableView.width, 50);
    [self configureHeaderView:headerView frameWithRect:rect viewForSection:section];
    return headerView;
}
- (UITableViewHeaderFooterView *)tableHeaderFooterViewWithTableView:(UITableView *)tableView andHeaderID:(NSString *)headerId
{
    UITableViewHeaderFooterView *headerView = nil;
    headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerId];
    if (!headerView) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:headerId];
    }
    return headerView;
}
- (void)configureHeaderView:(UITableViewHeaderFooterView *)headerView frameWithRect:(CGRect)rect viewForSection:(NSInteger)section
{
    UIView *contentView = headerView.contentView;
    CGFloat padding = 10;
    if (section == 0) {
        GTOButtonHeaderContentView *btnView = [contentView viewWithClass:[GTOButtonHeaderContentView class]];
        if (!btnView) {
            btnView = [[GTOButtonHeaderContentView alloc] initWithFrame:rect];
            [btnView.m_btn addTarget:self action:@selector(seeRepairClicked) forControlEvents:UIControlEventTouchUpInside];
            [contentView addSubview:btnView];
        }
        [btnView updateWithTitleLabelText:@"许可证" andButtonLabelText:@"查看报修单"];

    } else if (section == 1) {

        GTOLicenceResultHeaderContentView *view = [contentView viewWithClass:[GTOLicenceResultHeaderContentView class]];
        if (!view) {
            view = [[GTOLicenceResultHeaderContentView alloc] initWithFrame:rect];
            [contentView addSubview:view];
        }
        [view updateWithString:@"许可证问题结果"];

    } else {

        GTOPatrolPlanResultHeaderItem *resultHeader = [contentView viewWithClass:[GTOPatrolPlanResultHeaderItem class]];
        if (!resultHeader) {
            resultHeader = [[GTOPatrolPlanResultHeaderItem alloc] initWithFrame:rect];//
            [contentView addSubview:resultHeader];
        }
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:_d_licence.arrDisplayResults[section - 2]];
        resultHeader.isDisplay = displayR.isDisplay;// isDisplay;
        resultHeader.delegate = self;
        resultHeader.backgroundColor = [UIColor whiteColor];
        //刷新数据
        [resultHeader updateWithDisplayResult:displayR];
        resultHeader.tag = section;
    }
}

- (GTOLicenceResult *)p_licenceResult
{

    //_d_arrDisplayResults
    NSMutableArray *muArrItems = [NSMutableArray array];
    for (NSDictionary *dictDisplayR in _d_licence.arrDisplayResults) {
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:dictDisplayR];

        for (NSDictionary *dictQuestion in displayR.arrQuestions) {//一条数据
            GTOQuestion *question = [GTOQuestion DBObject];
            [question praseFromJsonDict:dictQuestion];
            GTOPioneeringSurveyItem *surveyItem = [[GTOPioneeringSurveyItem alloc] init];
            NSMutableDictionary *muDictItem = [NSMutableDictionary dictionary];
            GTOAnswer *ans;//找到问题对应的answer
            for (NSDictionary *dictAnswer in displayR.arrAnswers) {
                GTOAnswer *answer = [GTOAnswer DBObject];
                [answer praseFromJsonDict:dictAnswer];
                if ([question.uuid isEqualToString:answer.questionUuid]) {
                    ans = answer;
                    break;
                }
            }
            surveyItem.uuid = question.uuid;//用答案的uuid去标识每个问题的uuid

            surveyItem.details = question.details;
            surveyItem.resultDetails = ans.resultDetails;

            surveyItem.category = question.category;
            surveyItem.type = question.type;
            surveyItem.lineNo = question.lineNo;
            surveyItem.reference = question.reference;
            surveyItem.attachmentId = question.attachmentId;
            surveyItem.resultAttachmentId = ans.resultAttachmentId;
            surveyItem.title = question.title;
            surveyItem.star = question.star;
            surveyItem.scoreFrom = question.scoreFrom;
            surveyItem.scoreTo = question.scoreTo;
            surveyItem.writingReply = question.writingReply;
            surveyItem.pictureReply = question.pictureReply;
            surveyItem.recordReply = question.recordReply;

            if (ans) {
                surveyItem.resultScore = ans.resultScore;
                surveyItem.resultContent = ans.resultContent;
                surveyItem.resultRemark = ans.resultRemark;
                surveyItem.resultAttachmentId = ans.resultAttachmentId;
            }

            [muArrItems addObject:[surveyItem dictForCommit]];
        }
    }

    GTOLicenceResult *result = [[GTOLicenceResult alloc] init];
    result.uuid = _d_licence.uuid;
    result.version = _d_licence.version;
    result.billnumber = _d_licence.billnumber;
    result.requestDate = _d_licence.requestDate;
    result.engineer_uuid = _d_licence.engineer_uuid;
    result.engineer_code = _d_licence.engineer_code;
    result.engineer_name = _d_licence.engineer_name;
    result.licenceType = _d_licence.licenceType;
    result.repairUuid = _d_licence.repairUuid;
    result.repairNumber = _d_licence.repairNumber;
    result.riskGrade = _d_licence.riskGrade;
    result.store_uuid = _d_licence.store_uuid;
    result.store_code = _d_licence.store_code;
    result.store_name = _d_licence.store_name;
    result.validHours = _d_licence.validHours;
    //    result.beginDate = _d_licence.beginDate;
    //    result.endDate = _d_licence.endDate;
    result.items = muArrItems;

    return result;
}

//保存
- (void)httpSaveLicenceResult
{
    self.d_licence.beginDate = [[NSDate date] httpParameterString];
    self.d_licence.endDate = [[[NSDate date] dateAddHourse:3] httpParameterString];

    GTOLicenceResult *licenceR = [self p_licenceResult];

    [IBTLoadingView hideHUDWithText:nil];
    [IBTLoadingView showProgressLabel:@"正在保存"];

    void (^success)(id data) = ^(id data) {
        if ([data[@"success"] integerValue] == 1) {
            [IBTLoadingView hideHUDWithText:nil];
            [self localDelete];
            if (_d_isNew) {
                [self PopToViewControllerAtIndex:2 animated:YES];
            } else {
                [self PopViewControllerAnimated:YES];
            }
        } else {
            [IBTLoadingView showTextOnly:data[@"message"] inView:self.view];
        }

    };
    void (^failure)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        //        CLog(@"%@", data);
    };

    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doSaveLicenceResultWithData:[licenceR dictForCommit] success:success failure:failure];
}

//提交
- (void)httpSubmitLicenceResult
{
    self.d_licence.beginDate = [[NSDate date] httpParameterString];
    self.d_licence.endDate = [[[NSDate date] dateAddHourse:0] httpParameterString];
    GTOLicenceResult *licenceR = [self p_licenceResult];
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];

    [IBTLoadingView hideHUDWithText:nil];
    [IBTLoadingView showProgressLabel:@"正在提交"];

    void (^success)(id data) = ^(id data) {
        if ([data[@"success"] integerValue] == 1) {
            [IBTLoadingView hideHUDWithText:nil];
            [self localDelete];
            if (_d_isNew) {
                [self PopToViewControllerAtIndex:2 animated:YES];
            } else {
                [self PopViewControllerAnimated:YES];
            }
        } else {
            [IBTLoadingView showTextOnly:data[@"message"] inView:self.view];
        }

    };
    void (^failure)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
    };

    [httpCtrl doSubmitLicenceResultWithData:[licenceR dictForCommit] success:success failure:failure];
}

//审批拒绝
- (void)httpRejectedLicenceResultWithRejectCause:(NSString *)cause
{
    [IBTLoadingView showProgressLabel:@"审批拒绝中"];
    void (^success)(id data) = ^(id data) {
        if ([data[@"success"] integerValue] == 1) {
            [IBTLoadingView hideHUDWithText:nil];
            [self localDelete];
            [self PopViewControllerAnimated:YES];
        } else {
            [IBTLoadingView showTextOnly:data[@"message"] inView:self.view];
        }
    };
    void (^failure)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
    };

    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doLicenceRejectWithLicenceUuid:_d_licence.uuid version:_d_licence.version rejectCausen:cause success:success failure:failure];
}

//审批通过
- (void)httpApprovedLicenceResult
{
    [IBTLoadingView showProgressLabel:@"审批通过中"];
    void (^success)(id data) = ^(id data) {
        if ([data[@"success"] integerValue] == 1) {
            [IBTLoadingView hideHUDWithText:nil];
            [self localDelete];
            [self PopViewControllerAnimated:YES];
        } else {
            [IBTLoadingView showTextOnly:data[@"message"] inView:self.view];
        }
    };
    void (^failure)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
    };

    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doLicenceApproveWithLicenceUuid:_d_licence.uuid version:_d_licence.version success:success failure:failure];
    }

- (void)httpAskForApproveLicense {
    [IBTLoadingView showProgressLabel:@"申请审批中"];
    void (^success)(id data) = ^(id data) {
        if ([data[@"success"] integerValue] == 1) {
            [IBTLoadingView hideHUDWithText:nil];
            [self localDelete];
            [self PopViewControllerAnimated:YES];
        } else {
            [IBTLoadingView showTextOnly:data[@"message"] inView:self.view];
        }
    };
    void (^failure)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
    };
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doLicenceAskForApproveWithLicenceUuid:_d_licence.uuid version:_d_licence.version success:success failure:failure];

}

//上传附件
- (void)upLoadFlieWithAction:(NSString *)action
{

    __block NSInteger counts = 0;
    __block NSInteger totalCounts = _d_licence.arrDisplayResults.count;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.labelText = [NSString stringWithFormat:@"已上传%lu%%", counts * 100 / totalCounts];
    
    for (int count = 0; count < _d_licence.arrDisplayResults.count; count++) {
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:_d_licence.arrDisplayResults[count]];
        for (int ansCount = 0; ansCount < displayR.arrAnswers.count; ansCount++) {
            GTOAnswer *answer = [GTOAnswer DBObject];
            [answer praseFromJsonDict:displayR.arrAnswers[ansCount]];
            BOOL isFinish = NO;
            if ((ansCount == displayR.arrAnswers.count - 1) && (count == _d_licence.arrDisplayResults.count - 1)) {
                isFinish = YES;
            }
            
            //上传附件
            WS(weakSelf);
            ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
            [dbCtrl runFetchForClass:[ICRPostAttachment class] fetchBlock:^FMResultSet *(FMDatabase *db)
             {
                 NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? AND %@=? ORDER BY %@", [ICRPostAttachment TableName], @"questionUuid", @"licenceUuid", @"addTime"];
                 return [db executeQuery:sql, answer.questionUuid, answer.licenceUuid];
             } fetchResultsBlock:^(NSArray *fetchObjects) {
                 __strong __typeof(weakSelf) strongSelf = weakSelf;
                 if (!fetchObjects) {
                     if (!isFinish) {
                         return;
                     } else {
                       [hud hide:YES];
                         if ([action isEqualToString:@"save"]) {
                             [self httpSaveLicenceResult];
                         } else {
                             [self httpSubmitLicenceResult];
                         }
                         return;
                     }
                 }
                 if (fetchObjects.count > 0) {
                     
                     if (!_d_arrPostAttachments) {
                         strongSelf.d_arrPostAttachments = [@[] mutableCopy];
                     } else {
                         [strongSelf.d_arrPostAttachments removeAllObjects];
                     }
                     NSMutableArray *delArr = [@[] mutableCopy];
                     NSMutableArray *delArrPostAttachments = [@[] mutableCopy];
                     NSMutableArray *addArrPostAttachments = [@[] mutableCopy];
                     for (ICRPostAttachment *postAttachment in fetchObjects) {
                         if (postAttachment.is_delete) {
                             [delArr addObject:postAttachment.uuid];
                         }
                         if (postAttachment.is_localPhoto) {
                             [addArrPostAttachments addObject:postAttachment];
                             [strongSelf.d_arrPostAttachments addObject:postAttachment];
                         } else if (!postAttachment.is_localPhoto && postAttachment.is_delete) {
                             [delArrPostAttachments addObject:postAttachment];
                             [strongSelf.d_arrPostAttachments addObject:postAttachment];
                         } else {
                             
                         }
                     }
                     NSString *delStr = [delArr componentsJoinedByString:@";"];
                     if (delStr.length <= 0) {
                         delStr = @"";
                     }
                     if (addArrPostAttachments.count > 0 || delArrPostAttachments.count > 0) {
                         ICRPostAttachment *postAttachment = _d_arrPostAttachments[0];
                         ICRHTTPController *httpC = [ICRHTTPController sharedController];
                         if (delArrPostAttachments.count > 0) {
                             
                             [httpC deleteAttachments:delStr success:^(id data) {
                                 if ([data[@"success"] integerValue] == 1) {
                                     [strongSelf localDeleteOneAnswerPhotos:answer];
                                     if (!isFinish) {
                                         return;
                                     } else {
                                             [IBTLoadingView hideHUDWithText:nil];
                                             if ([action isEqualToString:@"save"]) {
                                                 [self httpSaveLicenceResult];
                                             } else {
                                                 [self httpSubmitLicenceResult];
                                             }
                                     }
                                     
                                 } else {
                                     [IBTLoadingView hideHUDWithText:data[@"message"]];
                                 }
                             } failure:^(id data) {
                                 [IBTLoadingView hideHUDWithText:@"上传删除的图片出错啦！ 请重新上传。"];
                             }];
                         }
                         
                         //添加附件
                         if (addArrPostAttachments.count > 0) {
                             [httpC multiPartUploadWithEntityType:postAttachment.entityType
                                                       entityUuid:postAttachment.entityUuid
                                             arrayPostAttachments:addArrPostAttachments
                                                          success:^(id data) {
                                                              if ([data[@"success"] integerValue] == 1) {
                                                                  counts++;
                                                                  CLog(@"------>count = %d", count);
                                                                  if (!isFinish) {
                                                                      [strongSelf localDeleteOneAnswerPhotos:answer];
                                                                      hud.labelText = [NSString stringWithFormat:@"已上传%lu%%", counts * 100 / _d_licence.arrDisplayResults.count];
                                                                      if (counts == totalCounts) {
                                                                          [[NSNotificationCenter defaultCenter] postNotificationName:@"doHttp" object:action];
                                                                          [IBTLoadingView hideHUDWithText:nil];

                                                                          [hud removeFromSuperview];
                                                                      }
                                                                      return;
                                                                  } else {
                                                                      
                                                                          
                                                                  }
                                                                  
                                                              } else {
                                                                  [IBTLoadingView hideHUDWithText:data[@"message"]];
                                                              }
                                                          }
                                                          failure:^(id data) {
                                                              [IBTLoadingView hideHUDWithText:@"上传图片出错啦！ 请重新上传。"];
                                                          }];
                         }
                         
                     } else {
                         if (!isFinish) {
                             return;
                         } else {
                             if ([action isEqualToString:@"save"]) {
                                 [self httpSaveLicenceResult];
                             } else {
                                 [self httpSubmitLicenceResult];
                             }
                         }
                     }
                 }
             }];
            
            
//            [self everyProblemUpLoadPhotoWithAnswer:answer isFinishedUpload:isFinish action:action index:count count:counts allCounts:_d_licence.arrDisplayResults.count hud:hud];
        }
    }
}

- (void)everyProblemUpLoadPhotoWithAnswer:(GTOAnswer *)answer
                         isFinishedUpload:(BOOL)isFinish
                                   action:(NSString *)action
                                    index:(NSInteger)index
                                    count:(NSInteger)counts
                                allCounts:(NSInteger)allcount
                                      hud:(MBProgressHUD *)hud
{
    //找到数据表中的附件

    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db)
    {
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? AND %@=? ORDER BY %@", [ICRPostAttachment TableName], @"questionUuid", @"licenceUuid", @"addTime"];
        return [db executeQuery:sql, answer.questionUuid, answer.licenceUuid];
    };

    __weak typeof(self) weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultBlk = ^(NSArray *fetchObjects) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        if (!fetchObjects) {
            if (!isFinish) {
                return;
            } else {
                if ([action isEqualToString:@"save"]) {
                    [self httpSaveLicenceResult];
                } else {
                    [self httpSubmitLicenceResult];
                }
                return;
            }
        }
        if (fetchObjects.count > 0) {

            if (!_d_arrPostAttachments) {
                strongSelf.d_arrPostAttachments = [@[] mutableCopy];
            } else {
                [strongSelf.d_arrPostAttachments removeAllObjects];
            }
            NSMutableArray *delArr = [@[] mutableCopy];
            NSMutableArray *delArrPostAttachments = [@[] mutableCopy];
            NSMutableArray *addArrPostAttachments = [@[] mutableCopy];
            for (ICRPostAttachment *postAttachment in fetchObjects) {
                if (postAttachment.is_delete) {
                    [delArr addObject:postAttachment.uuid];
                }
                if (postAttachment.is_localPhoto) {
                    [addArrPostAttachments addObject:postAttachment];
                    [strongSelf.d_arrPostAttachments addObject:postAttachment];
                } else if (!postAttachment.is_localPhoto && postAttachment.is_delete) {
                    [delArrPostAttachments addObject:postAttachment];
                    [strongSelf.d_arrPostAttachments addObject:postAttachment];
                } else {
                    
                }
            }
            NSString *delStr = [delArr componentsJoinedByString:@";"];
            if (delStr.length <= 0) {
                delStr = @"";
            }
            if (addArrPostAttachments.count > 0 || delArrPostAttachments.count > 0) {
                ICRPostAttachment *postAttachment = _d_arrPostAttachments[0];
                void (^succAdd)(id) = ^(id data) {
                    if ([data[@"success"] integerValue] == 1) {

                        if (!isFinish) {
                            [strongSelf localDeleteOneAnswerPhotos:answer];
                            hud.labelText = [NSString stringWithFormat:@"已上传%lu%%", (counts + 1) * 100 / allcount];
                            return;
                        } else {
                            [IBTLoadingView hideHUDWithText:nil];
                            if ([action isEqualToString:@"save"]) {
                                [self httpSaveLicenceResult];
                            } else {
                                [hud removeFromSuperview];
                                [self httpSubmitLicenceResult];
                            }
                        }

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

                void (^failAdd)(id) = ^(id data) {
                    [IBTLoadingView hideHUDWithText:@"上传图片出错啦！ 请重新上传。"];
                };

                void (^succDel)(id) = ^(id data) {
                    if ([data[@"success"] integerValue] == 1) {

                        [strongSelf localDeleteOneAnswerPhotos:answer];
                        if (!isFinish) {
                            return;
                        } else {
                            [IBTLoadingView hideHUDWithText:nil];
                            if ([action isEqualToString:@"save"]) {
                                [self httpSaveLicenceResult];
                            } else {
                                [self httpSubmitLicenceResult];
                            }
                        }

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

                void (^failDel)(id) = ^(id data) {
                    [IBTLoadingView hideHUDWithText:@"上传删除的图片出错啦！ 请重新上传。"];
                };

                ICRHTTPController *httpC = [ICRHTTPController sharedController];
                if (delArrPostAttachments.count > 0) {

                    [httpC deleteAttachments:delStr success:succDel failure:failDel];
                }
                if (addArrPostAttachments.count > 0) {
                    [httpC multiPartUploadWithEntityType:postAttachment.entityType
                                              entityUuid:postAttachment.entityUuid
                                    arrayPostAttachments:addArrPostAttachments
                                                 success:succAdd
                                                 failure:failAdd];
                }

            } else {
                if (!isFinish) {
                    return;
                } else {
                    if ([action isEqualToString:@"save"]) {
                        [self httpSaveLicenceResult];
                    } else {
                        [self httpSubmitLicenceResult];
                    }
                }
            }
        }
    };

    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRPostAttachment class] fetchBlock:fetchBlk fetchResultsBlock:fetchResultBlk];
}

//本地删除
- (void)localDelete
{
    //本地删除 许可证
    ICRDataBaseController *dataBaseC = [ICRDataBaseController sharedController];
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?", [GTOLicence TableName], @"uuid"];
        [db executeUpdate:strSql, _d_licence.uuid];
    }];
    //删除问题
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?", [GTOQuestion TableName], @"licenceUuid"];
        [db executeUpdate:strSql, _d_licence.uuid];
    }];
    //删除本地图片
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?", [GTOAnswer TableName], @"licenceUuid"];
        [db executeUpdate:strSql, _d_licence.uuid];
    }];
    //删除本地图片
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?", [ICRPostAttachment TableName], @"licenceUuid"];
        [db executeUpdate:strSql, _d_licence.uuid];
    }];
}
//本地删除 一个问题对应的答案的图片
- (void)localDeleteOneAnswerPhotos:(GTOAnswer *)answer
{
    ICRDataBaseController *dataBaseC = [ICRDataBaseController sharedController];
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql =
            [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=? AND %@=? ORDER BY %@", [ICRPostAttachment TableName], @"questionUuid", @"licenceUuid", @"addTime"];
        [db executeUpdate:strSql, answer.questionUuid, answer.licenceUuid];
    }];
}
#pragma bottomViewDelegate

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

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

        } break;
        case kBOttomViewAskForApprove:{
            //提交
            UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"确定申请审批？" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alertV.tag = kAlertViewAskForApprove;
            [alertV show];

        }
            break;
        default: break;
    }
}

- (void)bottomView:(GXFBottomView *)bottomView leftButtonClicked:(UIButton *)leftBtn
{
    switch (bottomView.tag) {
        case kBottomViewTwoSaveSubmitTag: {
            //保存
            //[self httpSubmitLicenceResult];
            [self upLoadFlieWithAction:@"save"];
        } break;
        case kBottomViewTwoRejectedApprovedTag: {
            UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"填写拒绝理由" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alertV.alertViewStyle = UIAlertViewStylePlainTextInput;
            alertV.tag = kAlertViewRejectedTag;
            [alertV show];

            // [self httpRejectedLicenceResult];

        } break;
        default: break;
    }
}

- (void)bottomView:(GXFBottomView *)bottomView RightButtonClicked:(UIButton *)rightBtn
{
    switch (bottomView.tag) {
        case kBottomViewTwoSaveSubmitTag: {
            //提交
            UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"确定提交" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alertV.tag = kAlertViewSubmiteTag;
            [alertV show];
            //            [self upLoadFlieWithAction: @"submit"];
        } break;
        case kBottomViewTwoRejectedApprovedTag: {
            UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"确定审批通过" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alertV.tag = kAlertViewApprovedTag;
            [alertV show];

        } break;
        default: break;
    }
}

//关闭许可证
- (void)bottomView:(GXFBottomView *)bottomView closeClicked:(UIButton *)oneBtn {
    UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"确定关闭许可证？" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertV.tag = kAlertViewClose;
    [alertV show];
}

- (void)closeLicense {
    [IBTLoadingView showProgressLabel:@"关闭中…"];
    void (^success)(id data) = ^(id data) {
        if ([data[@"success"] integerValue] == 1) {
            [IBTLoadingView hideHUDWithText:nil];
            [self localDelete];
            [self PopViewControllerAnimated:YES];
        } else {
            [IBTLoadingView showTextOnly:data[@"message"] inView:self.view];
        }
    };
    void (^failure)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
    };
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doLicenceAskForCloseWithLicenceUuid:_d_licence.uuid version:_d_licence.version success:success failure:failure];
}

- (void)modifyClicked:(UIButton *)btn
{
}

#pragma GTOPatrolPlanResultHeaderItemDelegate

// 巡检结果中：不同区的headerView
- (void)patrolPlanResultHeaderItem:(GTOPatrolPlanResultHeaderItem *)resultHeaderItem andIsDisplay:(BOOL)isDisplay
{
    NSInteger aIndex = resultHeaderItem.tag - 2;

    NSMutableArray *muArrDisplayRs = [NSMutableArray array];
    [muArrDisplayRs addObjectsFromArray:_d_licence.arrDisplayResults];
    GTODisplayResult *displayR = [GTODisplayResult DBObject];
    [displayR praseFromJsonDict:_d_licence.arrDisplayResults[aIndex]];
    displayR.isDisplay = !displayR.isDisplay;
    for (int count = 0; count < _d_licence.arrDisplayResults.count; count++) {
        if (count == aIndex) {
            [muArrDisplayRs replaceObjectAtIndex:aIndex withObject:[displayR dictForCommit]];
            break;
        }
    }

    _d_licence.arrDisplayResults = muArrDisplayRs;
    [_d_licence saveToDBWithHandleData:NULL
                              complete:^{
                                  [_c_tableView reloadData];
                              }
                                  fail:nil];
}
#pragma UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        switch (alertView.tag) {
            case kAlertViewSubmiteTag: {
                [self upLoadFlieWithAction:@"submit"];
            } break;
            case kAlertViewApprovedTag: {
                [self httpApprovedLicenceResult];
            } break;

            case kAlertViewRejectedTag: {
                UITextField *texfF = [alertView textFieldAtIndex:0];
                [self httpRejectedLicenceResultWithRejectCause:texfF.text];
            } break;
            case kAlertViewAskForApprove: {
                [self httpAskForApproveLicense];
            } break;
            case kAlertViewClose:{
                [self closeLicense];
            }break;
            default: break;
        }
    }
}

- (void)doHttp:(NSNotification *)note {
    NSString *action = note.object;
    if ([action isEqualToString:@"save"]) {
        [self httpSaveLicenceResult];
    } else {
        [self httpSubmitLicenceResult];
    }
}
#pragma button Action
- (void)seeRepairClicked
{
    GTORepairDetailViewController *repairDeVC = [[GTORepairDetailViewController alloc] initWithRepairUuid:_d_licence.repairUuid];
    [self PushViewController:repairDeVC animated:YES];
}
@end
