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

#import "BoltMaskView.h"
#import "GTOAllPatrolPlanViewController.h"
#import "GTOPaging.h"
#import "GTOPatrolPlan.h"
#import "GTOPatrolPlanCellContentView.h"
#import "GTOPatrolPlanListViewController.h"
#import "GTOQuestion.h"
#import "MJRefresh.h"
#import "SortMaskView.h"
#define TopMargin 44
#define TableHeight 120
#define LeftMargin 20
#define BtnWidth 60
#define BtnHeight 24
#define BtnSize 16

#define HexColor(colorStr) [UIColor colorWithHexString:colorStr]
#define GXF_DETAIL_COLOR                                                       \
  [UIColor colorWithHexString:@"888888"] // HexColor(@"888888")

#define PATROL_PLAN_CELL_HEIGHT 153
// typedef NS_ENUM(NSUInteger, PatrolSegmentsType) {
//    kPatrolSegUnFinished = 0,
//    kPatrolSegFinished,
//};

typedef enum : NSUInteger {
  SortTag = 3000,
  BoltTag

} BtnTag;

static NSString *PatrolPlanCellIdentifier = @"PatrolPlanCell";
@interface GTOPatrolPlanListViewController () <
    UITableViewDataSource, UITableViewDelegate, IBTScrollViewRefreshDelegate,
    SortMaskViewDelegate, BoltMaskViewDelegate> {
  BOOL _isRefresh;
  BOOL _isLoadMore;
  // NSInteger _currentPage;
}
@property(strong, nonatomic) UITableView *m_tableView;

@property(strong, nonatomic) NSMutableArray *m_arrAllData; //所以VI检查任务
@property(nonatomic, strong) UIBarButtonItem *c_sureBtn; //选择条件后确定按钮
@property(nonatomic, strong) UIButton *c_sortBtn;        // 排序按钮
@property(nonatomic, strong) UIButton *c_filterBtn;  //筛选
@property(nonatomic, strong) UIButton *c_currentBtn; //目前点击的按钮
@property(nonatomic, strong)
    UIView *c_maskView; //选择筛选条件时出现的灰色背景的view
@property(nonatomic, strong) SortMaskView *c_sortView; // 时间顺序
@property(nonatomic, strong) BoltMaskView *c_boltView;
@property(nonatomic, copy) NSString
    *d_state; //未提交=initial已提交=submitted调研中=insurvey已完成=finished
@property(nonatomic, strong) NSString *d_orderDirection; // asc(升序)，desc(降序)

@property(nonatomic, strong) NSString *d_titleLike;

@property(nonatomic, strong) NSString *d_patrolCategory;
@end

@implementation GTOPatrolPlanListViewController

- (instancetype)initWithTitle:(NSString *)title {
  self = [super init];
  if (!self) {
    return nil;
  }
  self.d_patrolCategory = title;
  self.title = [GTOCommonTools pioneeringCategoryWithString:title];
  return self;
}
- (void)viewDidLoad {
  [super viewDidLoad];
  //    self.title = @"HSEVI检查";
  [self p_initWithSubViews];
  [self createRefresh];
  [self createBackBtn];
  [self getLocalData];
}
- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  [self getHttpDataByLocalDateWithDateType:GTO_PATROL_DATE_TYPE_AFTER];
}

- (void)getLocalData {
  ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
    NSString *sql = [NSString
        stringWithFormat:@"SELECT *  FROM %@  WHERE %@=? ORDER BY %@ DESC",
                         [GTOPatrolPlan TableName], @"category",
                         @"lastModify_time"];
    NSLog(@"%@, %@", sql, _d_patrolCategory);
    return [db executeQuery:sql, _d_patrolCategory];
  };

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

    if (!fetchedObjects || fetchedObjects.count < 1) {
      [strongSelf getHttpDataWithDate:[[NSDate date] httpParameterString]
                             DateType:GTO_PATROL_DATE_TYPE_BEFORE];

    } else {
      if (!strongSelf.m_arrAllData) {
        strongSelf.m_arrAllData = [@[] mutableCopy];
      }
      [strongSelf.m_arrAllData addObjectsFromArray:fetchedObjects];
      [strongSelf.m_tableView reloadData];
    }
  };
  ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
  [dbCtrl runFetchForClass:[GTOPatrolPlan class]
                fetchBlock:fetchBlk
         fetchResultsBlock:fetchResultsBlk];
}
- (void)getHttpDataByLocalDateWithDateType:(NSString *)dateType {
  ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
    NSString *sql = [NSString
        stringWithFormat:@"SELECT *  FROM %@  WHERE %@=? ORDER BY %@ DESC",
                         [GTOPatrolPlan TableName], @"category",
                         @"lastModify_time"];
    NSLog(@"%@", sql);
    return [db executeQuery:sql, self.d_patrolCategory];
  };
  __weak typeof(self) weakSelf = self;
  ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
    __strong __typeof(weakSelf) strongSelf = weakSelf;
    if (fetchedObjects.count < 1)
      return;
    GTOPatrolPlan *last = [fetchedObjects lastObject];
    GTOPatrolPlan *first = [fetchedObjects firstObject];
    if ([dateType isEqualToString:GTO_PATROL_DATE_TYPE_BEFORE]) { //旧数据
      [strongSelf getHttpDataWithDate:last.lastModify_time
                             DateType:GTO_PATROL_DATE_TYPE_BEFORE];
    }
    if ([dateType isEqualToString:GTO_PATROL_DATE_TYPE_AFTER]) { //最新数据
      [strongSelf getHttpDataWithDate:first.lastModify_time
                             DateType:GTO_PATROL_DATE_TYPE_AFTER];
    }
  };
  [self endRefreshing];
  ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
  [dbCtrl runFetchForClass:[GTOPatrolPlan class]
                fetchBlock:fetchBlk
         fetchResultsBlock:fetchResultsBlk];
}

/** 联网获取属数据 */
- (void)getHttpDataWithDate:(NSString *)date DateType:(NSString *)dateType {
  __weak typeof(self) weakSelf = self;
  void (^succ)(id) = ^(id data) {
    [IBTLoadingView hideHUDWithText:nil];
    __strong __typeof(weakSelf) strongSelf = weakSelf;
    [strongSelf fetchtPuchaseList:data DateType:dateType];
  };
  void (^fail)(id) = ^(id data) {
    [IBTLoadingView hideHUDWithText:nil];
    [IBTLoadingView showTips:data];
  };
  [IBTLoadingView showProgressLabel:@"正在加载..."];

  ICRHTTPController *httpCtrl =
      [ICRHTTPController sharedController]; //@"2015-10-16 21:46:03"
  [httpCtrl getMyPatrolWithCategory:_d_patrolCategory
                          startTime:date
                           dateType:dateType
                         pageNumber:0
                           pageSize:20
                            success:succ
                            failure:fail];

}
//刷新列表  从服务器中获取数据
- (void)fetchtPuchaseList:(id)data DateType:(NSString *)dateType {
  if (data) {
    NSInteger success = [data[@"success"] integerValue];
    NSString *message = data[@"message"];
    if (success == 1) {
      //            NSString *string = [data JSONString];
      NSArray *recodesArr = data[@"data"][@"records"];
      if ([dateType isEqualToString:GTO_PATROL_DATE_TYPE_BEFORE]) {
        if (recodesArr.count <= 0) {
          [self endRefreshing];
          [self.m_tableView.mj_footer endRefreshingWithNoMoreData];
          return;
        }
      }

      if (recodesArr.count <= 0) {
        [self endRefreshing];
        return;
      }
      for (int count = 0; count < recodesArr.count; count++) {
        NSDictionary *dict = recodesArr[count];
        GTOPatrolPlan *patrolPlan = [GTOPatrolPlan DBObject];
        [patrolPlan praseFromJsonDict:dict];
        int finishStores = 0;
        int totalStores = (int)patrolPlan.inspectors.count;
        for (NSDictionary *dict in patrolPlan.inspectors) {
          if ([dict[@"state"] integerValue] == 1) {
            finishStores++;
          }
        }
        if (totalStores <= 0) {
          totalStores = 0;
        }
        patrolPlan.finishedStoreNumber = finishStores;
        patrolPlan.totalStoreNumber = totalStores;
        if (patrolPlan.totalStoreNumber == 0) {
          patrolPlan.processLength = 0.0;
        } else {
          patrolPlan.processLength = finishStores * 1.0 / totalStores;
        }

        NSMutableArray *arrQuestionCategorys = [@[] mutableCopy];
        for (NSDictionary *dictQuestion in patrolPlan.questions) {
          [arrQuestionCategorys addObject:dictQuestion[@"category"]];
        }
        NSSet *setQuestionCategorys = [NSSet setWithArray:arrQuestionCategorys];
        [arrQuestionCategorys removeAllObjects];
        for (NSString *str in setQuestionCategorys) {
          [arrQuestionCategorys addObject:str];
        }
        patrolPlan.questionCategorys = arrQuestionCategorys;
        if (!self.m_arrAllData) {
          self.m_arrAllData = [@[] mutableCopy];
        }
        [self.m_arrAllData addObject:patrolPlan];

        //                [self.m_tableView reloadData];
        if (count == recodesArr.count - 1) {
          [self.m_tableView reloadData];
        }
        [patrolPlan saveToDBWithHandleData:NULL
                                  complete:^{
                                    if (count == recodesArr.count - 1) {
                                      [self endRefreshing];
                                      [self p_getLocalData];
                                    }

                                  }
                                      fail:NULL];
      }

    } else {
      [self endRefreshing];
      [IBTLoadingView showTips:message];
    }
  } else {
    [self endRefreshing];
    [IBTLoadingView showTips:@"      无记录      "];
  }
}
- (void)p_getLocalData {
  ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
    NSString *sql = [NSString
        stringWithFormat:@"SELECT *  FROM %@  WHERE %@=? ORDER BY %@ DESC",
                         [GTOPatrolPlan TableName], @"category",
                         @"lastModify_time"];
    NSLog(@"%@", sql);
    return [db executeQuery:sql, self.d_patrolCategory];
  };

  __weak typeof(self) weakSelf = self;
  ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
    __strong __typeof(weakSelf) strongSelf = weakSelf;
    if (fetchedObjects.count < 1) {

    } else {
      if (!strongSelf.m_arrAllData) {
        strongSelf.m_arrAllData = [@[] mutableCopy];
      }
      [strongSelf.m_arrAllData removeAllObjects];
      [strongSelf.m_arrAllData addObjectsFromArray:fetchedObjects];
      [strongSelf.m_tableView reloadData];
    }
  };
  ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
  [dbCtrl runFetchForClass:[GTOPatrolPlan class]
                fetchBlock:fetchBlk
         fetchResultsBlock:fetchResultsBlk];
}

- (void)createBackBtn {
  UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
  [btn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
  btn.frame = CGRectMake(0, 0, 12, 20);
  [btn addTarget:self
                action:@selector(backClicked)
      forControlEvents:UIControlEventTouchUpInside];
  UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithCustomView:btn];
  self.navigationItem.leftBarButtonItem = back;
}
- (void)backClicked {
  [self PopViewControllerAnimated:YES];
}
- (void)p_initWithSubViews {
  self.view.backgroundColor = XXFBgColor;
  self.m_tableView = [[UITableView alloc]
      initWithFrame:(CGRectMake(0, TopMargin, ScreenSize.width,
                                ScreenSize.height - 64 - TopMargin))
              style:(UITableViewStylePlain)];
  [self.m_tableView registerClass:[UITableViewCell class]
           forCellReuseIdentifier:PatrolPlanCellIdentifier];
  self.m_tableView.delegate = self;
  self.m_tableView.dataSource = self;
  [self.view addSubview:self.m_tableView];

  self.c_sureBtn =
      [[UIBarButtonItem alloc] initWithTitle:@"确定"
                                       style:UIBarButtonItemStylePlain
                                      target:self
                                      action:@selector(sureClicked)];
  self.navigationItem.rightBarButtonItem = _c_sureBtn;
  self.c_sortBtn = [IBTCustomButtom
      creatButtonWithFrame:CGRectMake(LeftMargin, 10, BtnWidth, BtnHeight)
                    target:self
                       sel:@selector(sortClicked:)
                       tag:SortTag
                     image:@"black_arrow_down_with_text"
                     title:nil
                titleColor:GXF_DETAIL_COLOR
                  isCorner:NO
                    corner:0
                   bgColor:nil];

  self.c_filterBtn = [IBTCustomButtom
      creatButtonWithFrame:CGRectMake(self.view.width - BtnWidth - LeftMargin,
                                      10, BtnWidth, BtnHeight)
                    target:self
                       sel:@selector(sortClicked:)
                       tag:BoltTag
                     image:@"black_filter_with_text"
                     title:nil
                titleColor:GXF_DETAIL_COLOR
                  isCorner:NO
                    corner:0
                   bgColor:nil];
  _c_filterBtn.titleLabel.font = FontSize(BtnSize);

  self.c_maskView = [[UIView alloc]
      initWithFrame:CGRectMake(0, TopMargin, ScreenSize.width,
                               ScreenSize.height - 64 - TopMargin)];
  self.c_maskView.backgroundColor = RGBA(0, 0, 0, 0.5);
  self.c_maskView.hidden = YES;

  [self.view addSubview:_c_maskView];
  [self.view addSubview:_c_sortBtn];
  [self.view addSubview:_c_filterBtn];
}

- (void)createRefresh {
  self.m_tableView.mj_header =
      [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (_isRefresh) {
          return;
        }
        _isRefresh = YES;
        [self getHttpDataByLocalDateWithDateType:GTO_PATROL_DATE_TYPE_AFTER];
      }];
  self.m_tableView.mj_header.lastUpdatedTimeKey = PurchaseNoticeUpdateDate;

  self.m_tableView.mj_footer =
      [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (_isLoadMore) {
          return;
        }
        _isLoadMore = YES;
        [self getHttpDataByLocalDateWithDateType:GTO_PATROL_DATE_TYPE_BEFORE];

      }];
}
#pragma mark - 结束刷新
- (void)endRefreshing {
  _isLoadMore = NO;
  _isRefresh = NO;
  [self.m_tableView.mj_header endRefreshing];
  [self.m_tableView.mj_footer endRefreshing];
}
#pragma mark - Data Update

- (void)p_fetchPatrolList {

  ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
    NSString *sql =
        [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY %@ DESC",
                                   [GTOPatrolPlan TableName],
                                   @"beginDate"]; //??f_beginDate
    return [db executeQuery:sql];
  };

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

  ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
  [dbCtrl runFetchForClass:[GTOPatrolPlan class]
                fetchBlock:fetchBlk
         fetchResultsBlock:fetchResultsBlk];
}
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return [_m_arrAllData count];
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
  return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  //    [tableView deselectRowAtIndexPath:indexPath animated:YES];

  UITableViewCell *cell =
      [tableView dequeueReusableCellWithIdentifier:PatrolPlanCellIdentifier
                                      forIndexPath:indexPath];

  [self configureCell:cell forRowAtIndexPath:indexPath];

  return cell;
}

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

  UIView *contentView = cell.contentView;

  GTOPatrolPlanCellContentView *view =
      [contentView viewWithClass:[GTOPatrolPlanCellContentView class]];

  if (!view) {
    view =
        [[GTOPatrolPlanCellContentView alloc] initWithFrame:contentView.bounds];
    // view.m_bHiddenNumLabel = m_bIsInHome;
    [view autoresizingWithStrechFullSize];
    [contentView addSubview:view];
  }
  GTOPatrolPlan *patrolPlan = _m_arrAllData[indexPath.section];
  [view updateWithPatrolPlan:patrolPlan];
}

#pragma mark - UITableView Delegate
- (CGFloat)tableView:(UITableView *)tableView
    heightForRowAtIndexPath:(NSIndexPath *)indexPath {

  return PATROL_PLAN_CELL_HEIGHT; // m_bIsInHome ? PATROL_PLAN_CELL_HEIGHT :
                                  // 109;
}
- (CGFloat)tableView:(UITableView *)tableView
    heightForHeaderInSection:(NSInteger)section {
  return section == 0 ? 1 : 10;
}
- (void)tableView:(UITableView *)tableView
    didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

  [tableView deselectRowAtIndexPath:indexPath animated:YES];

  GTOPatrolPlan *plan = _m_arrAllData[indexPath.section];

  GTOAllPatrolPlanViewController *allPatrolPlanVC =
      [[GTOAllPatrolPlanViewController alloc] initWithPatrolPlan:plan];
  [self PushViewController:allPatrolPlanVC animated:YES];
}

- (void)sortClicked:(UIButton *)btn {
  self.c_maskView.backgroundColor = RGBA(0, 0, 0, 0.5);
  _c_maskView.hidden = NO;
  if (btn.tag == SortTag) {
    if (_c_boltView) { //如果筛选的不为nil
      [self p_hiddenBoltMaskView:NO];
    }
    if (_c_currentBtn == btn) {
      [btn setImage:[UIImage imageNamed:@"black_arrow_down_with_text"]
           forState:UIControlStateNormal];
      [self p_hiddenSortMaskView:YES];
      self.c_currentBtn = nil;
    } else {
      [btn setImage:[UIImage imageNamed:@"select_arrow_up_text"]
           forState:UIControlStateNormal];
      if (!_c_sortView) {
        self.c_sortView = [[SortMaskView alloc]
                 initWithFrame:CGRectMake(0, -105, ScreenSize.width, 150)
            withOrderDirection:_d_orderDirection];
        self.c_sortView.dataArr = [[NSMutableArray alloc]
            initWithObjects:@"默认排序", @"按时间逆序",
                            @"按时间顺序", nil];
        self.c_sortView.delegate = self;
        [_c_maskView addSubview:_c_sortView];
        [UIView animateWithDuration:0.25
                         animations:^{
                           CGRect sortFrame = _c_sortView.frame;
                           sortFrame.origin.y = 0;
                           self.c_sortView.frame = sortFrame;
                         }];
      }
      self.c_currentBtn = btn;
    }
  } else if (btn.tag == BoltTag) {
    if (_c_sortView) {
      [self p_hiddenSortMaskView:NO];
    }
    if (_c_currentBtn == btn) {
      [btn setImage:[UIImage imageNamed:@"black_filter_with_text"]
           forState:UIControlStateNormal];
      [self p_hiddenBoltMaskView:YES];
      _c_currentBtn = nil;

    } else {

      [btn setImage:[UIImage imageNamed:@"selected-filter_with_text"]
           forState:UIControlStateNormal];
      if (_c_boltView == nil) {
        self.c_boltView = [[BoltMaskView alloc]
            initWithFrame:CGRectMake(0, -105, ScreenSize.width, 274)
                    state:_d_state
                    title:@""];
        self.c_boltView.backgroundColor = XXFBgColor;
        self.c_boltView.delegate = self;
        self.c_boltView.dataArr = [[NSMutableArray alloc]
            initWithObjects:@"不限", @"未提交", @"已提交", @"执行中",
                            @"已完成", @"已取消", nil];
        [self.c_maskView addSubview:_c_boltView];
        [UIView animateWithDuration:0.25
                         animations:^{
                           CGRect sortFrame = _c_boltView.frame;
                           sortFrame.origin.y = 0;
                           self.c_boltView.frame = sortFrame;
                         }];
        self.c_currentBtn = btn;
      }
    }
  }
}

- (void)p_hiddenSortMaskView:(BOOL)isHide {
  self.c_currentBtn = nil;
  [self p_checkSortBtnColor];
  if (isHide == NO) {
    [_c_sortView removeFromSuperview];
    self.c_sortView = nil;
  } else {
    [UIView animateWithDuration:0.25
        animations:^{
          CGRect sortFrame = _c_sortView.frame;
          sortFrame.origin.y = -105;
          self.c_sortView.frame = sortFrame;
          self.c_maskView.backgroundColor = RGBA(0, 0, 0, 0);
        }
        completion:^(BOOL finished) {
          [_c_sortView removeFromSuperview];
          self.c_sortView = nil;
          self.c_maskView.hidden = YES;
        }];
  }
}
- (void)p_hiddenBoltMaskView:(BOOL)isHide {
  self.c_currentBtn = nil;
  [self p_checkBoltBtnColor];
  if (isHide == NO) {
    [_c_boltView removeFromSuperview];
    self.c_boltView = nil;
  } else {
    [UIView animateWithDuration:0.25
        animations:^{
          CGRect sortFrame = _c_boltView.frame;
          sortFrame.origin.y = -105;
          self.c_boltView.frame = sortFrame;
          self.c_maskView.backgroundColor = RGBA(0, 0, 0, 0);
        }
        completion:^(BOOL finished) {
          [_c_boltView removeFromSuperview];
          self.c_boltView = nil;
          self.c_maskView.hidden = YES;
        }];
  }
}

//检测排序的颜色
- (void)p_checkSortBtnColor {
  if (self.d_orderDirection.length > 0) {
    [_c_sortBtn setImage:[UIImage imageNamed:@"select_arrow_up_text"]
                forState:UIControlStateNormal];
  } else {
    [_c_sortBtn setImage:[UIImage imageNamed:@"black_arrow_down_with_text"]
                forState:UIControlStateNormal];
  }
}

- (void)p_checkBoltBtnColor {
  if (_d_state.length >
      0) { //|| self.billNumberLike.length > 0 || self.titleLike.length > 0) {
    [_c_filterBtn setImage:[UIImage imageNamed:@"selected-filter_with_text"]
                  forState:UIControlStateNormal];
  } else {
    [_c_filterBtn setImage:[UIImage imageNamed:@"black_filter_with_text"]
                  forState:UIControlStateNormal];
  }
}

#pragma mark - sortDelegate
- (void)getSortValueSelectRow:(NSString *)state {
  if (state.length > 0) {
    CLog(@"%@", state);
    self.d_orderDirection = state;
    [self reloadDateFromCondition];
  }
}
#pragma mark - boltDelegate
- (void)getBoltValueSelectRow:(NSString *)state {
  CLog(@"%@", state);
  self.d_state = state;
  [self reloadDateFromCondition];
}
- (void)getTitleLike:(NSString *)titleLike {
  CLog(@"%@", titleLike);
  self.d_titleLike = titleLike;
  [self reloadDateFromCondition];
}
// TODO
- (void)clearBoltInformation {
  self.d_state = nil;
  self.d_orderDirection = nil;
  self.d_titleLike = nil;
  self.m_arrAllData = nil;
}
#pragma button action
- (void)sureClicked {
  if (self.d_state == nil && self.d_orderDirection == nil &&
      self.d_titleLike == nil && self.m_arrAllData == nil) {
    [self reloadDateFromCondition];
  }
  //还原数据
  if (_c_sortView) {
    [self p_hiddenSortMaskView:YES];
  }
  if (_c_boltView) {
    [self p_hiddenBoltMaskView:YES];
  }
}

//根据排序和筛选条件重新返回列表数据
- (void)reloadDateFromCondition {
  if ([self.d_state isEqualToString:@"none"]) {
    self.d_state = nil;
  }
  NSString *sql = [NSString string];
  ICRDatabaseFetchBlock fetchBlk;
  if ([self.d_orderDirection isEqualToString:@"none"]) {
    self.d_orderDirection = @"desc";
  }

  if (self.d_orderDirection && (!self.d_state && !self.d_titleLike)) { // 1
    if ([self.d_orderDirection isEqualToString:@"desc"]) {
      sql = [NSString
          stringWithFormat:@"SELECT * FROM %@ WHERE %@=?  ORDER BY  %@ DESC",
                           [GTOPatrolPlan TableName], @"category",
                           @"lastModify_time"];
    } else {
      sql = [NSString
          stringWithFormat:@"SELECT * FROM %@ WHERE %@=?  ORDER BY  %@ ASC",
                           [GTOPatrolPlan TableName], @"category",
                           @"lastModify_time"];
    }

    fetchBlk = ^FMResultSet *(FMDatabase *db) {
      return [db executeQuery:sql, _d_patrolCategory];
    };
  }

  if (self.d_orderDirection && self.d_state && (!self.d_titleLike)) { // 2
    if ([self.d_orderDirection isEqualToString:@"desc"]) {
      sql = [NSString
          stringWithFormat:
              @"SELECT * FROM %@ WHERE %@=? AND %@ =? ORDER BY  %@ DESC",
              [GTOPatrolPlan TableName], @"category", @"state",
              @"lastModify_time"];
    } else {
      sql = [NSString
          stringWithFormat:
              @"SELECT * FROM %@ WHERE %@=? AND %@ =? ORDER BY  %@ ASC",
              [GTOPatrolPlan TableName], @"category", @"state",
              @"lastModify_time"];
    }
    fetchBlk = ^FMResultSet *(FMDatabase *db) {
      return [db executeQuery:sql, _d_patrolCategory, self.d_state];
    };
  }
  if (self.d_orderDirection && (!self.d_state) && self.d_titleLike) { // 3
    if ([self.d_orderDirection isEqualToString:@"desc"]) {
      sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? AND %@ "
                                       @"like '%%%@%%' ORDER BY  %@ DESC",
                                       [GTOPatrolPlan TableName], @"category",
                                       @"name", self.d_titleLike,
                                       @"lastModify_time"];
    } else {
      sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? AND %@ "
                                       @"like '%%%@%%' ORDER BY  %@ ASC",
                                       [GTOPatrolPlan TableName], @"category",
                                       @"name", self.d_titleLike,
                                       @"lastModify_time"];
    }
    fetchBlk = ^FMResultSet *(FMDatabase *db) {
      return [db executeQuery:sql, _d_patrolCategory];
    };
  }
  if (self.d_orderDirection && self.d_state && self.d_titleLike) { // 4
    if ([self.d_orderDirection isEqualToString:@"desc"]) {
      sql = [NSString
          stringWithFormat:@"SELECT * FROM %@ WHERE %@=?  AND %@ =? AND %@ "
                           @"like '%%%@%%' ORDER BY  %@ DESC",
                           [GTOPatrolPlan TableName], @"category", @"state",
                           @"name", self.d_titleLike, @"lastModify_time"];
    } else {
      sql = [NSString
          stringWithFormat:@"SELECT * FROM %@ WHERE %@=?  AND %@ =? AND %@ "
                           @"like '%%%@%%' ORDER BY  %@ ASC",
                           [GTOPatrolPlan TableName], @"category", @"state",
                           @"name", self.d_titleLike, @"lastModify_time"];
    }
    fetchBlk = ^FMResultSet *(FMDatabase *db) {
      return [db executeQuery:sql, _d_patrolCategory, self.d_state];
    };
  }

  if (!self.d_orderDirection && self.d_state && self.d_titleLike) { // 5
    sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=?  AND %@ =? "
                                     @"AND %@ like '%%%@%%' ORDER BY  %@ DESC",
                                     [GTOPatrolPlan TableName], @"category",
                                     @"state", @"name", self.d_titleLike,
                                     @"lastModify_time"];
    fetchBlk = ^FMResultSet *(FMDatabase *db) {
      return [db executeQuery:sql, _d_patrolCategory, self.d_state];
    };
  }
  if (!self.d_orderDirection && (!self.d_state) && self.d_titleLike) { // 6
    sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? AND %@ like "
                                     @"'%%%@%%' ORDER BY  %@ DESC",
                                     [GTOPatrolPlan TableName], @"category",
                                     @"name", self.d_titleLike,
                                     @"lastModify_time"];
    fetchBlk = ^FMResultSet *(FMDatabase *db) {
      return [db executeQuery:sql, _d_patrolCategory];
    };
  }
  if (!self.d_orderDirection && self.d_state && (!self.d_titleLike)) { // 7
    sql = [NSString
        stringWithFormat:
            @"SELECT * FROM %@ WHERE %@=?  AND %@ =?  ORDER BY  %@ DESC",
            [GTOPatrolPlan TableName], @"category", @"state",
            @"lastModify_time"];
    fetchBlk = ^FMResultSet *(FMDatabase *db) {
      return [db executeQuery:sql, _d_patrolCategory, self.d_state];
    };
  }
  if (!self.d_orderDirection && !self.d_state && !self.d_titleLike) { // 8
    sql = [NSString stringWithFormat:
                        @"SELECT * FROM %@ WHERE category =? ORDER BY  %@ DESC",
                        [GTOPatrolPlan TableName], @"lastModify_time"];
    fetchBlk = ^FMResultSet *(FMDatabase *db) {
      return [db executeQuery:sql, _d_patrolCategory];
    };
  }
  __weak typeof(self) weakSelf = self;
  ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
  [dbCtrl runFetchForClass:[GTOPatrolPlan class]
                fetchBlock:fetchBlk
         fetchResultsBlock:^(NSArray *fetchedObjects) {
           __strong __typeof(weakSelf) strongSelf = weakSelf;
           if (!strongSelf.m_arrAllData) {
             strongSelf.m_arrAllData = [@[] mutableCopy];
           }
           [strongSelf.m_arrAllData removeAllObjects];
           if (fetchedObjects) {
             [strongSelf.m_arrAllData addObjectsFromArray:fetchedObjects];
           }

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

@end
