//
//  DwgViewController.m
//  iOdaApp
//
//  Created by Irina Bezruk on 03/11/15.
//  Copyright © 2015 ODA. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "DwgViewController.h"
#include <Gs/GsBaseVectorizer.h>
#include <RxVariantValue.h>
#include <RxDictionary.h>
#include <ColorMapping.h>
#include <AbstractViewPE.h>

#import "iOdaAppServices.h"
#import "iStrConv.h"

#import "DbRasterImageDef.h"
#import "DbBlockTableRecord.h"
#import "DbDictionary.h"
#import "DbRasterImage.h"
#include "stdafx.h"
#include "OdaCommon.h"

@interface DwgViewController ()<UIGestureRecognizerDelegate>
@property (nonatomic, strong) UITapGestureRecognizer * tap;
@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGR;

@property (nonatomic, assign) int nid;
@end

@implementation DwgViewController

@synthesize cadFileName;
@synthesize glContext;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [YJProgressHUD showProgress:@"正在加载..." inView:self.view];
    UIButton *disBtn = [UIButton z_textButton:@"取消" boldFontSize:18 normalColor:IndicatedColor];
    [disBtn addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    CGFloat y;
    if (IS_IPHONE_X) {
        y =20.f + 24.f;
    }else {
        y = 20.f;
    }
    disBtn.frame = CGRectMake(16, y, 40, 30);
    [self.view addSubview:disBtn];
    [self load];
    
}
- (void)cancelAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)load {
    NSLog(@"DwgViewController: %@", cadFileName);
    backingWidth = 0;
    backingHeight = 0;
    prevAngleRad = 0.0;
    prevScale = 1.0;
    prevPanPoint = {0.0, 0.0};
    self.scale = 1.0;
    self.enable = YES;
    self.glContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2 ];
    
    if (!self.glContext) {
        NSLog(@"Failed to create OpenGL ES 2.0 context");
    }
    //  [EAGLContext setCurrentContext:self.glContext]; // VERY important! GL silently stops working without this
    GLKView *view = (GLKView *)self.view;
    view.context = self.glContext;
    view.drawableDepthFormat = GLKViewDrawableDepthFormat24;
    [self setupGL];
    odgsInitialize();
//    [self LoadCadFile];
    [self LoadFile];
    [self addGestureRecognizer];
    //    [self addTap];
    //    [self addLongTap];
}
- (void)addGestureRecognizer {
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    pan.minimumNumberOfTouches = 1;
    [self.view addGestureRecognizer:pan];
    
    UIPinchGestureRecognizer * pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
    pinch.scale = 1.0;
    pinch.enabled = YES;
    pinch.cancelsTouchesInView = YES;
    pinch.delaysTouchesEnded = YES;
    [self.view addGestureRecognizer:pinch];
    //    UIRotationGestureRecognizer * rotaion = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotate:)];
    //    rotaion.rotation = 0;
    //    //    rotaion.enabled = YES;
    //    //    rotaion.delaysTouchesEnded = YES;
    //    //    rotaion.cancelsTouchesInView = YES;
    //    [self.view addGestureRecognizer:rotaion];
}

- (void)setupGL
{
    [EAGLContext setCurrentContext:self.glContext];
}

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    if (gsDevice.isNull())
        return;
    // Set actual screen size for the generated geometry
    [YJProgressHUD hide];
    [self resizeGsDevice:rect];
    // Draw geometry
    gsDevice->invalidate();
    gsDevice->update();
    
}


-(void)resizeGsDevice: (CGRect)rect
{
    // Get size of our current window
    if (((GLint)rect.size.width != backingWidth) ||
        ((GLint)rect.size.height != backingHeight))
    {
        backingWidth = (GLint)rect.size.width;
        backingHeight = (GLint)rect.size.height;
        // Set the screen size for the generated geometry.
        double scaleF = [[UIScreen mainScreen] scale];
        //Plus 理想像素与实际像素比为1.15
//        if (3 == scaleF) {
//            scaleF /= 1.15;
//        }
        OdGsDCRect screenRect( OdGsDCPoint(0, self.view.frame.size.height*scaleF),
                              OdGsDCPoint(self.view.frame.size.width*scaleF, 0) );
        gsDevice->onSize(screenRect);
    }
}

-(void)UninitOpenGLES
{
    if (!gsDevice.isNull())
    {
        // Release vectorizer and render buffers
        gsDevice.release();
    }
}

- (void)dealloc
{
    if ([EAGLContext currentContext] == self.glContext)
    {
        [EAGLContext setCurrentContext:nil];
    }
    
    self.glContext = nil;
    
    // Uninitialize OpenGL context
    [self UninitOpenGLES];
    // Uninitialize GS
    odgsUninitialize();
    
    ClearData();
}


- (OdGePoint3d)toWCS: (CGFloat)x andY:(CGFloat) y
{
    OdGePoint3d wcsPt((double)x, (double)y, 0.0);
    const OdGsView* pView = gsDevice->viewAt(0);
    if (pView->isPerspective())
    {
        wcsPt.z = pView->projectionMatrix()(2, 3);
    }
    wcsPt.transformBy((pView->screenMatrix() * pView->projectionMatrix()).inverse());
    wcsPt.z =0.;
    wcsPt.transformBy(OdAbstractViewPEPtr(pView)->eyeToWorld(pView));
    return wcsPt;
}

- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
    if (!self.enable) {
        return;
    }
    CGPoint translation = [recognizer translationInView:self.view];
    
    OdGsView* pView = gsDevice->viewAt(0);
    OdGeVector3d delta = [self toWCS:-translation.x andY:-translation.y] - [self toWCS:-prevPanPoint.x andY:-prevPanPoint.y];
    delta.transformBy(pView->viewingMatrix());
    pView->dolly(delta.x, delta.y, delta.z);
    
    prevPanPoint = translation;
    if ([recognizer state] == UIGestureRecognizerStateEnded)
    {
        prevPanPoint = {0.0, 0.0};
    }
}


- (void)handlePinch:(UIPinchGestureRecognizer *)recognizer
{
    if (!self.enable) {
        return;
    }
    if (!gsDevice.isNull())
    {
        OdGsView* pView = gsDevice->viewAt(0);
        CGFloat scale = 1.0 - (prevScale - recognizer.scale);
        //pView->zoom((double)(1.0 + (recognizer.scale - 1.0)/16.0));
        pView->zoom((double)(scale));
        prevScale = recognizer.scale;
        if ([recognizer state] == UIGestureRecognizerStateEnded)
        {
            prevScale = 1.0;
        }
        self.scale /= (double)scale;
        double revZoomScale = 1.0/scale;
        
        ZoomTag(pDb,  revZoomScale);
    }
}

- (bool)viewCanRotate
{
    if (pDb.isNull())
    {
        return false;
    }
    return (pDb->getTILEMODE()) ? true : false;
}


- (void)handleRotate:(UIRotationGestureRecognizer *)recognizer
{
    if (!self.enable) {
        return;
    }
    CGFloat curAngleRad = recognizer.rotation;
    
    if (!gsDevice.isNull() && [self viewCanRotate])
    {
        OdGsView* pView = gsDevice->viewAt(0);
        double angle = ((curAngleRad - prevAngleRad)/90)*180/OdaPI;
        pView->roll(angle);
        prevAngleRad = recognizer.rotation;
        if ([recognizer state] == UIGestureRecognizerStateEnded)
        {
            prevAngleRad = 0.0;
        }
    }
}


-(BOOL) LoadCadFile
{
    BOOL rtn = false;
    try
    {
        // Load file
        pDb = iOdaAppServices::getInstance()->readFile(NSString2OdString(cadFileName));
        if (pDb.isNull())
        {
            
            // load database failed
        }
        else
        {
            // Create the rendering context.
            OdGiContextForDbDatabasePtr pDwgContext = OdGiContextForDbDatabase::createObject();
            // Create the custom rendering device and set the output stream for the device.
            if (!gsDevice.isNull())
            {
                gsDevice.release();
            }
            if (gsDevice.isNull())
            {
                
                NSString* adinitPath0 = [[NSBundle mainBundle]pathForResource:@"txt" ofType:@"shx"];
                OdString adinitFile0 = iOdaAppServices::getInstance()->findFile([adinitPath0 cStringUsingEncoding:NSUTF8StringEncoding]);
                
                NSString* adinitPath1 = [[NSBundle mainBundle]pathForResource:@"hztxt" ofType:@"shx"];
                OdString adinitFile1 = iOdaAppServices::getInstance()->findFile([adinitPath1 cStringUsingEncoding:NSUTF8StringEncoding]);
                
                OdDbTextStyleTablePtr pTextStyles = pDb->getTextStyleTableId().safeOpenObject(OdDb::kForWrite);
                OdDbSymbolTableIteratorPtr itTextStyle = pTextStyles->newIterator();
                OdDbTextStyleTableRecordPtr pTextStyle;
                for (itTextStyle->start(); !itTextStyle->done(); itTextStyle->step())
                {
                    pTextStyle = itTextStyle->getRecord(OdDb::kForWrite);
                    OdString oName = pTextStyle->getName();
                    OdString oFileName = pTextStyle->fileName();
                    OdString oBigFileName = pTextStyle->bigFontFileName();
                    OdString  name = itTextStyle->getRecord()->getName();
                    //			pTextStyle = itTextStyle->getRecord(OdDb::kForWrite);
                    bool bShape = pTextStyle->isShapeFile();
                    if (!bShape){
                        pTextStyle->setFileName(adinitFile0);
                        pTextStyle->setBigFontFileName(adinitFile1);
                        //                 pTextStyle->setIsShapeFile(true);
                        bShape = pTextStyle->isShapeFile();
                    }
                }
//                ModifySteelSymbol(pDb->getModelSpaceId());
                // Load graphics device module
                OdGsModulePtr m = ::odrxDynamicLinker()->loadModule(OdWinGLES2ModuleName);
                
                // Create graphics device
                gsDevice = m->createDevice();
                // Prepare callbacks for WinOpenGL vectorizer
                // m_protoCallback.m_pDelegate = self;
                // Setup graphics device properties
                OdRxDictionaryPtr pProps = gsDevice->properties();
                if (!pProps.isNull())
                {
                    //TODO
                }
                else
                {
                    NSLog(@"\nCan't access device properties");
                }
            }
            // Set the database to be vectorized.
            pDwgContext->setDatabase(pDb);
            pDwgContext->enableGsModel(true);
            // Prepare the device to render the active layout in this database.
            gsDevice = OdDbGsManager::setupActiveLayoutViews(gsDevice, pDwgContext);
            // Setup device palette
            if (OdGsPaperLayoutHelper::cast(gsDevice).isNull())
            {
                // ModelSpace
                gsDevice->setLogicalPalette(::odcmAcadDarkPalette(), 256);
                gsDevice->setBackgroundColor(ODRGB(0, 0, 0));
                pDwgContext->setPaletteBackground(ODRGB(0, 0, 0));
            }
            else
            {
                gsDevice->setLogicalPalette(::odcmAcadLightPalette(), 256);
                gsDevice->setBackgroundColor(ODRGB(173, 174, 173));
                pDwgContext->setPaletteBackground(ODRGB(255, 255, 255));
            }
            // Setup rendering surface size
            [self resizeGsDevice:self.view.frame];
            OdAbstractViewPEPtr(gsDevice->viewAt(0))->zoomExtents(gsDevice->viewAt(0));
            
            // Layer must be set for WinGLES2 device
            gsDevice->properties()->putAt(OD_T("EAGLContext"), OdRxVariantValue((OdIntPtr)self.glContext));
        }
    }
    catch (int)
    {
        NSLog(@"\nNormal termination");
    }
    catch (const OdError& e)
    {
        printf("\nException Caught: %ls\n", e.description().c_str());
    }
    catch (...)
    {
        NSLog(@"\nUnknown Exception Caught\n");
    }
    return rtn;
}

-(BOOL) LoadFile
{
    BOOL rtn = false;
    try
    {
        // Load file
        NSString* tmp = [cadFileName pathExtension];
        tmp = [ tmp lowercaseString];
        tmp = [ tmp lowercaseString];
        
        if ([tmp isEqualToString:@"jpg"] ||
            [tmp isEqualToString:@"png"] ||
            [tmp isEqualToString:@"bmp"] ||
            [tmp isEqualToString:@"jpeg"]){
            
            pDb = iOdaAppServices::getInstance()->createDatabase();
            OdDbBlockTableRecordPtr pRecord = pDb->getActiveLayoutBTRId().safeOpenObject(OdDb::kForWrite) ;
            OdDbObjectId imageDictId = OdDbRasterImageDef::createImageDictionary(pRecord->database());
            OdDbDictionaryPtr pImageDict = imageDictId.safeOpenObject(OdDb::kForWrite);
            // Create image definition
            OdDbObjectId defId;
            OdDbRasterImageDefPtr pDef = OdDbRasterImageDef::createObject();
            pDef->setSourceFileName(NSString2OdString(cadFileName));
            defId = pImageDict->setAt(OD_T("importedRasterImage"), pDef);
            // Try to load raster image to found correct dimensions inside TD
            OdDbRasterImageDefPtr pDefLoad = OdDbRasterImageDef::cast(defId.openObject(OdDb::kForWrite));
            pDefLoad->load(false);
            // Create and attach raster image reference
            OdDbRasterImagePtr pRef = OdDbRasterImage::createObject();
            pRef->setDatabaseDefaults(pDb);
            pRef->setImageDefId(defId);
            pRef->setOrientation(OdGePoint3d::kOrigin, OdGeVector3d::kXAxis, OdGeVector3d::kYAxis);
            pRef->setDisplayOpt(OdDbRasterImage::kShow, true);
            pRecord->appendOdDbEntity(pRef);
            [self loadTheFile];
            
        }else{
//                        UIView *view = [[UIView alloc]init];
//                        view.backgroundColor = [UIColor blackColor];
//                        [self.view addSubview:view];
//                        [view mas_makeConstraints:^(MASConstraintMaker *make) {
//                            make.edges.mas_equalTo(0);
//                        }];
            
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                pDb = iOdaAppServices::getInstance()->readFile(NSString2OdString(self.cadFileName));
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self loadTheFile];
                });
            });
            
        }
        
        
        //        if (pDb.isNull()){
        //            // load database failed
        //        }else{
        //
        //        }
    }
    catch (int)
    {
        NSLog(@"\nNormal termination");
    }
    catch (const OdError& e)
    {
        printf("\nException Caught: %ls\n", e.description().c_str());
    }
    catch (...)
    {
        NSLog(@"\nUnknown Exception Caught\n");
    }
    return rtn;
}
void ModifySteelSymbol(const OdDbObjectId &objectId)
{
    OdDbBlockTableRecordPtr pBlockTableRecord = objectId.safeOpenObject(OdDb::kForWrite);
    
    OdDbObjectIteratorPtr pEntIter = pBlockTableRecord->newIterator();
    /********************************************************************/
    for (; !pEntIter->done(); pEntIter->step())
    {
        OdDbObjectPtr pEntity = pEntIter->objectId().safeOpenObject(OdDb::kForWrite);
        
        if (pEntity->isKindOf(OdDbText::desc())){
            OdDbTextPtr pOld = OdDbText::cast(pEntity);
            OdString text = pOld->textString();
            
            bool bFind = false;
            
            for(int i=0;i<4;i++){
                OdChar cE530 = 0xE530+i;
                OdString sE530(" ");
                OdString sE530New("%%130");
                if(i==1)
                    sE530New = "%%131";
                else if(i==2)
                    sE530New = "%%132";
                else if(i==3)
                    sE530New = "%%133";
                
                sE530.setAt(0, cE530);
                if(text.find(cE530)>-1){
                    text.replace(sE530, sE530New);
                    bFind = true;
                }
            }
            
            if(bFind)
                pOld->setTextString(text);
        }
        else if (pEntity->isKindOf(OdDbMText::desc())){
            OdDbMTextPtr pOld = OdDbMText::cast(pEntity);
            OdString text = pOld->contents();
            
            bool bFind = false;
            
            for(int i=0;i<4;i++){
                OdChar cE530 = 0xE530+i;
                OdString sE530(" ");
                OdString sE530New("%%130");
                if(i==1)
                    sE530New = "%%131";
                else if(i==2)
                    sE530New = "%%132";
                else if(i==3)
                    sE530New = "%%133";
                
                sE530.setAt(0, cE530);
                if(text.find(cE530)>-1){
                    text.replace(sE530, sE530New);
                    bFind = true;
                }
            }
            
            if(bFind)
                pOld->setContents(text);
        }
        
    }
}
- (void)loadTheFile{
    // Create the rendering context.
    OdGiContextForDbDatabasePtr pDwgContext = OdGiContextForDbDatabase::createObject();
    // Create the custom rendering device and set the output stream for the device.
    if (!gsDevice.isNull()){
        gsDevice.release();
    }
    if (gsDevice.isNull()){
        
        
        NSString* adinitPath0 = [[NSBundle mainBundle]pathForResource:@"txt" ofType:@"shx"];
        OdString adinitFile0 = iOdaAppServices::getInstance()->findFile([adinitPath0 cStringUsingEncoding:NSUTF8StringEncoding]);
        
        NSString* adinitPath1 = [[NSBundle mainBundle]pathForResource:@"hztxt" ofType:@"shx"];
        OdString adinitFile1 = iOdaAppServices::getInstance()->findFile([adinitPath1 cStringUsingEncoding:NSUTF8StringEncoding]);
        
        OdDbTextStyleTablePtr pTextStyles = pDb->getTextStyleTableId().safeOpenObject(OdDb::kForWrite);
        OdDbSymbolTableIteratorPtr itTextStyle = pTextStyles->newIterator();
        OdDbTextStyleTableRecordPtr pTextStyle;
        for (itTextStyle->start(); !itTextStyle->done(); itTextStyle->step())
        {
            pTextStyle = itTextStyle->getRecord(OdDb::kForWrite);
            OdString oName = pTextStyle->getName();
            OdString oFileName = pTextStyle->fileName();
            OdString oBigFileName = pTextStyle->bigFontFileName();
            OdString  name = itTextStyle->getRecord()->getName();
            //			pTextStyle = itTextStyle->getRecord(OdDb::kForWrite);
            bool bShape = pTextStyle->isShapeFile();
            if (!bShape){
                pTextStyle->setFileName(adinitFile0);
                pTextStyle->setBigFontFileName(adinitFile1);
                //                 pTextStyle->setIsShapeFile(true);
                bShape = pTextStyle->isShapeFile();
            }
        }
//        ModifySteelSymbol(pDb->getModelSpaceId());
        // Load graphics device module
        OdGsModulePtr m = ::odrxDynamicLinker()->loadModule(OdWinGLES2ModuleName);
        
        // Create graphics device
        gsDevice = m->createDevice();
        // Prepare callbacks for WinOpenGL vectorizer
        // m_protoCallback.m_pDelegate = self;
        // Setup graphics device properties
        OdRxDictionaryPtr pProps = gsDevice->properties();
        if (!pProps.isNull())
        {
            //TODO
        }
        else
        {
            NSLog(@"\nCan't access device properties");
        }
    }
    // Set the database to be vectorized.
    pDwgContext->setDatabase(pDb);
    pDwgContext->enableGsModel(true);
    // Prepare the device to render the active layout in this database.
    gsDevice = OdDbGsManager::setupActiveLayoutViews(gsDevice, pDwgContext);
    // Setup device palette
    if (OdGsPaperLayoutHelper::cast(gsDevice).isNull())
    {
        // ModelSpace
        gsDevice->setLogicalPalette(::odcmAcadDarkPalette(), 256);
        gsDevice->setBackgroundColor(ODRGB(0, 0, 0));
        pDwgContext->setPaletteBackground(ODRGB(0, 0, 0));
    }
    else
    {
        gsDevice->setLogicalPalette(::odcmAcadLightPalette(), 256);
        gsDevice->setBackgroundColor(ODRGB(173, 174, 173));
        pDwgContext->setPaletteBackground(ODRGB(255, 255, 255));
    }
    // Setup rendering surface size
    [self resizeGsDevice:self.view.frame];
    OdAbstractViewPEPtr(gsDevice->viewAt(0))->zoomExtents(gsDevice->viewAt(0));
    // Layer must be set for WinGLES2 device
    gsDevice->properties()->putAt(OD_T("EAGLContext"), OdRxVariantValue((OdIntPtr)self.glContext));
}
/** 单击 */
- (void)handleTap:(UITapGestureRecognizer *)recognizer {
    if (!self.enable) {
        return;
    }
    //点击点位置
    CGPoint point = [recognizer locationInView:self.view];
    
    
    [self addShape:point text:@"测试" type:ShapeTypePass];
    
}

- (int)addShape:(CGPoint)point text:(NSString *)text type:(ShapeType)type {
    float out1[3];
    float out2[3];
    OdGsViewPtr gsViewPtr = gsDevice->viewAt(0);
    //ios视窗有个缩放比例
    double scaleF = [[UIScreen mainScreen] scale];
    ////Plus 理想像素与实际像素比为1.15
    if (3 == scaleF) {
        scaleF /= 1.15;
    }
    ScreenToWorld(gsViewPtr, 0, 0, out1);
    ScreenToWorld(gsViewPtr, 100, 0, out2);
    float size = fabs(out2[0]- out1[0]);
    point.x *= scaleF;
    point.y *= scaleF;
    size *= scaleF;
    
    //屏幕坐标要转换为世界坐标
    ScreenToWorld(gsViewPtr, point.x, point.y, out1);
    
    NSFileManager * fm = [NSFileManager defaultManager];
    NSString* caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSString* fullFilePath = nil;
    
    
    fullFilePath = [NSString stringWithFormat:@"%@/marker/%@", caches, [self nameWithType:type]];
    
    BOOL exsist = [fm fileExistsAtPath:fullFilePath];
    if (!exsist) {
        NSLog(@"addShpae:图片不存在");
        return 0;
    }
    
    OdString filepath = iOdaAppServices::getInstance()->findFile([fullFilePath cStringUsingEncoding:NSUTF8StringEncoding]);
    
    NSString* txtPath = [[NSBundle mainBundle]pathForResource:@"txt" ofType:@"shx"];
    OdString oTxtPath = iOdaAppServices::getInstance()->findFile([txtPath cStringUsingEncoding:NSUTF8StringEncoding]);
    
    NSString* hzTxtPath = [[NSBundle mainBundle]pathForResource:@"hztxt" ofType:@"shx"];
    OdString oHzTxtPath = iOdaAppServices::getInstance()->findFile([hzTxtPath cStringUsingEncoding:NSUTF8StringEncoding]);
    if (text ==nil) {
        text = @"";
    }
    OdString tex = NSString2OdString(text);
    
    //    OdString tex;
    //    if (text.length) {
    //        tex = NSString2OdString(text);
    //    } else {
    //        tex = "";
    //    }
    
    //    int i = PickShapeByCursor(gsDevice->viewAt(0), pDb, point.x, point.y);
    //    if (i) {
    //        DeleteShape(pDb, i);
    //    }
    int nid = AddShape(pDb, oTxtPath, oHzTxtPath, out1[0], out1[1], size, filepath, tex, true);
    return nid;
}

- (int)alter:(int)currentID point:(CGPoint)point text:(NSString *)text type:(ShapeType)type {
    if (currentID) {
        DeleteShape(pDb, currentID);
    }
    return  [self addShape:point text:text type:type];
}

- (void)deleteShape:(int)currentId {
    if (currentId) {
        DeleteShape(pDb, currentId);
    }
}

- (NSString *)nameWithType:(ShapeType)type {
    NSString * str = nil;
    //    typedef NS_ENUM(NSInteger, ShapeType) {
    //        ShapeTypePass = 0,                  //符合背景图，无语音，无照片，无文字
    //        ShapeTypePassOk,                    //有文字：符合
    //        ShapeTypePassPhoto,                 //有照片
    //        ShapeTypePassPhotoOk,               //有照片，有文字：符合
    //        ShapeTypePassSound,                 //有语音，有文字：符合
    //        ShapeTypePassPhotoSoundOk,          //有语音，有照片，有文字：符合
    //        ShapeTypeUnPass,                    //不符合背景图，无语音，无照片，无文字
    //        ShapeTypeUnPassOk,                  //有文字:不符合
    //        ShapeTypeUnPassPhoto,               //有照片
    //        ShapeTypeUnPassPhotoOk,             //有照片，有文字：不符合
    //        ShapeTypeUnPassSound,               //有语音，有文字：不符合
    //        ShapeTypeUnPassPhotoSoundOk,        //有语音，有照片
    //    };
    
    NSArray * imageNames = @[@"maker_pass",@"maker_pass_ok",@"maker_pass_p",@"maker_pass_pp",@"maker_pass_a",@"maker_pass_pa",@"maker_unpass",@"maker_unpass_ok",@"maker_unpass_p",@"maker_unpass_pp",@"maker_unpass_a",@"maker_unpass_pa"];
    str = [NSString stringWithFormat:@"%@.png",imageNames[type]];
    //    str = @"maker_pass.png";
    return str;
}

- (void)zoomExtents {
    double revZoomScale = 1.0 / self.scale;
    
    ZoomTag(pDb, revZoomScale);
    
    OdGsViewPtr pView = gsDevice->viewAt(0);
    OdAbstractViewPEPtr(pView)->zoomExtents(pView);
    self.scale = 1.0;
}

- (int)picke:(CGPoint)point {
    double scaleF = [[UIScreen mainScreen] scale];
    if (3 == scaleF) {
        scaleF /= 1.15;
    }
    point.x *= scaleF;
    point.y *= scaleF;
    
    return PickShapeByCursor(gsDevice->viewAt(0), pDb, point.x, point.y);
}

- (void)addLongTap{
    self.longPressGR=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
    
    //设置手势需要的最小时间间隔
    self.longPressGR.minimumPressDuration=1;
    
    //绑定手势到视图上
    [self.view addGestureRecognizer:self.longPressGR];
}
- (void)removeLongTap{
    [self.view removeGestureRecognizer:self.longPressGR];
    self.longPressGR = nil;
}
-(void)longPress:(UILongPressGestureRecognizer *)gr{
    self.point=[gr locationInView:self.view];
    int nid = [self picke:self.point];
    if (self.isDelete == YES || nid == 0) {
        return;
    }

    self.isDelete = YES;
    int currentId = [self picke:self.point];
    [self deleteShape:currentId];
    self.isDelete = NO;
    
}

- (void)addTap {
    [self.view addGestureRecognizer:self.tap];
}
- (void)removeTap {
    [self.view removeGestureRecognizer:self.tap];
    self.tap = nil;
}
- (UITapGestureRecognizer *)tap {
    if (!_tap) {
        _tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
        _tap.numberOfTapsRequired = 1;
        _tap.numberOfTouchesRequired = 1;
        
    }
    return _tap;
}
#pragma mark-uiGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

@end

