//
//  SprtPrinter.m
//  qm-hardwarekit
//
//  Created by wuzhuoxuan on 2017/7/31.
//  Copyright © 2017年 Marc Shilling. All rights reserved.
//

#import "SprtPrinter.h"


//for issc
static NSString *const kWriteCharacteristicUUID_cj = @"49535343-8841-43F4-A8D4-ECBE34729BB3";
static NSString *const kReadCharacteristicUUID_cj = @"49535343-1E4D-4BD9-BA61-23C647249616";
static NSString *const kServiceUUID_cj = @"49535343-FE7D-4AE5-8FA9-9FAFD205E455";

// Properties是特征的属性，可以看出FF01具有读的权限，FF02具有读写的权限。特征拥有的权限类别有如下几种：
static NSString *const kFlowControlCharacteristicUUID = @"ff03";
static NSString *const kWriteCharacteristicUUID = @"ff02";
static NSString *const kReadCharacteristicUUID = @"ff01";
static NSString *const kServiceUUID = @"ff00";

//CBPeripheral *activeDevice;
//CBCharacteristic *activeWriteCharacteristic;
//CBCharacteristic *activeReadCharacteristic;
//CBCharacteristic *activeFlowControlCharacteristic;
//
//int response = 1;
//int mtu = 20;
//int credit = 0;
//int cjFlag=1;
//int cmd=0;

@implementation SprtPrinter
{
    NSThread *thread;
}

RCT_EXPORT_MODULE();

// 连接蓝牙设备
RCT_REMAP_METHOD(connect,address:(NSString*)address
                 resolver:(RCTPromiseResolveBlock)resolve
                 reject:(RCTPromiseRejectBlock)reject){
    DeviceBluetooth *deviceBluet = [DeviceBluetooth sharedInstance];
    [deviceBluet connectTheDeviceWithPeripheral:@{@"identifier":address} ConnectSuccess:^(NSString *success) {
        deviceBluet.selectedPeripheral.delegate = self;
        //此时设备已经连接上了  你要做的就是找到该设备上的指定服务 调用完该方法后会调用代理CBPeripheralDelegate（现在开始调用另一个代理的方法了）的
        [deviceBluet.selectedPeripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID]]];
        [deviceBluet.selectedPeripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID_cj]]];
        NSMutableDictionary *periphDict = [NSMutableDictionary dictionary];
        [periphDict setObject:[NSString stringWithFormat:@"%@",[deviceBluet.selectedPeripheral.identifier UUIDString]] forKey:@"address"];
        [periphDict setObject:deviceBluet.selectedPeripheral.name forKey:@"name"];
        [periphDict setObject:@(1) forKey:@"bondState"];
        resolve(periphDict);
    } andConnectError:^(NSString *err) {
        NSError *error=[NSError errorWithDomain:@"打印机连接失败" code:101 userInfo:nil];
        reject(@"-1", @"打印机连接失败", error);
    }];
}

RCT_EXPORT_METHOD(printSmallTicket:(NSString *)printData){
    [self PrintClick:[self dictionaryWithJsonString:printData]];
}

RCT_EXPORT_METHOD(disconnect:(NSString *)address){
    DeviceBluetooth *deviceBluet = [DeviceBluetooth sharedInstance];
    [deviceBluet didDisconnectPeripheral:@{@"identifier":address}];
}


// 文本内容居中
RCT_EXPORT_METHOD(printAlignCenter){
    [SPRTPrint printAlignCenter];
}


// 文本内容左对齐
RCT_EXPORT_METHOD(printAlignLeft){
    [SPRTPrint printAlignLeft];
}

// 文本标题字体
RCT_EXPORT_METHOD(fontTitle){
    [SPRTPrint setAsciiWordFormat:0 bold:YES doubleHeight:YES doubleWidth:YES underline:NO];
}



// 文本内容字体
RCT_EXPORT_METHOD(fontContent){
    [SPRTPrint setAsciiWordFormat:0 bold:NO doubleHeight:NO doubleWidth:NO underline:NO];
}


// 文本内容右对齐
RCT_EXPORT_METHOD(printAlignRight){
    [SPRTPrint printAlignRight];
}

RCT_EXPORT_METHOD(printlnText:(NSString *)text){
    [SPRTPrint printTxt:[text stringByAppendingString: @"\n"]];
}

RCT_EXPORT_METHOD(printText:(NSString *)text){
    [SPRTPrint printTxt:text];
}

RCT_EXPORT_METHOD(sendPos:(NSString *)posCMD){
    NSArray *arrPos = [posCMD componentsSeparatedByString:@","];
    for (NSString *pos in arrPos) {
        [SPRTPrint sendPos:[pos stringByAppendingString:@"\r\n"] withResponse:NO];
    }
}

RCT_EXPORT_METHOD(lineWrap:(NSInteger) number) {
    for (NSInteger index = number; index >= 0 ; --index) {
        [SPRTPrint printTxt: @"\n"];
    }
}

RCT_EXPORT_METHOD(lineSplit) {
    [SPRTPrint printTxt: @"--------------------------------\n"];
}


//- (void)printPage:(id)sender {
//    if(sender == nil){
//        sender = @{@"storeName":@"店铺名称",
//                   @"tid":@"2017181831",
//                   @"payTime":@"2017/2/23 23:00:00",
//                   @"payType":@"现金",
//                   @"items":@[@{@"itemName":@"商品名称",@"itemNum":@"1",@"itemPrice":@"200",@"itemTotal":@"200"}],
//                   @"totalItem":@"20",
//                   @"discountFee":@"20000",
//                   @"totalMoney":@"200000",
//                   @"totalFee":@"100",
//                   @"oddChange":@"100",
//                   @"cardNo":@"131321414",
//                   @"balance":@"200",
//                   @"bottomText":@"谢谢光临"};
//    }
//    [SPRTPrint printAlignCenter];
//    [SPRTPrint setAsciiWordFormat:0 bold:YES doubleHeight:YES doubleWidth:YES underline:NO];
//    BOOL isPrint =  [SPRTPrint printTxt:[sender[@"storeName"] stringByAppendingString:@"\n"]];
//    if(!isPrint){
//        if(self.printError){
//            self.printError(@"打印失败");
//        }
//        thread = NULL;
//        return;
//    }
//    [SPRTPrint printAlignLeft];
//    [SPRTPrint setAsciiWordFormat:0 bold:NO doubleHeight:NO doubleWidth:NO underline:NO];
//    [SPRTPrint printTxt:[[@"单号:" stringByAppendingString:sender[@"tid"]] stringByAppendingString:@"\n"]];
//    [SPRTPrint printTxt:[[@"时间:" stringByAppendingString:sender[@"payTime"]] stringByAppendingString:@"\n"]];
//    [SPRTPrint printTxt:[[@"支付方式:" stringByAppendingString:sender[@"payType"]] stringByAppendingString:@"\n"]];
//    [SPRTPrint printTxt:[@"--------------------------------" stringByAppendingString:@"\n"]];
//    [SPRTPrint printTxt:@"商品名称          数量      金额\n"];
//    NSArray *items = sender[@"items"];
//    for (int i=0; i<items.count; i++) {
//        NSDictionary *dict = items[i];
//        NSString *name = dict[@"itemName"];
//        NSString *itemNum =[NSString stringWithFormat:@"%@",dict[@"itemNum"]]; ;
//        NSString *price = [NSString stringWithFormat:@"%@",dict[@"itemPrice"] ];
//        NSString *itemTotal = [NSString stringWithFormat:@"%@", dict[@"itemTotal"]];
//        NSArray *nameList =  [self stringList:name andLength:8];
//        itemNum = [self stringModification:itemNum andLength:6 isEnd:YES];;
//        itemTotal = [self stringModification:itemTotal andLength:12 isEnd:YES];
//
//        [SPRTPrint printAlignLeft];
//        [SPRTPrint printTxt:nameList[0]];
//        [SPRTPrint printAlignCenter];
//        [SPRTPrint printTxt:itemNum];
//        [SPRTPrint printAlignRight];
//        [SPRTPrint printTxt:[NSString stringWithFormat:@"%@\n",itemTotal]];
//        for (int j=1; j<nameList.count; j++) {
//            [SPRTPrint printTxt:nameList[j]];
//        }
//    }
//
//    [SPRTPrint printTxt:[@"--------------------------------" stringByAppendingString:@"\n"]];
//    [SPRTPrint printAlignLeft];
//    NSString *number =  [self stringModification:[NSString stringWithFormat:@"数量:%@",sender[@"totalItem"]] andLength:15 isEnd:NO];
//    [SPRTPrint printTxt:number];
//    [SPRTPrint printTxt:[NSString stringWithFormat:@"优惠:%@\n",sender[@"discountFee"]]];
//    NSString *price =  [self stringModification:[NSString stringWithFormat:@"金额:%@",sender[@"totalMoney"] ] andLength:15 isEnd:NO];
//    [SPRTPrint printTxt:price];
//    if([sender[@"payType"] isEqualToString:@"现金"]){
//        [SPRTPrint printTxt:[NSString stringWithFormat:@"实收:%@\n",sender[@"totalFee"]]];
//        [SPRTPrint printTxt:[NSString stringWithFormat:@"找零:%@\n",sender[@"oddChange"]]];
//    }else{
//        [SPRTPrint printTxt:@"\n"];
//    }
//        [SPRTPrint printAlignCenter];
//        [SPRTPrint printTxt:[@"--------------------------------" stringByAppendingString:@"\n"]];
//        [SPRTPrint printAlignLeft];
//
//        NSString* cardNo = nil;
//        if(![sender[@"cardNo"] isEqualToString:@""]){
//            cardNo = sender[@"cardNo"];
//        }else{
//            cardNo = @"--";
//        }
//        [SPRTPrint printTxt:[NSString stringWithFormat:@"会员卡号:%@\n",cardNo]];
//
//        NSString* balance = nil;
//        if(![sender[@"balance"] isEqualToString:@""]){
//            balance = sender[@"balance"];
//        }else{
//            balance = @"--";
//        }
//        [SPRTPrint printTxt:[NSString stringWithFormat:@"积分余额:%@\n",balance]];
//
//    [SPRTPrint printAlignCenter];
//    [SPRTPrint printTxt:[@"--------------------------------" stringByAppendingString:@"\n"]];
//    [SPRTPrint printTxt:[sender[@"bottomText"] stringByAppendingString:@"\n"]];
//    [SPRTPrint printTxt:@"\n"];
//    [SPRTPrint printTxt:@"\n"];
//    [SPRTPrint printTxt:@"\n"];
//    [SPRTPrint printTxt:@"\n"];
//    thread = NULL;
//    if(self.printSuccess){
//        self.printSuccess(@"打印成功");
//    }
//}




#pragma mark -- CBPeripheralDelegate
//是否写入成功的代理
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:error
{
    if (error==nil)
    {
        NSLog(@"写入成功");
        return;
    }
    NSLog(@"写入失败");
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (error==nil)
    {
        //在这个方法中我们要查找到我们需要的服务  然后调用discoverCharacteristics方法查找我们需要的特性
        //该discoverCharacteristics方法调用完后会调用代理CBPeripheralDelegate的
        for (CBService *service in peripheral.services)
        {
            if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]])
            {
                cjFlag=0;
                [peripheral discoverCharacteristics:nil forService:service];
            }
            else if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID_cj]])
            {
                cjFlag=1;
                [peripheral discoverCharacteristics:nil forService:service];
            }
        }
    }
}

//发现characteristics，由发现服务调用（上一步），获取读和写的characteristics
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    if (error==nil) {
        //在这个方法中我们要找到我们所需的服务的特性 然后调用setNotifyValue方法告知我们要监测这个服务特性的状态变化
        //当setNotifyValue方法调用后调用代理CBPeripheralDelegate的- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
        //有时读写的操作是由一个characteristic完成
        for (CBCharacteristic *characteristic in service.characteristics)
        {
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kWriteCharacteristicUUID]])
            {
                [peripheral setNotifyValue:YES forCharacteristic:characteristic];
                activeWriteCharacteristic = characteristic;
            }
            else
                if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kReadCharacteristicUUID]]){
                    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
                    activeReadCharacteristic = characteristic;
                }else if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kFlowControlCharacteristicUUID]]) {
                    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
                    activeFlowControlCharacteristic = characteristic;
                    credit = 0;
                    response = 1;
                }else if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kWriteCharacteristicUUID_cj]]) {
                    
                    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
                    activeWriteCharacteristic = characteristic;
                }else if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kReadCharacteristicUUID_cj]]) {
                    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
                    activeReadCharacteristic = characteristic;
                }
            activeDevice = peripheral;
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSLog(@"enter didUpdateNotificationStateForCharacteristic!");
    if (error==nil)
    {
        //调用下面的方法后 会调用到代理的- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
        [peripheral readValueForCharacteristic:characteristic];
    }
}

// 数据接收
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSLog(@"enter didUpdateValueForCharacteristic!");
    NSData *data = characteristic.value;
    NSLog(@"read data=%@!",data);
    if (characteristic == activeFlowControlCharacteristic) {
        NSData * data = [characteristic value];
        NSUInteger len = [data length];
        int bytesRead = 0;
        if (len > 0) {
            unsigned char * measureData = (unsigned char *) [data bytes];
            unsigned char field = * measureData;
            measureData++;
            bytesRead++;
            if(field == 2){
                unsigned char low  = * measureData;
                measureData++;
                mtu =  low + (* measureData << 8);
            }
            if(field == 1){
                if(credit < 5) {
                    credit += * measureData;
                }
            }
        }
    }
    
}

// 打印
- (void)PrintClick:(NSDictionary *)printData{
    if (thread == NULL) {
        thread = [[NSThread alloc] initWithTarget:self selector:@selector(printPage:) object:printData];
        [thread start];
    } else {
        NSLog(@"Already running");
    }
}



// End是否显示在NO前面@"111     " YES后面 @"    111"
- (NSString *)stringModification:(NSString *)str andLength:(int)index isEnd:(BOOL)End {
    int count = index - str.length;
    if(End == YES){
        // 字符串在后面
        NSMutableString *newStr = [NSMutableString stringWithFormat:@"%@",str];
        if(count>0){
            for(int i=0;i<index-newStr.length;i++){
                // 字符串 == 两个空
                [newStr insertString:@"  " atIndex:0];
            }
        }
        return newStr;
    }else{
        // 字符串在前面
        NSString *newStr = [NSString stringWithFormat:@"%@",str];
        if(count>0){
            // 如果index==15 后面拼接一个空字符
            if(index == 15){
                for(int i=0;i<count;i++){
                    // 如果是金额这边就拼接一个空
                    newStr = [newStr stringByAppendingString:@" "];
                }
            }else{
                for(int i=0;i<count;i++){
                    // 字符串 == 两个空
                    newStr = [newStr stringByAppendingString:@"  "];
                }
            }
        }
        return newStr;
    }
    
}
//超过8个 换行最多2行  最多显示16个字符 最后...
- (NSArray *)stringList:(NSString *)str andLength:(int)index {
    NSMutableArray *list = [NSMutableArray array];
    if(str.length>index){
        // 超过8个字符 换行
        NSString *strOne = [str substringToIndex:index];
        NSString *strTwo = [str substringFromIndex:index];
        if(strTwo.length>index){
            strTwo = [[strTwo substringToIndex:index-2]stringByAppendingString:@"..."] ;
        }
        strTwo = [strTwo stringByAppendingString:@"\n"];
        [list addObject:strOne];
        [list addObject:strTwo];
        return list;
    }else{
        // 字符串小于8个 在字符串后面拼接
        if(str.length<index){
            [list addObject:[self stringModification:str andLength:index isEnd:NO]];
        }else{
            [list addObject:str];
        }
        return list;
    }
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

@end
