using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SyncSDK_Demo
{

    public partial class Form1 : Form
    {

        private string ini_ConfigFilePath = ""; 
        public Form1()
        {
            InitializeComponent();
            loadConfig();
        }

        

        const string LibraryName = "SyncSDK.dll"; // 动态链接库名称 // Dynamic link library name

        // 操作类型定义 // Operation type definitions
        // 下载 // Download
        const int Sync_Action_DownLoad = 0x0;
        // 上传 // Upload
        const int Sync_Action_UpLoad = 0x1;
        // 删除 // Delete
        const int Sync_Action_Delete = 0x2;

        // 协议类型定义 // Protocol type definitions
        const int SDK_ProtocolType_None = 0; // 无协议 // No protocol
        const int SDK_ProtocolType_Sttp = 1; // STTP协议 // STTP protocol

        // 数据类型定义 // Data type definitions
        // 无 // None
        const int Sync_DataType_nil = 0xFFFF;
        // 单品 // Single item
        const int Sync_DataType_PLU = 0x0000;
        // 部门 // Department
        const int Sync_DataType_Department = 0x0001;
        // 单位 // Unit
        const int Sync_DataType_Unit = 0x0002;
        // 热键 // Hotkey
        const int Sync_DataType_Hotkey = 0x0003;
        // 自定义条码 // Custom barcode
        const int Sync_DataType_CustomBarcode = 0x0004;
        // 信息1 // Information 1
        const int Sync_DataType_Note1 = 0x0005;
        // 信息2 // Information 2
        const int Sync_DataType_Note2 = 0x0006;
        // 信息3 // Information 3
        const int Sync_DataType_Note3 = 0x0007;
        // 信息4 // Information 4
        const int Sync_DataType_Note4 = 0x0008;
        // 头信息 // Header information
        const int Sync_DataType_HeaderInfo = 0x0009;
        // 尾信息 // Footer information
        const int Sync_DataType_FooterInfo = 0x000A;
        // 广告词 // Advertisement
        const int Sync_DataType_Advertisement = 0x000B;
        // 系统参数 // System parameters
        const int Sync_DataType_SystemOptions = 0x000C;
        // 时间 // Time
        const int Sync_DataType_Time = 0x000D;

        // 字库 // Font library
        const int Sync_DataType_Font = 0x1000;
        // 下位机主程序 // Main program of the lower-level machine
        const int Sync_DataType_Firmware = 0x1001;
        // AD模块 // AD module
        const int Sync_DataType_ADModule = 0x1002;
        // 打印模块 // Printer module
        const int Sync_DataType_PrinterModule = 0x1003;

        // 标签元件 // Label component
        const int Sync_DataType_Label = 0x2000;
        // 标签背纹 // Label background
        const int Sync_DataType_LabelBackGround = 0x2001;
        // 标签文件 // Label file
        const int Sync_DataType_LabelFile = 0x2002;

        // 下载压缩文件 // Download compressed file
        const int Sync_DataType_ZipFile = 0x3000;

        // 错误信息 // Error messages
        // 执行success // Execution successful
        const int SDK_Err_Success = 0x0;
        // 进度事件 // Progress event
        const int SDK_Err_Progress = 0x1;
        // 手动停止 // Manual stop
        const int SDK_Err_Terminate = 0x2;

        // 不支持的协议类型 // Unsupported protocol type
        const int SDK_Err_ProtocolTypeNotSupport = 0x100; //256
                                                          // 不支持的数据类型 // Unsupported data type
        const int SDK_Err_DataTypeNotSupport = 0x101;
        // 无法打开输入文件 // Unable to open input file
        const int SDK_Err_CannotOpenInputFile = 0x102;
        // 字段数与内容数不匹配 // Number of fields does not match content
        const int SDK_Err_ImportDataFailed = 0x103;
        // 通讯数据异常 // Communication data error
        const int SDK_Err_CommDataFailed = 0x104;
        // 解析数据异常 // Data parsing error
        const int SDK_Err_ParseDataFailed = 0x105;
        // 无法创建输出文件 // Unable to create output file
        const int SDK_Err_CannotCreateOutputFile = 0x106;
        // 通信Param值错误超过次数 // Communication Param value error exceeds times
        const int SDK_Err_ParamError = 0x107;
        // 无法连接 // Unable to connect
        const int SDK_Err_CannotConnect = 0x108;

        // 没有此命令 // Command does not exist
        const int SDK_Err_NotHaveThisCommand = 0x109;
        // 数据超长 // Data too long
        const int SDK_Err_DataOutOfRange = 0x10A;
        // 写入失败 // Write failure
        const int SDK_Err_WriteError = 0x10B;
        // 剩余空间不足 // Insufficient remaining space
        const int SDK_Err_DiskNotEnough = 0x10C;
        // 读取失败 // Read failure
        const int SDK_Err_ReadError = 0x10D;
        // 包号错误 // Package number error
        const int SDK_Err_PackageNoError = 0x10E;
        // 命令错误 // Command error
        const int SDK_Err_CommandError = 0x10F;
        // 数据错误 // Data error
        const int SDK_Err_DataError = 0x110;
        // 缺纸 // Out of paper
        const int SDK_Err_MissPaper = 0x111;
        // MD5校验失败 // MD5 check failed
        const int SDK_Err_MD5CheckError = 0x112;

        // 错误应答包数据长度不是1错误 // Error response package data length is not 1
        const int SDK_Err_ErrorPackageLenError = 0x113;
        // 应答包数据长度不对 // Response package data length incorrect
        const int SDK_Err_PackageLenError = 0x114;
        // 数据错误, 且不是错误命令 // Data error, and not an error command
        const int SDK_Err_DataErrNotErrCode = 0x115;

        // 下位机没有此号标签 // Lower-level machine has no such label number
        const int SDK_Err_HaveNoThisLabelNo = 0x116;
        // 下载程序时，MD5校验超时 // MD5 check timeout during program download
        const int SDK_Err_MD5WaitTimeOut = 0x117;
        // 没有收到机器的回应包 // No response package received from the machine
        const int SDK_Err_DeviceNoRespond = 0x118;
        // 文件大小不正确 // File size incorrect
        const int SDK_Err_FileSizeError = 0x119;

        // 键盘类型不支持 // Keyboard type not supported
        const int SDK_Err_HotkeyNotSupport = 0x120;
        // 下载文件格式错误 // Download file format error
        const int SDK_Err_FileFormatError = 0x121;
        // 文件太小 // File too small
        const int SDK_Err_FileTooSmaill = 0x122;
        // 文件太大 // File too large
        const int SDK_Err_FileTooLarge = 0x123;
        // 文件名不正确 // File name incorrect
        const int SDK_Err_FileNameErr = 0x124;

        // 没有此错误命令 // No such error command
        const int SDK_Err_NoThisErrorCode = 0x1FF;

        // 格式 // Format
        // 时间格式 // Date time format
        const string SDK_DateTimeFormat = "YYYY-MM-DD HH:mm:SS";

        // 任务失败 // Task failed
        // const int SDK_Task_Failed = THandle(-1);
        [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
        public struct TASSDKDeviceInfo
        {
            public UInt32 Addr; // 设备IP // Device IP
            public UInt32 Port; // 端口 // Port
            public UInt32 ProtocolType; // 协议类型 // Protocol type
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
            public Byte[] DeviceNo; // 设备号 // Device number
            public UInt32 Version; // 下位机软件版本 // Lower-level machine software version
            public Byte LangID; // 下位机语言类别 // Lower-level machine language category
            public Byte KeyID; // 键盘类别 // Keyboard category
            public UInt16 PLUStorage; // PLU可存储数量 // PLU storage capacity
            public UInt16 Note1Storage; // Note1可存储数量 // Note1 storage capacity
            public UInt16 Note2Storage; // Note2可存储数量 // Note2 storage capacity
            public UInt16 Note3Storage; // Note3可存储数量 // Note3 storage capacity
            public UInt16 Note4Storage; // Note4可存储数量 // Note4 storage capacity
            public Byte BoardType; // 主板类型 // Motherboard type
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 7)]
            public Byte[] PrintEnableDate; // 日期格式 YYYYMMDDhhmmss // Date format YYYYMMDDhhmmss
            public Double PrinterKm; // 打印公里数 // Printer mileage
            public UInt32 PrinterPaperCount; // 打印纸张数 // Number of printer paper
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 192)]
            public Byte[] Reserve; // 保留字段 // Reserved field
        }
        [UnmanagedFunctionPointerAttribute(CallingConvention.StdCall)]
        public delegate void TASSDKOnProgressEvent(uint nErrorCode, uint Index, uint Total, IntPtr lpUserData); // 进度事件委托 // Progress event delegate

        // 初始化动态库 // Initialize dynamic library
        [DllImport(LibraryName)]
        static public extern Boolean SDK_Initialize(Pointer Adjuct = null);
        // 释放动态库 // Finalize dynamic library
        [DllImport(LibraryName)]
        static public extern void SDK_Finalize();
        // 获取设备信息 // Get device information
        [DllImport(LibraryName, CharSet = CharSet.Ansi)]
        static public extern Boolean SDK_GetDevicesInfo(UInt32 Addr, ref TASSDKDeviceInfo DeviceInfo);
        // 执行任务A (ANSI) // Execute task A (ANSI)
        [DllImport(LibraryName)]
        static public extern IntPtr SDK_ExecTaskA(UInt32 Addr, UInt32 ProcType, UInt32 DataType,
          string FileName, TASSDKOnProgressEvent OnProgress, Pointer lpUserData);

        // 执行任务W (Unicode) // Execute task W (Unicode)
        [DllImport(LibraryName)]
        static public extern IntPtr SDK_ExecTaskW(UInt32 Addr, UInt32 ProcType, UInt32 DataType,
          string FileName, TASSDKOnProgressEvent OnProgress, Pointer lpUserData);
        // 执行任务 // Execute task
        [DllImport(LibraryName, CallingConvention = CallingConvention.StdCall)]
        static public extern IntPtr SDK_ExecTask(UInt32 Addr, UInt32 ProcType, UInt32 DataType,
          string FileName, TASSDKOnProgressEvent OnProgress, Pointer lpUserData);
        // 等待任务完成 // Wait for task completion
        [DllImport(LibraryName)]
        static public extern void SDK_WaitForTask(IntPtr TaskHandle);
        // 停止任务 // Stop task
        [DllImport(LibraryName)]
        static public extern void SDK_StopTask(IntPtr TaskHandle);

        // 获取单个PLU信息A (ANSI) // Get single PLU information A (ANSI)
        [DllImport(LibraryName)]
        static public extern int SDK_GetOnePLUA(UInt32 Addr, UInt32 LFCode, string FileName);
        // 获取单个PLU信息 // Get single PLU information
        [DllImport(LibraryName)]
        static public extern int SDK_GetOnePLU(UInt32 Addr, UInt32 LFCode, string FileName);

        // 获取一组PLU信息A (ANSI) // Get a group of PLU information A (ANSI)
        [DllImport(LibraryName)]
        static public extern int SDK_GetGroupPLUA(UInt32 Addr, string infilename, string outfilename);
        // 获取一组PLU信息 // Get a group of PLU information
        [DllImport(LibraryName)]
        static public extern int SDK_GetGroupPLU(UInt32 Addr, string infilename, string outfilename);
        

        private void BtInitiallize_Click(object sender, EventArgs e)
        {
            SDK_Initialize(); // 初始化SDK // Initialize SDK
        }
        public uint MakeHostToDWord(string sHost)
        {
            int i;
            string[] Segment;
            uint result;
            result = 0;

            Segment = sHost.Split('.');
            if (Segment.Length != 4)
                return result;
            for (i = 0; i < (Segment.Length); i++)
            {
                if ((Convert.ToUInt32(Segment[i]) >= 0) && (Convert.ToUInt32(Segment[i]) <= 255))
                {
                    result = result + Convert.ToUInt32(Convert.ToUInt32(Segment[i]) << ((3 - i) * 8));
                }
                else
                    return result;
            }
            return result;
        }

        UInt32 DownLoadState = 0; // 如果用 Waitfor 加这个参数查看下载情况 // Add this parameter to check the download status when using WaitFor

        public void OnProgressEvent(UInt32 nErrorCode, UInt32 Index, UInt32 Total, IntPtr lpUserData)
        {
            const string sInfoProgress = "Progress: {0}/{1}"; // 进度提示 // Progress prompt
            const string sInfoComplete = "Complete, Total: {0}"; // 完成提示 // Completion prompt
            const string sInfoStop = "Proc Stop!"; // 进程停止提示 // Process stop prompt
            const string sInfoFailed = "Proc Failed!"; // 进程失败提示 // Process failure prompt

            DownLoadState = nErrorCode; // 更新下载状态 // Update download state

            switch (nErrorCode)
            {
                case SDK_Err_Success:
                    {
                        MessageBox.Show(string.Format(sInfoComplete, Total)); // 显示完成消息 // Show completion message
                        break;
                    }
                case SDK_Err_Progress:
                    {
                        pbProgress.Value = (int)Index; // 更新进度条位置 // Update progress bar position
                        pbProgress.Maximum = (int)Total; // 设置进度条最大值 // Set progress bar maximum value
                                                         //  setPrigressBar setPrigressBar1 = new setPrigressBar(Index, Total);

                        //MessageBox.Show(string.Format(sInfoProgress, Index, Total)); // 显示进度 // Show progress
                        break;
                    }
                case SDK_Err_Terminate:
                    {
                        MessageBox.Show(sInfoStop); // 显示停止消息 // Show stop message
                        break;
                    }
                case SDK_Err_CannotOpenInputFile:
                    {
                        MessageBox.Show("can not open input file"); // 显示无法打开输入文件的错误消息 // Show error message for unable to open input file
                        break;
                    }
                case SDK_Err_CannotConnect:
                    {
                        MessageBox.Show("can not connect"); // 显示无法连接的错误消息 // Show error message for unable to connect
                        break;
                    }
                default:
                    MessageBox.Show(sInfoFailed); // 显示未知错误消息 // Show unknown error message
                    break;
            }
        }

        public void OnProgressEvent_WaitFor(UInt32 nErrorCode, UInt32 Index, UInt32 Total, IntPtr lpUserData)
        {
            const string sInfoProgress = "Progress: {0}/{1}"; // 进度提示 // Progress prompt
            const string sInfoComplete = "Complete, Total: {0}"; // 完成提示 // Completion prompt
            const string sInfoStop = "Proc Stop!"; // 进程停止提示 // Process stop prompt
            const string sInfoFailed = "Proc Failed!"; // 进程失败提示 // Process failure prompt

            DownLoadState = nErrorCode; // 更新下载状态 // Update download state

            switch (nErrorCode)
            {
                case SDK_Err_Success:
                    {
                        MessageBox.Show(string.Format(sInfoComplete, Total)); // 显示完成消息 // Show completion message
                        break;
                    }
                case SDK_Err_Progress:
                    {
                        // 使用waitfor要把进度条的进度去掉
                        // pbProgress.Value = (int)Index;
                        // pbProgress.Maximum = (int)Total;
                        //  setPrigressBar setPrigressBar1 = new setPrigressBar(Index, Total);

                        //MessageBox.Show(string.Format(sInfoProgress, Index, Total)); // 显示进度 // Show progress
                        break;
                    }
                case SDK_Err_Terminate:
                    {
                        MessageBox.Show(sInfoStop); // 显示停止消息 // Show stop message
                        break;
                    }
                case SDK_Err_CannotOpenInputFile:
                    {
                        MessageBox.Show("can not open input file"); // 显示无法打开输入文件的错误消息 // Show error message for unable to open input file
                        break;
                    }
                case SDK_Err_CannotConnect:
                    {
                        MessageBox.Show("can not connect"); // 显示无法连接的错误消息 // Show error message for unable to connect
                        break;
                    }
                default:
                    MessageBox.Show(sInfoFailed); // 显示未知错误消息 // Show unknown error message
                    break;
            }
        }

        public String getCurrentFileDir()
        {
            string Paths;

            Paths = Environment.CurrentDirectory; // 获取当前目录 // Get current directory
            return Paths;
        }

        public string getFilePathCase(UInt32 ADataType)
        {
            string Path;
            Path = getCurrentFileDir(); // 获取当前目录路径 // Get current directory path
            switch (ADataType)
            {
                case Sync_DataType_PLU: // 单品资料 // Single item data
                    Path = Path + "\\PLU.txt";
                    break;
                case Sync_DataType_Department: // 部门 // Department
                    Path = Path + "\\Department.txt";
                    break;
                case Sync_DataType_Unit: // 单位 // Unit
                    Path = Path + "\\Unit.txt";
                    break;
                case Sync_DataType_Hotkey: // 热键 // Hotkey
                    Path = Path + "\\Hotkey.txt";
                    break;
                case Sync_DataType_CustomBarcode: // 自定义条码 // Custom barcode
                    Path = Path + "\\CustomBarcode.txt";
                    break;
                case Sync_DataType_Note1: // 信息1 // Information 1
                    Path = Path + "\\Note1.txt";
                    break;
                case Sync_DataType_Note2: // 信息2 // Information 2
                    Path = Path + "\\Note2.txt";
                    break;
                case Sync_DataType_Note3: // 信息3 // Information 3
                    Path = Path + "\\Note3.txt";
                    break;
                case Sync_DataType_Note4: // 信息4 // Information 4
                    Path = Path + "\\Note4.txt";
                    break;
                case Sync_DataType_SystemOptions: // 系统参数 // System parameters
                    Path = Path + "\\SystemOptions.txt";
                    break;
                case Sync_DataType_Time: // 下载时间 // Download time (Actually, download time doesn't need a document, just pass an existing file name)
                    Path = Path + "\\PLU.txt";
                    break;
                case Sync_DataType_Label: // 标签 // Label
                    Path = Path + "\\DefaultLabel.lbl";
                    break;
                case Sync_DataType_LabelBackGround: // 标签背景 // Label background
                    Path = Path + "\\DefaultLabel.lbl";
                    break;
                case Sync_DataType_LabelFile: // 标签文件 // Label file
                    Path = Path + "\\DefaultLabel.lbl";
                    break;
            }
            return Path;
        }

        public void setFilesAction(UInt32 Datatypes, UInt32 Actiontypes)
        {
            uint iAddr;
            uint DataType;

            string sFileName;

            // 数据类型。
            // ASSDK_DataType_PLU = $0000; PLU
            // ASSDK_DataType_HotKey = $0003; 热键
            DataType = Convert.ToUInt32(Datatypes); // 转换数据类型 // Convert data type

            iAddr = MakeHostToDWord(tbDeviceIP.Text); // 将设备IP转换为数字形式 // Convert device IP to numeric form

            sFileName = "C:\\Users\\Administrator\\Desktop\\PLU.txt"; // 设置文件路径 // Set file path

            Boolean UseWaitFor; // 这个只是用来标识是否使用SDK_WaitForTask // This is only used to indicate whether to use SDK_WaitForTask

            UseWaitFor = true; // 默认使用等待模式 // Default to use wait mode

            TASSDKDeviceInfo DeviceInfo = new TASSDKDeviceInfo();
            if (SDK_GetDevicesInfo(iAddr, ref DeviceInfo)) // 获取设备信息 // Get device information
            {
                if (UseWaitFor)
                {
                    // 使用 SDK_WaitForTask 的情况
                    TASSDKOnProgressEvent OnProgress = new TASSDKOnProgressEvent(OnProgressEvent_WaitFor); // 创建进度事件处理委托 // Create progress event handler delegate

                    DownLoadState = 0; // 这个用来标识数据更新的情况 // This is used to indicate the status of data update

                    SDK_WaitForTask(SDK_ExecTaskA(DeviceInfo.Addr,
                      Actiontypes, DataType, getFilePathCase(Datatypes), OnProgress, null)); // 执行任务并等待完成 // Execute task and wait for completion

                    switch (DownLoadState)
                    {
                        case SDK_Err_Success:
                            MessageBox.Show("success"); // 显示success消息 // Show success message
                            break;
                        default:
                            MessageBox.Show("error code:" + DownLoadState.ToString()); // 显示error code // Show error number
                            break;

                    }
                }
                else
                {
                    TASSDKOnProgressEvent OnProgress = new TASSDKOnProgressEvent(OnProgressEvent);
                    SDK_ExecTaskA(DeviceInfo.Addr,
                       Actiontypes, DataType, getFilePathCase(Datatypes), OnProgress, null); // 执行任务 // Execute task
                }
            }
        }

        public void setFilesActionBeiwen(UInt32 Datatypes, UInt32 Actiontypes)
        {
            uint iAddr;
            uint DataType;

            string sFileName;

            // 数据类型。
            // ASSDK_DataType_PLU = $0000; PLU
            // ASSDK_DataType_HotKey = $0003; 热键
            DataType = Convert.ToUInt32(Datatypes); // 转换数据类型 // Convert data type

            iAddr = MakeHostToDWord(tbDeviceIP.Text); // 将设备IP转换为数字形式 // Convert device IP to numeric form

            sFileName = "C:\\Users\\Administrator\\Desktop\\PLU.txt"; // 设置文件路径 // Set file path

            TASSDKDeviceInfo DeviceInfo = new TASSDKDeviceInfo();
            if (SDK_GetDevicesInfo(iAddr, ref DeviceInfo)) // 获取设备信息 // Get device information
            {
                TASSDKOnProgressEvent OnProgress = new TASSDKOnProgressEvent(OnProgressEvent); // 创建进度事件处理委托 // Create progress event handler delegate

                SDK_ExecTaskA(DeviceInfo.Addr,
                  Actiontypes, DataType, getFilePathCase(Datatypes), OnProgress, null); // 执行任务 // Execute task
            }
        }

        public void setFilesActionBeiwents(UInt32 Datatypes, UInt32 Actiontypes)
        {
            uint iAddr;
            uint DataType;

            string sFileName;

            // 数据类型。
            // ASSDK_DataType_PLU = $0000; PLU
            // ASSDK_DataType_HotKey = $0003; 热键
            DataType = Convert.ToUInt32(Datatypes); // 转换数据类型 // Convert data type

            iAddr = MakeHostToDWord(tbDeviceIP.Text); // 将设备IP转换为数字形式 // Convert device IP to numeric form

            // sFileName = "C:\\Users\\Administrator\\Desktop\\DefaultLabel.lbl";
            sFileName = getFilePathCase(Datatypes); // 获取文件路径 // Get file path
            TASSDKDeviceInfo DeviceInfo = new TASSDKDeviceInfo();
            if (SDK_GetDevicesInfo(iAddr, ref DeviceInfo)) // 获取设备信息 // Get device information
            {
                TASSDKOnProgressEvent OnProgress = new TASSDKOnProgressEvent(OnProgressEvent); // 创建进度事件处理委托 // Create progress event handler delegate
                SDK_ExecTaskA(DeviceInfo.Addr,
                  Actiontypes, DataType, sFileName, OnProgress, null); // 执行任务 // Execute task
            }
        }

        private void BtPlu_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_PLU, Sync_Action_DownLoad);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SDK_Initialize();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            SDK_Finalize();
        }

        private void BtDepartment_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Department, Sync_Action_DownLoad);
        }

        private void PtUnit_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Unit, Sync_Action_DownLoad);
        }

        private void BtHotKey_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Hotkey, Sync_Action_DownLoad);
        }

        private void BtCustomBarcode_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_CustomBarcode, Sync_Action_DownLoad);
        }

        private void BtNote1_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Note1, Sync_Action_DownLoad);
        }

        private void BtNote2_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Note2, Sync_Action_DownLoad);
        }

        private void BtNote3_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Note3, Sync_Action_DownLoad);
        }

        private void BtNote4_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Note4, Sync_Action_DownLoad);
        }

        private void BtSystemOptions_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_SystemOptions, Sync_Action_DownLoad);
        }

        private void BtTime_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Time, Sync_Action_DownLoad);
        }

        private void BtLabel_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Label, Sync_Action_DownLoad);
        }

        private void BtLabelBackGround_Click(object sender, EventArgs e)
        {

                  setFilesActionBeiwents(Sync_DataType_LabelBackGround, Sync_Action_DownLoad);
           // setFilesAction(Sync_DataType_LabelBackGround, Sync_Action_DownLoad);
        }

        private void BtLabelFile_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_LabelFile, Sync_Action_DownLoad);
        }

        private void btnSDK_Finalize_Click(object sender, EventArgs e)
        {
            SDK_Finalize();
        }

        private void btPluUp_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_PLU, Sync_Action_UpLoad);
        }

        private void btnUpDepartment_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Department, Sync_Action_UpLoad);
        }

        private void btnUpHotkey_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Hotkey, Sync_Action_UpLoad);
        }

        private void btnUpCustomBarcode_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_CustomBarcode, Sync_Action_UpLoad);
        }

        private void btnUpNote1_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Note1, Sync_Action_UpLoad);

        }

        private void btnUpNote2_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Note2, Sync_Action_UpLoad);
        }

        private void btnUpNote3_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Note3, Sync_Action_UpLoad);
        }

        private void btnUpNote4_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Note4, Sync_Action_UpLoad);
        }

        private void btnUpSystemOptions_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_SystemOptions, Sync_Action_UpLoad);

        }

        private void btnUpLabelFile_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_LabelFile, Sync_Action_UpLoad);
        }

        private void btnDelPLU_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_PLU, Sync_Action_Delete);
        }

        private void btnDelNote3_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Note3, Sync_Action_Delete);
        }

        private void btnDelNote4_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Note4, Sync_Action_Delete);
        }

        private void btnDelNote1_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Note1, Sync_Action_Delete);
        }

        private void btnDelNote2_Click(object sender, EventArgs e)
        {
            setFilesAction(Sync_DataType_Note2, Sync_Action_Delete);
        }

        private void pbProgress_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void lbProgress_Click(object sender, EventArgs e)
        {

        }

        private void tbDeviceIP_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnUpOnePLU_Click(object sender, EventArgs e)
        {
            //
            string filename = getCurrentFileDir() + "\\OnePLU.txt";
            uint iAddr = MakeHostToDWord(tbDeviceIP.Text);
            uint lfcode = 10001; // 这个是需要上传的PLU的生鲜码// The fresh code of the PLU that needs to be uploaded
            int result;
            TASSDKDeviceInfo DeviceInfo = new TASSDKDeviceInfo();
            if (SDK_GetDevicesInfo(iAddr, ref DeviceInfo))
            {
                result = SDK_GetOnePLUA(DeviceInfo.Addr, lfcode, filename);
            }
            // 可根据result来知晓运行情况。result的值对应上面 SDK_Err_ 开头的错误信息。
            // You can know the running status according to result. The value of result corresponds to the error message starting with SDK_Err_.
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string outfilename = getCurrentFileDir() + "\\GroupPLU.txt";
            string infilename = getCurrentFileDir() + "\\InFileName.txt"; // 需要的PLU列表 //the list of required PLUs
            uint iAddr = MakeHostToDWord(tbDeviceIP.Text);
            int result;
            TASSDKDeviceInfo DeviceInfo = new TASSDKDeviceInfo();
            if (SDK_GetDevicesInfo(iAddr, ref DeviceInfo))
            {
                result = SDK_GetGroupPLUA(DeviceInfo.Addr, infilename, outfilename);
            }
        }
        private void btnSetLanguage_Click(object sender, EventArgs e)
        {            
            if (!File.Exists(ini_ConfigFilePath))
            {return;}
            IniFile ini_Config = new IniFile(ini_ConfigFilePath);
            ini_Config.WriteValue("Config", "LangCode", comboBox1.Text);
            loadLanguage(comboBox1.Text);
        }
         
       
        private void loadLanguage(string LangCode)
        {

            string ini_LangFilePath = getCurrentFileDir() + "//Language//" + LangCode +  ".ini";
            if (!File.Exists(ini_LangFilePath)) {
                ini_LangFilePath = getCurrentFileDir() + "//Language//" + "English" + ".ini";
                if (!File.Exists(ini_LangFilePath))
                {
                    return;
                }
            }
            IniFile ini_Lang = new IniFile(ini_LangFilePath);
            List<string> ControllerStrings = ini_Lang.ReadAllValuesInSection("ControllerStrings");

            if (ControllerStrings.Count < 37) {
                return;
            }

            BtInitiallize.Text = ControllerStrings[0];
            btnSDK_Finalize.Text = ControllerStrings[1];
            btnUpOnePLU.Text = ControllerStrings[2];
            btnUpGroupPLu.Text = ControllerStrings[3];
            btPluUp.Text = ControllerStrings[4];
            BtPlu.Text = ControllerStrings[5];
            btnDelPLU.Text = ControllerStrings[6];
            btnUpNote1.Text = ControllerStrings[7];
            btnUpNote2.Text = ControllerStrings[8];
            btnUpNote3.Text = ControllerStrings[9];
            btnUpNote4.Text = ControllerStrings[10];
            BtNote1.Text = ControllerStrings[11];
            BtNote2.Text = ControllerStrings[12];
            BtNote3.Text = ControllerStrings[13];
            BtNote4.Text = ControllerStrings[14];
            btnDelNote1.Text = ControllerStrings[15];
            btnDelNote2.Text = ControllerStrings[16];
            btnDelNote3.Text = ControllerStrings[17];
            btnDelNote4.Text = ControllerStrings[18];
            btnUpSystemOptions.Text = ControllerStrings[19];
            BtSystemOptions.Text = ControllerStrings[20];
            btnUpLabelFile.Text = ControllerStrings[21];
            BtLabelFile.Text = ControllerStrings[22];
            BtLabelBackGround.Text = ControllerStrings[23];
            BtLabel.Text = ControllerStrings[24];
            btnUpCustomBarcode.Text = ControllerStrings[25];
            BtCustomBarcode.Text = ControllerStrings[26];
            btnUpHotkey.Text = ControllerStrings[27];
            BtHotKey.Text = ControllerStrings[28];
            btnUpDepartment.Text = ControllerStrings[29];
            BtDepartment.Text = ControllerStrings[30];
            BtTime.Text = ControllerStrings[31];
            PtUnit.Text = ControllerStrings[32];
            btnSetLanguage.Text = ControllerStrings[33];
            lbIp.Text = ControllerStrings[34];
            lbLanguage.Text = ControllerStrings[35];
            lbProgress.Text = ControllerStrings[36];
        }

        private void loadConfig()
        {
            ini_ConfigFilePath = getCurrentFileDir() + "//Config" + "//config.ini";
            if (!File.Exists(ini_ConfigFilePath))
            { return; }
            IniFile ini_Config = new IniFile(ini_ConfigFilePath);

            //language code
            string LangCode = ini_Config.ReadValue("Config", "LangCode");
            loadLanguage(LangCode);

            //support language
            List<string> supportedLanguages = ini_Config.ReadAllValuesInSection("SupportLanguages");
            comboBox1.Items.AddRange(supportedLanguages.ToArray());
            foreach (var item in comboBox1.Items)
            {
                if (item.ToString() == LangCode)
                {
                    comboBox1.SelectedItem = item;
                    break;
                }
            }
        }
    }

   

}

