using System;

using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices; 
using System.Text;
using System.Net.NetworkInformation;
using System.Reflection;

namespace hhScale
{
    /// <summary>
    /// 辉宏1800、1810条码秤
    /// </summary>
    public class HuihongBarcodeScale1800 : Form
    {

 

        public void Init()
        {

        }


        public bool CheckDll()
        {
            try
            {
                return File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "HuiHongHuiHongTransferScale.dll"));
            }
            catch (Exception ex)
            {
               // logger.Error(ex, "检查辉宏dll发生异常");
                return false;
            }
        }


        //public bool GeneratePLUFile(BarcodeScaleItem barcodeScaleItem, List<ProductExt> dataSource, BarCodeTypeEnum barcodeType, string barcodeSign, int amountPrecision, int weightPrecision)
        //{
        //    bool isSucc = false;
        //    try
        //    {
        //        //条码转换
        //        var barcodeTypeTrans = barcodeType == BarCodeTypeEnum.金额码 ? "2" : "7";

        //        StringBuilder sb = new StringBuilder();
        //        //PLU标准格式 商品编号,货号,部门号,组号,第一品名,第一单价,第二单价,第一标签号,第二标签号,第三标签号,第一图片号,第2图片号,第3图片号,商品类型,固定重量,条码号,皮重号,计数商品单位,是否打印包装日期,包装日期类型,包装日期偏移量,包装绝对日期,是否打印推荐日期,保质日期类型,保质日期偏移量,保质绝对日期,是否打印推荐日期,推荐日期类型,推荐日期偏移量,推荐绝对日期,附加信息号,营养表号,特价开始日期,特价结束日期,特价,是否允许改价,是否打折,是否特价,是否打印追溯码,计重单位,第二品名
        //        var format = "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23},{24},{25},{26},{27},{28},{29},{30},{31},{32},{33},{34},{35},{36},{37},{38},{39},{40}\r\n";
        //        //内容
        //        if (dataSource != null && dataSource.Count > 0)
        //        {
        //            foreach (var p in dataSource)
        //            {
        //                var weightWay = p.WeightWay == 1 ? 0 : 1;//0：计重，1：计数
        //                var unit = p.UnitName.Length > 4 ? p.UnitName.Substring(0, 4) : p.UnitName;
        //                //校验非法商品
        //                if (p.BarCode.Length == 5)
        //                {
        //                    sb.AppendFormat(format, p.BarCode, p.BarCode, barcodeSign, 0, p.Name, p.SpecialPrice, p.SpecialPrice,11, 22,33,1,2,3, weightWay, 0, 0,0, unit, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,string.Empty,string.Empty,p.SpecialPrice,p.ForeBargain, p.ForeDiscount,0, 0, 0, p.Name);
        //                }

        //            }
        //        }
        //        if(sb.Length > 0)
        //        {
        //            //写入文件系统
        //            var newPath = Path.Combine(Global.Instance.HuihongFileDataPath, "plu.txt");
        //            File.WriteAllText(newPath, sb.ToString(), Encoding.GetEncoding("GB2312"));
        //        }
        //        isSucc = true;
        //    }
        //    catch (Exception ex)
        //    {
        //        logger.Error(ex, "生成辉宏PLU文件异常");
        //        isSucc = false;
        //    }
        //    return isSucc;
        //}

        public bool TestConnect(string ipAddress, int port)
        {
            bool isSucc = false;
            try
            {
                Ping ping = new Ping();
                PingReply reply = ping.Send(ipAddress);
                if (reply.Status == IPStatus.Success)
                {
                    isSucc = true;
                }
                else
                {
                    isSucc = false;
                }
            }
            catch (Exception ex)
            {
               // logger.Error(ex, "测试辉宏秤连接异常");
                isSucc = false;
            }
            finally
            {
            }
            return isSucc;
        }

        public bool Upload(string ipAddress, int port, bool uploadAll)
        {
            bool isSucc = true;
            try
            {
                var plufileName =@"D:\work\Application\SoftProject\DZC\HR00\程序源码\ScaleDataManager\ScaleDataManager\DLL\demo\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\plu.txt"; //Path.Combine(Global.Instance.HuihongFileDataPath, "plu.txt");
                var hotkeyfileName = "";//Path.Combine(Global.Instance.HuihongFileDataPath, "hotkey.txt");
                var deviceAddressfileName = @"D:\work\Application\SoftProject\DZC\HR00\程序源码\ScaleDataManager\ScaleDataManager\DLL\demo\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\ScaleAddress.ini";//Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ScaleAddress.ini");

                //生成设备INI文件
                //if (!File.Exists(deviceAddressfileName))
                //{
                //    File.WriteAllText(deviceAddressfileName, "[1]");
                //}
                //FileIniDataParser fileIniData = new FileIniDataParser();
                //fileIniData.Parser.Configuration.CommentString = "#";
                //fileIniData.Parser.Configuration.AllowDuplicateKeys = true;
                //fileIniData.Parser.Configuration.AssigmentSpacer = string.Empty;
                //IniData parsedData = fileIniData.ReadFile(deviceAddressfileName);
                //var section = "1";
                //parsedData[section]["NAME"] = "1";
                //parsedData[section]["IP"] = ipAddress;
                //parsedData[section]["PORT"] = port.ToString();
                //parsedData[section]["RESULT"] = string.Empty;
                ////这里注意，默认格式为UTF-8-BOM
                //var utf8WithOutBom = new System.Text.UTF8Encoding(false);
                //fileIniData.WriteFile(deviceAddressfileName, parsedData, utf8WithOutBom);

                if (File.Exists(plufileName))
                {
                    //logger.Info("辉宏开始下传PLU");
                    //商品数据 对应数据类型值为 1207 , 支持 文本格式 和 二进制格式 的数据文件
                    //附加信息   对应数据类型值为 1209 , 支持 文本格式 和 二进制格式 的数据文件
                    //预置键     对应数据类型值为 1216 , 支持 文本格式 和 二进制格式 的数据文件
                    //秤时间校准 对应数据类型值为 1238 , 支持 文本格式 和 二进制格式 的数据文件，（校时时，DataFileName为空字符串即可。）
                    //0：成功 , 其它值失败 或 用户中止.
                    //int ttt = TestCallFun(1, 2, "abc");
                    var res = SendDataToScale("1", 1207, plufileName, 0);
                    //logger.Error("辉宏下传PLU返回结果<{0}>", res);
                    if (res == 0 && isSucc)
                    {
                        isSucc = true;
                    }
                    else
                    {
                        isSucc = false;
                    }

                    //logger.Info("辉宏下传PLU结束");
                }

                //if (File.Exists(hotkeyfileName))
                //{
                //    logger.Info("辉宏开始下传热键");
                //    var res = SendDataToScale("1", 1216, hotkeyfileName, 0);
                //    logger.Error("辉宏下传热键返回结果<{0}>", res);
                //    if (res == 0 && isSucc)
                //    {
                //        isSucc = true;
                //    }
                //    else
                //    {
                //        isSucc = false;
                //    }

                //   // logger.Info("辉宏下传热键结束");
                //}
            }
            catch (Exception ex)
            {
               // logger.Error(ex, "辉宏传秤异常");
                isSucc = false;
            }
            finally
            {
            }
            return isSucc;
        }

        /// <summary>
        /// 下载地址
        /// </summary>
        /// <returns></returns>
        //public string GetInstallUrl() => Constant.HUIHONGDllUrl;

        [DllImport("HuiHongTransferScale.dll", EntryPoint = "TestCallFun", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Winapi)]
        public static extern int TestCallFun(int a, int b, string c);

        [DllImport("HuiHongTransferScale.dll", EntryPoint = "TestShowForm", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Winapi)]
        public static extern int TestShowForm();

        [DllImport("HuiHongTransferScale.dll", EntryPoint = "RecvDataFromScale", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Winapi)]
        public static extern int RecvDataFromScale(int ScaleNo, int DataType, int FromNo, int ToNo, string DestFileName);

        [DllImport("HuiHongTransferScale.dll", EntryPoint = "SendDataToScale", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Winapi)]
        public static extern int SendDataToScale(string ScaleNoList, int DataType, string DataFileName, int DataFormat);

        [DllImport("HuiHongTransferScale.dll", EntryPoint = "DeleteDataFromScale", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Winapi)]
        public static extern int DeleteDataFromScale(string ScaleNoList, int DataType, int FromNo, int ToNo);

        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // HuihongBarcodeScale1800
            // 
            this.ClientSize = new System.Drawing.Size(282, 253);
            this.Name = "HuihongBarcodeScale1800";
            this.Load += new System.EventHandler(this.HuihongBarcodeScale1800_Load);
            this.ResumeLayout(false);

        }

        private void HuihongBarcodeScale1800_Load(object sender, EventArgs e)
        {

        }
    }
}
