using com.hnshituo.core.webapp.vo;
using Common;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FrmStandAloneMetering
{
    /// <summary>
    /// 仪表状态
    /// </summary>
    public enum MeterStatus
    {
        /// <summary>
        /// Stable  稳定
        /// </summary>
        Stable,

        /// <summary>
        /// 不稳定
        /// </summary>
        UnStable,

        /// <summary>
        /// 空磅
        /// </summary>
        Null,

        ///// <summary>
        ///// 未连接
        ///// </summary>
        UnConnect,

        ///// <summary>
        ///// 已连接
        ///// </summary>
        Connect
    }

    public partial class FrmStandAloneMetering : Form
    {
        private string strComPara; //仪表参数
        private int messageLength; //报文长度
        private string strSeparate;//分割符
        private int startPosition; //开始取值位置
        private int dataLength;    //数据长度
        private int sleepTime; //采样频率
        private int stableTime; //稳定时间
        private int stableCount; //稳定次数
        private int stableDiff; //稳定次数
        private double tmpWeight; //临时重量,用于判断是否稳定状态
        private int weightStabCount; //波动次数

        private SerialPort serialPort1; //数据采集串口
        private bool blThreadFlag;//数据采集线程开关
        private StringBuilder weightLog = new StringBuilder(); //重量日志的文件

        private MeterWorkCarActualFirstService actualFirstService = new MeterWorkCarActualFirstService();

        public FrmStandAloneMetering()
        {
            InitializeComponent();
        }

        private void FrmStandAloneMetering_Load(object sender, EventArgs e)
        {
            strComPara = ConfigurationManager.AppSettings["ComPara"].ToString().Trim(); //仪表参数COM口
            messageLength = Convert.ToInt32(ConfigurationManager.AppSettings["MessageLength"].ToString().Trim()); //报文长度
            strSeparate = ConfigurationManager.AppSettings["Separate"].ToString().Trim();//分割符
            startPosition = Convert.ToInt32(ConfigurationManager.AppSettings["StartPosition"].ToString().Trim());//开始取值位置
            dataLength = Convert.ToInt32(ConfigurationManager.AppSettings["DataLength"].ToString().Trim());// 数据长度
            sleepTime = Convert.ToInt32(ConfigurationManager.AppSettings["SleepTime"].ToString().Trim());//采样频率
            stableTime = Convert.ToInt32(ConfigurationManager.AppSettings["StableTime"].ToString().Trim());//稳定时间
            stableDiff = Convert.ToInt32(ConfigurationManager.AppSettings["StableDiff"].ToString().Trim());//稳定重量
            stableCount = stableTime * 1000 / sleepTime;//稳定次数

            //界面COM赋值
            if (!String.IsNullOrEmpty(strComPara) && strComPara.Contains(","))
            {
                string[] strParams = strComPara.Split(new char[] { ',' });
                cbChooseCom.Text = strParams[0];
            }

            //物料下拉框赋值
            DataTable dtMatterInfo = selectMatterInfo();
            this.cbMatterName.DataSource = dtMatterInfo;
            this.cbMatterName.DisplayMember = "name";
            this.cbMatterName.ValueMember = "value";

            //发货单位下拉框赋值
            DataTable dtForwardingUnit = selectCustomerInfo();
            this.cbForwardingUnitName.DataSource = dtForwardingUnit;
            this.cbForwardingUnitName.DisplayMember = "name";
            this.cbForwardingUnitName.ValueMember = "value";

            //收货单位下拉框赋值
            DataTable dtReceivingUint = selectCustomerInfo();
            this.cbReceivingUintName.DataSource = dtReceivingUint;
            this.cbReceivingUintName.DisplayMember = "name";
            this.cbReceivingUintName.ValueMember = "value";

            //计量点下拉框赋值
            DataTable dtSpotInfo = selectSpotInfo();
            this.cbBaseSpot.DataSource = dtSpotInfo;
            this.cbBaseSpot.DisplayMember = "name";
            this.cbBaseSpot.ValueMember = "value";


            //界面稳定时间赋值
            cbStableSchedule.Text = stableTime.ToString();

            tmpWeight = 0;//临时重量
            weightStabCount = 0; //波动次数
        }

        #region 用户控件的事件

        /// <summary>
        /// 开启数据采集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCollection_Click(object sender, EventArgs e)
        {
            if (blThreadFlag)
            {
                MessageBox.Show("采集程序已经运行，禁止重新进行采集！");
                return;
            }
            blThreadFlag = true;
            System.Threading.Thread DataCollectThread = new System.Threading.Thread(new System.Threading.ThreadStart(DataCollect));
            DataCollectThread.Start();
        }

        /// <summary>
        /// 上传本地的计量数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUploadData_Click(object sender, EventArgs e)
        {
            uploadData();
        }

        /// <summary>
        /// 下载服务器的基础数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDownloadData_Click(object sender, EventArgs e)
        {
            
            // 删除CSV文件
            Utils.FileUtil.DeleteFile(AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseMatterInfo.csv");

            // 获取物料信息
            MeterBaseMatterInfoService meterBaseMatterInfo = new MeterBaseMatterInfoService();//物料服务
            MeterBaseMatterInfo MatterInfo1 = new MeterBaseMatterInfo();

            MatterInfo1.validFlag = "1";
            MatterInfo1.pageNum = 1;
            MatterInfo1.pageSize = 9999;
            RESTfulResult<List<MeterBaseMatterInfo>> rmx = meterBaseMatterInfo.doQueryListLike(MatterInfo1);

            // 重新保存CSV文件
            saveMatterInfo(rmx);

            // 删除CSV文件
            Utils.FileUtil.DeleteFile(AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseCustomerSupplier.csv");

            // 获取客商信息
            MeterBaseCustomerSupplierService service2 = new MeterBaseCustomerSupplierService();//物料服务
            MeterBaseCustomerSupplier customerInfo1 = new MeterBaseCustomerSupplier();

            customerInfo1.validFlag = "1";
            RESTfulResult<List<MeterBaseCustomerSupplier>> rmx2 = service2.doQuery(customerInfo1);

            // 重新保存CSV文件
            saveCustomerInfo(rmx2);

            // 删除CSV文件
            Utils.FileUtil.DeleteFile(AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseSpotInfo.csv");

            // 获取客商信息
            MeterBaseSpotInfoService service3 = new MeterBaseSpotInfoService();//物料服务
            MeterBaseSpotInfo customerInfo2 = new MeterBaseSpotInfo();

            customerInfo2.validFlag = "1";
            RESTfulResult<List<MeterBaseSpotInfo>> rmx3 = service3.doQueryWf(customerInfo2);

            // 重新保存CSV文件
            saveSpotInfo(rmx3);
        }

        /// <summary>
        /// 数据查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btQuery_Click(object sender, EventArgs e)
        {
            doQuery();
        }

        /// <summary>
        /// 毛重保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btSaveGross_Click(object sender, EventArgs e)
        {
            saveData("0"); //毛重保存（0=毛重；1=常规皮重）
            doQuery();
        }

        /// <summary>
        /// 皮重保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btSaveTare_Click(object sender, EventArgs e)
        {
            saveData("1"); //毛重保存（0=毛重；1=常规皮重）
            doQuery();
        }

        /// <summary>
        /// 界面关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmStandAloneMetering_FormClosing(object sender, FormClosingEventArgs e)
        {
            blThreadFlag = false;
            System.Threading.Thread.Sleep(sleepTime * 2);
            if (serialPort1 != null)
            {
                serialPort1.Close();
            }
            Application.Exit();
        }

        /// <summary>
        /// 稳定时间选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbStableSchedule_TextChanged(object sender, EventArgs e)
        {
            stableTime = Convert.ToInt32(cbStableSchedule.Text.Trim());//稳定时间
            stableCount = stableTime * 1000 / sleepTime;//稳定次数
        }

        /// <summary>
        /// COM口下拉事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void cbChooseCom_TextChanged(object sender, EventArgs e)
        {
            if (blThreadFlag)
            {
                MessageBox.Show("采集程序已经运行，禁止重新调整COM口！");
                return;
            }
        }

        #endregion 用户控件的事件

        #region 数据采集

        /// <summary>
        /// 数据采集线程
        /// </summary>
        private void DataCollect()
        {
            if (!blThreadFlag) return;
            string[] strParams = strComPara.Split(new char[] { ',' });

            Parity parity = Parity.None;
            if (strParams[2].ToUpper() == "ODD")
            {
                parity = Parity.Odd;
            }
            if (strParams[2].ToUpper() == "EVEN")
            {
                parity = Parity.Even;
            }

            StopBits stopBits = StopBits.None;
            if (strParams[4] == "1")
            {
                stopBits = StopBits.One;
            }
            if (strParams[4] == "1.5")
            {
                stopBits = StopBits.OnePointFive;
            }
            if (strParams[4] == "2")
            {
                stopBits = StopBits.Two;
            }
            serialPort1 = new SerialPort(strParams[0], Int32.Parse(strParams[1]),
                parity, Int32.Parse(strParams[3]), stopBits);

            while (!serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.Open();
                }
                catch (Exception err)
                {
                    WriteCatchLog(err.ToString());
                }
                System.Threading.Thread.Sleep(500);
            }

            StringBuilder stringBuilder = new StringBuilder();
            string strtmp = "";

            while (blThreadFlag)
            {
                try
                {
                    System.Threading.Thread.Sleep(sleepTime);

                    if (serialPort1.BytesToRead > 0)
                    {
                        strtmp = serialPort1.ReadExisting();

                        stringBuilder.Append(strtmp);
                        //"US,GS,+0073.34 t\r\nUS,GS,+0073.96 t\r\nUS,GS,+0071.36 t\r\nUS,GS,+0070.40 t\r\nUS,GS,+0073.06 t\r\nUS,GS,+0073.16 t\r\nUS,GS,+0071.72 t\r\nUS,GS,+0073.30 t\r\nUS,GS,+0074.16 t\r\n"

                        //0252.50 kg
                        //20 20 0D 0A 7F 30 32 35 32 2E 35 30 20 6B 67
                        //03 04 0D 0A FF 30 30 30 30 31 35 20 6B 67

                        //char strSeparate = (char)0x6B;
                        if (stringBuilder.ToString().LastIndexOf(strSeparate) >= 0)
                        {
                            if (stringBuilder.ToString().LastIndexOf(strSeparate) < messageLength)//不完整报文，抛掉
                            {
                                stringBuilder.Remove(0, stringBuilder.ToString().LastIndexOf(strSeparate) + strSeparate.Length);
                                //stringBuilder.Remove(0, stringBuilder.ToString().LastIndexOf(strSeparate) + strSeparate.Length);
                            }

                            int index = stringBuilder.ToString().LastIndexOf(strSeparate);
                            if ((index - messageLength) < 0)
                                continue;

                            string strData = stringBuilder.ToString().Substring(index - messageLength, messageLength + strSeparate.Length);
                            // WriteCatchLog("strData  " + strData);

                            string weight = strData.Substring(startPosition, dataLength);
                            if ("T".Equals(strSeparate.ToUpper()))
                            {
                                //单位为T是做特殊处理，界面显示的是T
                                weight = (Convert.ToDouble(weight) * 1000) + "";
                            }
                            //WriteCatchLog("weight  " + weight);

                            stringBuilder.Remove(0, stringBuilder.Length);
                            ucStorageWeightT1.setWgt(Math.Round(Convert.ToDouble(weight), 3));
                            DoShowWeightStatus(Convert.ToDouble(weight));
                        }
                    }
                }
                catch (Exception err)
                {
                    MessageBox.Show("串口打开异常！异常原因" + err.ToString());
                    WriteCatchLog("DataCollect1" + err.ToString());
                }
            }
        }

        /// <summary>
        /// 重量稳定判断
        /// </summary>
        /// <param name="_weight"></param>
        public void DoShowWeightStatus(double _weight)
        {
            if (Math.Abs(_weight) < 50)
            {
                //不稳定状态;红灯
                ucStorageWeightT1.setStable(false);
                return;
            }

            //波动在范围内时，稳定次数+1，临时重量不变；波动范围超出时，稳定次数清零，更新临时重量，
            int inDiff = Math.Abs(Convert.ToInt32(tmpWeight - _weight));
            if (inDiff < stableDiff)
            {
                weightStabCount += 1;
            }
            else
            {
                weightStabCount = 0;
            }
            //WriteCatchLog("_tmpWeight: " + _tmpWeight + "   _weight: " + _weight + "   inDiff: "+inDiff+ "  StabCount : " + weightStabCount);
            tmpWeight = Convert.ToSingle(_weight);
            //重量30kg内波动超过10次认为重量稳定
            if (weightStabCount > stableCount)
            {
                //稳定状态;绿灯
                ucStorageWeightT1.setStable(true);
                weightStabCount = stableCount;
            }
            else
            {
                ucStorageWeightT1.setStable(false);
            }
        }

        #endregion 数据采集

        /// <summary>
        /// 重量保存：0=毛重；1=常规皮重
        /// </summary>
        /// <param name="strWeightType"></param>
        private void saveData(string strWeightType)
        {
            MeterWorkCarActualFirst actualFirst = new MeterWorkCarActualFirst(); //一次计量实体
            actualFirst.actualFirstNo = "CAR" + DateTime.Now.ToString("yyyyMMddHHmmssfff"); //主键
            actualFirst.carNo = tbCarNo.Text.Trim();//车号
            actualFirst.baseSpotNo = cbBaseSpot.SelectedValue.ToString().Trim();//计量点
            //actualFirst.meterTypeName = cbMeterTypeName.Text.Trim();//业务类型
            //actualFirst.contractNo = cbContractNo.Text.Trim();//合同号
            //actualFirst.batchNo = tbBatchNo.Text.Trim();//批次号
            //actualFirst.heatNo = tbHeatNo.Text.Trim();//炉号
            //actualFirst.shipmentNum = Convert.ToInt32(string.IsNullOrEmpty(tbShipmentNum.Text.Trim()) ? "0" : tbShipmentNum.Text.Trim());//包数/数量
            actualFirst.matterNo = cbMatterName.SelectedValue.ToString().Trim();//物资名称
            actualFirst.receivingUintNo = cbReceivingUintName.SelectedValue.ToString().Trim();//收货单位
            actualFirst.forwardingUnitNo = cbForwardingUnitName.SelectedValue.ToString().Trim();//发货单位
            //actualFirst.customerSupplierName = cbCustomerSupplierName.Text.Trim();//供应商
            //actualFirst.loadPointName = cbLoadPointName.Text.Trim();//卸货地点
            actualFirst.memo = tbMemo.Text.Trim();//备注
            actualFirst.weightType = strWeightType;//重量类型
            actualFirst.meterWeight = ucStorageWeightT1.getWgt() * 1000;

            //DataTable csvDataTable = OpenCSV(AppDomain.CurrentDomain.BaseDirectory + "alonData\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\actualFirst.csv");
            if (System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "alonData\\" + DateTime.Now.ToString("yyyy-MM-dd")) == false
                || System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "alonData\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\actualFirst.csv") == false)
            {
                StringBuilder actualFirstLogHead = new StringBuilder(); //一次计量数据保存文件
                actualFirstLogHead.Append("createTime,");//若第一行默认为当前时间则第一行多个逗号
                actualFirstLogHead.Append("actualFirstNo,");
                actualFirstLogHead.Append("carNo,");
                actualFirstLogHead.Append("baseSpotNo,");
                //actualFirstLogHead.Append("meterTypeName,");
                //actualFirstLogHead.Append("contractNo,");
                //actualFirstLogHead.Append("batchNo,");
                //actualFirstLogHead.Append("heatNo,");
                //actualFirstLogHead.Append("shipmentNum,");
                actualFirstLogHead.Append("matterNo,");
                actualFirstLogHead.Append("receivingUintNo,");
                actualFirstLogHead.Append("forwardingUnitNo,");
                //actualFirstLogHead.Append("customerSupplierName,");
                //actualFirstLogHead.Append("loadPointName,");
                actualFirstLogHead.Append("memo,");
                actualFirstLogHead.Append("weightType,"); //最后一行不要逗号
                actualFirstLogHead.Append("meterWeight");
                logCsv.WriteDataLog("actualFirst", actualFirstLogHead.ToString());
            }

            StringBuilder actualFirstLog = new StringBuilder(); //一次计量数据保存文件
            actualFirstLog.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ",");
            actualFirstLog.Append(actualFirst.actualFirstNo.ToString() + ",");
            actualFirstLog.Append(actualFirst.carNo.ToString() + ",");
            actualFirstLog.Append(actualFirst.baseSpotNo.ToString() + ",");
           // actualFirstLog.Append(actualFirst.meterTypeName.ToString() + ",");
            //actualFirstLog.Append(actualFirst.contractNo.ToString() + ",");
            //actualFirstLog.Append(actualFirst.batchNo.ToString() + ",");
            //actualFirstLog.Append(actualFirst.heatNo.ToString() + ",");
            //actualFirstLog.Append(actualFirst.shipmentNum.ToString() + ",");
            actualFirstLog.Append(actualFirst.matterNo.ToString() + ",");
            actualFirstLog.Append(actualFirst.receivingUintNo.ToString() + ",");
            actualFirstLog.Append(actualFirst.forwardingUnitNo.ToString() + ",");
            //actualFirstLog.Append(actualFirst.customerSupplierName.ToString() + ",");
            //actualFirstLog.Append(actualFirst.loadPointName.ToString() + ",");
            actualFirstLog.Append(actualFirst.memo.ToString() + ",");
            actualFirstLog.Append(actualFirst.weightType.ToString() + ",");
            actualFirstLog.Append(actualFirst.meterWeight.ToString());
            logCsv.WriteDataLog("actualFirst", actualFirstLog.ToString());
        }

        /// <summary>
        /// 上传数据
        /// </summary>
        private void uploadData()
        {
            openFileDialogUpData.Filter = "csv文件|*.csv";//只允许csv文件;*.csv;*.xlsx
            openFileDialogUpData.Title = "选择要导入的计量数据文件"; //弹出框头部显示
            openFileDialogUpData.AddExtension = true; //自动增加后缀
            openFileDialogUpData.AutoUpgradeEnabled = true; //是否随系统自动升级弹出窗口样式
            openFileDialogUpData.InitialDirectory = Application.StartupPath + "\\alonData\\" + DateTime.Now.ToString("yyyy-MM-dd");//默认打开当前目录
            //openFileDialog1.Multiselect = true;//该值确定是否可以选择多个文件
            if (openFileDialogUpData.ShowDialog() == DialogResult.OK)
            {
                DataTable csvDataTable = OpenCSV(openFileDialogUpData.FileName);
                int rowCount = csvDataTable.Rows.Count;
                if (csvDataTable != null && csvDataTable.Rows.Count > 0)
                {
                    List<MeterWorkCarActualFirst> lp = csvDataTable.TableToDataList<MeterWorkCarActualFirst>();
                    DialogResult dr = MessageBox.Show("共 " + lp.Count + " 条计量数据，是否继续上传？", "提示", MessageBoxButtons.OKCancel);
                    if (dr != DialogResult.OK)
                    {
                        return;
                    }
                    //操作日志
                    RESTfulResult<string> rES = actualFirstService.addEmergency(lp);
                    if (rES.Succeed)
                    {
                        MessageBox.Show("数据上传成功！");
                    }
                    else
                    {
                        MessageBox.Show("数据上传失败：" + rES.Message);
                    }
                }
            };
        }

        public static DataTable OpenCSV(string filePath)
        {
            Encoding encoding = Encoding.UTF8; //Common.GetType(filePath); //Encoding.ASCII;//
            DataTable dt = new DataTable();
            FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            //StreamReader sr = new StreamReader(fs, Encoding.UTF8);
            StreamReader sr = new StreamReader(fs, encoding);
            //string fileContent = sr.ReadToEnd();
            //encoding = sr.CurrentEncoding;
            //记录每次读取的一行记录
            string strLine = "";
            //记录每行记录中的各字段内容
            string[] aryLine = null;
            string[] tableHead = null;
            //标示列数
            int columnCount = 0;
            //标示是否是读取的第一行
            bool IsFirst = true;
            //逐行读取CSV中的数据
            while ((strLine = sr.ReadLine()) != null)
            {
                //strLine = Common.ConvertStringUTF8(strLine, encoding);
                //strLine = Common.ConvertStringUTF8(strLine);

                if (IsFirst == true)
                {
                    tableHead = strLine.Split(',');
                    IsFirst = false;
                    columnCount = tableHead.Length;
                    //创建列
                    for (int i = 0; i < columnCount; i++)
                    {
                        DataColumn dc = new DataColumn(tableHead[i]);
                        //DataColumn dc = new DataColumn(i.ToString());
                        dt.Columns.Add(dc);
                        switch (i) { }
                    }
                }
                else
                {
                    aryLine = strLine.Split(',');
                    DataRow dr = dt.NewRow();
                    for (int j = 0; j < columnCount; j++)
                    {
                        dr[j] = aryLine[j];
                    }
                    dt.Rows.Add(dr);
                }
            }
            //if (aryLine != null && aryLine.Length > 0)
            //{
            //    dt.DefaultView.Sort = tableHead[0] + " " + "asc";
            //}

            sr.Close();
            fs.Close();
            return dt;
        }

        /// <summary>
        /// 数据查询
        /// </summary>
        private void doQuery()
        {
            if (System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "alonData\\" + DateTime.Now.ToString("yyyy-MM-dd")) == true
               && System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "alonData\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\actualFirst.csv") == true)
            {
                DataTable csvDataTable = OpenCSV(AppDomain.CurrentDomain.BaseDirectory + "alonData\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\actualFirst.csv");
                int rowCount = csvDataTable.Rows.Count;
                if (csvDataTable != null && csvDataTable.Rows.Count > 0)
                {
                    List<MeterWorkCarActFirAlon> lp = csvDataTable.TableToDataList<MeterWorkCarActFirAlon>();
                    rowCount = lp.Count;
                    //毛重数据查询
                    DataTable dtGross = csvDataTable.Clone();
                    List<MeterWorkCarActFirAlon> lpGross = lp.Where(s => s.weightType == "0").ToList();
                    if (lpGross != null && lpGross.Count > 0)
                    {
                        dtGross = lpGross.ListToDataTable<MeterWorkCarActFirAlon>();
                    }
                    ClsControlPack.CopyDataToDatatable(ref dtGross, ref this.dtCarActFirstGross, true);
                    foreach (var item in this.ultraGridGross.Rows)
                    {
                        item.Cells["weightType"].Value = GetWeightType(item.Cells["weightType"].Value.ToString());
                    }
                    ClsControlPack.RefreshAndAutoSize(ultraGridGross);

                    //皮重数据查询
                    DataTable dtTare = csvDataTable.Clone();
                    List<MeterWorkCarActFirAlon> lpTare = lp.Where(s => s.weightType == "1").ToList();
                    if (lpTare != null && lpTare.Count > 0)
                    {
                        dtTare = lpTare.ListToDataTable<MeterWorkCarActFirAlon>();
                    }
                    ClsControlPack.CopyDataToDatatable(ref dtTare, ref this.dtCarActFirstTare, true);
                    foreach (var item in this.ultraGridTare.Rows)
                    {
                        item.Cells["weightType"].Value = GetWeightType(item.Cells["weightType"].Value.ToString());
                    }
                    ClsControlPack.RefreshAndAutoSize(ultraGridTare);
                }
            }
            else
            {
                MessageBox.Show("未查询到当天的数据文件！");
            }
        }

        /// <summary>
        /// 重量类型
        /// </summary>
        /// <param name="strCode"></param>
        /// <returns></returns>

        public static string GetWeightType(string strCode)
        {
            string weightType = ""; //重量类型（0：毛重；1：皮重）
            switch (strCode)
            {
                case "0": weightType = "毛重"; break;
                case "1": weightType = "皮重"; break;
                default:
                    break;
            }
            return weightType;
        }

        /// <summary>
        /// 记录错误日志
        /// </summary>
        /// <param name="str"></param>
        private void WriteCatchLog(string str)
        {
            try
            {
                string m_szRunPath = System.Environment.CurrentDirectory.ToString();
                if (!(System.IO.Directory.Exists(m_szRunPath + "\\log")))
                {
                    System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
                }

                string strDate = System.DateTime.Now.ToString("yyyyMMddhh");

                System.IO.TextWriter tw = new System.IO.StreamWriter(m_szRunPath + "\\log\\catch.log", true);

                tw.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\t" + str);

                tw.Close();
            }
            catch
            {
            }
        }

        /// <summary>
        /// 保存物料信息到csv文件
        /// </summary>
        /// <param name="result"></param>
        private void saveMatterInfo(RESTfulResult<List<MeterBaseMatterInfo>> result)
        {
            StringBuilder materInfoHead = new StringBuilder(); // 物料头
            materInfoHead.Append("matterNo,");//若第一行默认为当前时间则第一行多个逗号
            materInfoHead.Append("matterName");
           
            logCsv.WriteBaseData("MeterBaseMatterInfo", materInfoHead.ToString());

            if (result.Succeed)
            {
                StringBuilder materInfo = new StringBuilder(); // 物料体

                List<MeterBaseMatterInfo> list = result.Data;

                foreach (MeterBaseMatterInfo info in list)
                {
                    materInfo.Clear();
                    materInfo.Append(info.matterNo + ",");
                    materInfo.Append(info.matterName + ",");

                    logCsv.WriteBaseData("MeterBaseMatterInfo", materInfo.ToString());
                }
            }
        }

        /// <summary>
        /// 保存收发货单位信息到csv文件
        /// </summary>
        /// <param name="result"></param>
        private void saveCustomerInfo(RESTfulResult<List<MeterBaseCustomerSupplier>> result)
        {
            StringBuilder customerInfoHead = new StringBuilder(); // 客商头
            customerInfoHead.Append("customerSupplierNo,");//若第一行默认为当前时间则第一行多个逗号
            customerInfoHead.Append("customerSupplierName");

            logCsv.WriteBaseData("MeterBaseCustomerSupplier", customerInfoHead.ToString());

            if (result.Succeed)
            {
                StringBuilder customerInfo = new StringBuilder(); // 物料体

                List<MeterBaseCustomerSupplier> list = result.Data;

                if(result.Data != null)
                {
                    foreach (MeterBaseCustomerSupplier info in list)
                    {
                        customerInfo.Clear();
                        customerInfo.Append(info.customerSupplierNo + ",");
                        customerInfo.Append(info.customerSupplierName + ",");

                        logCsv.WriteBaseData("MeterBaseCustomerSupplier", customerInfo.ToString());
                    }
                }
            }
        }

        /// <summary>
        /// 保存计量点信息到csv文件
        /// </summary>
        /// <param name="result"></param>
        private void saveSpotInfo(RESTfulResult<List<MeterBaseSpotInfo>> result)
        {
            StringBuilder spotInfoHead = new StringBuilder(); // 客商头
            spotInfoHead.Append("spotNo,");//若第一行默认为当前时间则第一行多个逗号
            spotInfoHead.Append("spotName"); 

            logCsv.WriteBaseData("MeterBaseSpotInfo", spotInfoHead.ToString());

            if (result.Succeed)
            {
                StringBuilder spotInfo = new StringBuilder(); // 物料体

                List<MeterBaseSpotInfo> list = result.Data;

                if (result.Data != null)
                {
                    foreach (MeterBaseSpotInfo info in list)
                    {
                        spotInfo.Clear();
                        spotInfo.Append(info.baseSpotNo + ",");
                        spotInfo.Append(info.baseSpotName + ",");

                        logCsv.WriteBaseData("MeterBaseSpotInfo", spotInfo.ToString());
                    }
                }
            }
        }

        /// <summary>
        /// 从csv文件读取物料信息
        /// </summary>
        /// <returns></returns>
        private DataTable selectMatterInfo()
        {
            if (System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "baseData") == true
               && System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseMatterInfo.csv") == true)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseMatterInfo.csv";
                DataTable csvDataTable = OpenCSV(path);
                int rowCount = csvDataTable.Rows.Count;
                if (csvDataTable != null && csvDataTable.Rows.Count > 0)
                {
                    DataTable newCsvDataTable = new DataTable();
                    newCsvDataTable.Columns.Add("name");
                    newCsvDataTable.Columns.Add("value");
                    for (int i = 1; i < csvDataTable.Rows.Count; i++)
                    {
                        DataRow dr = newCsvDataTable.NewRow();
                        dr[0] = "[" + csvDataTable.Rows[i]["matterNo"].ToString() + "]" + csvDataTable.Rows[i]["matterName"].ToString();
                        dr[1] = csvDataTable.Rows[i]["matterNo"].ToString();
                        newCsvDataTable.Rows.Add(dr);
                    }
                    return newCsvDataTable;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 从csv文件读取收发货单位信息
        /// </summary>
        /// <returns></returns>
        private DataTable selectCustomerInfo()
        {
            if (System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "baseData") == true
               && System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseCustomerSupplier.csv") == true)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseCustomerSupplier.csv";
                DataTable csvDataTable = OpenCSV(path);
                int rowCount = csvDataTable.Rows.Count;
                if (csvDataTable != null && csvDataTable.Rows.Count > 0)
                {
                    DataTable newCsvDataTable = new DataTable();
                    newCsvDataTable.Columns.Add("name");
                    newCsvDataTable.Columns.Add("value");
                    for (int i = 1; i < csvDataTable.Rows.Count; i++)
                    {
                        DataRow dr = newCsvDataTable.NewRow();
                        dr[0] = "[" + csvDataTable.Rows[i]["customerSupplierNo"].ToString() + "]" + csvDataTable.Rows[i]["customerSupplierName"].ToString();
                        dr[1] = csvDataTable.Rows[i]["customerSupplierNo"].ToString();
                        newCsvDataTable.Rows.Add(dr);
                    }
                    return newCsvDataTable;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 从csv文件读取计量点信息
        /// </summary>
        /// <returns></returns>
        private DataTable selectSpotInfo()
        {
            if (System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "baseData") == true
               && System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseSpotInfo.csv") == true)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseSpotInfo.csv";
                DataTable csvDataTable = OpenCSV(path);
                int rowCount = csvDataTable.Rows.Count;
                if (csvDataTable != null && csvDataTable.Rows.Count > 0)
                {
                    DataTable newCsvDataTable = new DataTable();
                    newCsvDataTable.Columns.Add("name");
                    newCsvDataTable.Columns.Add("value");
                    for (int i = 1; i < csvDataTable.Rows.Count; i++)
                    {
                        DataRow dr = newCsvDataTable.NewRow();
                        dr[0] = "[" + csvDataTable.Rows[i]["spotNo"].ToString() + "]" + csvDataTable.Rows[i]["spotName"].ToString();
                        dr[1] = csvDataTable.Rows[i]["spotNo"].ToString();
                        newCsvDataTable.Rows.Add(dr);
                    }
                    return newCsvDataTable;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }
    }
}