#include <QCoreApplication>
#include <iostream>
#include <stdio.h>
#include <iconv.h>
#include <errno.h>
#include "pos_print.h"


int charset_convert(const char* charset_from, const char* charset_to
                    , const std::string& string_from, std::string& string_to)
{
    iconv_t cd = iconv_open(charset_to, charset_from);
    if (!cd)
    {
        return -1;
    }

    string_to = "";
    int ret = 0;
    size_t inbytes = string_from.size();
    char* inbuf = const_cast<char*>(string_from.c_str());
    while (inbytes > 0)
    {
        char buffer[1024] = {0};
        char *outbuf = buffer;
        size_t outbytes = sizeof(buffer) - 1;
        ret = iconv(cd, &inbuf, &inbytes, &outbuf, &outbytes);
        if (ret == 0 || errno == E2BIG)
        {
            string_to.append(buffer);
        }
        else
        {
            break;
        }
    }
    ret = iconv_close(cd);
    if (inbytes != 0 || ret != 0)
    {
        return -1;
    }
    
    return 0;
}

std::string charset_u2g(const std::string& utf8)
{
    std::string gbk;
    int i= charset_convert("UTF-8", "GB18030//IGNORE", utf8, gbk);
    std::cout<<"convert res:"<<i<<std::endl;
    return gbk;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    std::cout<<"hello world"<<std::endl;

//        setbuf(stdout, NULL);
        int fd;
        fd = open_port("/dev/ttyS1");
        set_port(fd,9600);
         
        //QByteArray str=QString("例汤").toLocal8Bit();
    	//char lading[]="³¬ÖµÃÛÖ­²æÉÕ·¹/ÍâÂô";
	
	//----中文----
	//QByteArray zStr=QString("我的abc例汤").toUtf8();
	std::string zz="上菜单";
	print(const_cast<char*>(charset_u2g(zz).data()),3);
	//----end-----

	//----latin1------
	std::string lading="1 ³¬ÖµÃÛÖ­²æÉÕ·¹/ÍâÂô";
        QByteArray str=QString(lading.data()).toLatin1();
	//----end--------

	//print(str.data(),3);
	std::string num="        台号：50";
        print(const_cast<char*>(charset_u2g(num).data()),5);
	std::string str1="人数：3   单据：123456789";
        print(const_cast<char*>(charset_u2g(str1).data()),1);
	std::string str2="日期：20-10-24 时间：17:40";
	print(const_cast<char*>(charset_u2g(str2).data()),1);
        print("--------------------------------------------",1);
        print(str.data(),3);
   
        std::string menu2="2 Ôç²ÍÌØÖÆÔÆÍÌºÓ·Û";	
        print(QString(menu2.data()).toLatin1().data(),3);
        std::string menu3="3 ÒøÌ©Ô±¹¤Ì×²ÍA1";
        print(QString(menu3.data()).toLatin1().data(),3);
        cut_paper();
        close_port();

    return 0;
}

