using com.hnshituo.core.webapp.vo;
using Common;
using Common.DbOption.work;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TrainVideoDataDispose
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private string m_szRunPath = "";
        private bool m_bRun = true;
        //private bool newRow_Flag = false;
        private DataTable m_dtTrainWeightOrigDataMain;//轨道衡原始数据主表
        private DataTable m_dtTrainWeightOrigData;//轨道衡原始数据表
        private string[] m_szOrigDataPath;//轨道衡共享数据文件夹列表
        private System.Threading.Thread m_hTrainOrigDataCollect;//轨道衡原始数据采集线程

        private MeterWorkRailwayRecMainService meterWorkRailwayRecMainService = new MeterWorkRailwayRecMainService(); // 采集主表
        private MeterWorkRailwayReceivedService MeterWorkRailwayReceivedService = new MeterWorkRailwayReceivedService(); // 采集从表

        /// <summary>
        /// 获取轨道衡系统上传的原始数据文件保存路径
        /// </summary>
        private void GetOrigDataPathInfo()
        {
            try
            {
                //doc:编辑TrainOrigData.txt时要用UTF-8格式保存
                if (System.IO.File.Exists(m_szRunPath + "\\TrainOrigData.txt"))
                {
                    string str = System.IO.File.ReadAllText(m_szRunPath + "\\TrainOrigData.txt", Encoding.Default);
                    m_szOrigDataPath = str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                }
            }
            catch (System.Exception error)
            {
                WriteLog("GetOrigDataPathInfo：" + error.Message);
            }
        }

        /// <summary>
        /// 构建轨道衡原始数据表,客户端获取该表得到最新数据
        /// </summary>
        private void BuildOrigDataTable()
        {
            m_dtTrainWeightOrigDataMain = new DataTable("ORIGDATAMAIN");
            DataColumn dc = new System.Data.DataColumn("SEQUENCENUMBER");//流水号
            m_dtTrainWeightOrigDataMain.Columns.Add(dc);
            dc = new System.Data.DataColumn("WEIGHTTIME");//时间
            m_dtTrainWeightOrigDataMain.Columns.Add(dc);
            dc = new System.Data.DataColumn("POINTNO");//计量编号
            m_dtTrainWeightOrigDataMain.Columns.Add(dc);
            dc = new System.Data.DataColumn("POINTNAME");//计量点
            m_dtTrainWeightOrigDataMain.Columns.Add(dc);
            dc = new System.Data.DataColumn("TOTALCOUNT");//总节数
            m_dtTrainWeightOrigDataMain.Columns.Add(dc);
            dc = new System.Data.DataColumn("VIDEOFILENAME");//录像文件名
            m_dtTrainWeightOrigDataMain.Columns.Add(dc);

            m_dtTrainWeightOrigData = new System.Data.DataTable("ORIGDATADETAIL");

            dc = new System.Data.DataColumn("SEQUENCENUMBER");//流水号
            m_dtTrainWeightOrigData.Columns.Add(dc);
            dc = new System.Data.DataColumn("INDEXNO");//车厢序号
            m_dtTrainWeightOrigData.Columns.Add(dc);
            dc = new System.Data.DataColumn("TRAINNO");//车号
            m_dtTrainWeightOrigData.Columns.Add(dc);
            dc = new System.Data.DataColumn("WEIGHT");//重量
            m_dtTrainWeightOrigData.Columns.Add(dc);
            dc = new System.Data.DataColumn("SPEED");//速度
            m_dtTrainWeightOrigData.Columns.Add(dc);
            dc = new System.Data.DataColumn("POINTNO");//计量编号
            m_dtTrainWeightOrigData.Columns.Add(dc);
            dc = new System.Data.DataColumn("POINTNAME");//计量点
            m_dtTrainWeightOrigData.Columns.Add(dc);
            dc = new System.Data.DataColumn("WEIGHTTIME");//时间
            m_dtTrainWeightOrigData.Columns.Add(dc);
            dc = new System.Data.DataColumn("ISVALID");//是否有效
            m_dtTrainWeightOrigData.Columns.Add(dc);
            dc = new System.Data.DataColumn("RAILWAYWORKNO");//列车作业编号
            m_dtTrainWeightOrigData.Columns.Add(dc);
            dc = new System.Data.DataColumn("RAILWAYMODELNAME");//车型名称
            m_dtTrainWeightOrigData.Columns.Add(dc);
        }

        /// <summary>
        /// 写日志信息到日志文件
        /// </summary>
        /// <param name="str"></param>
        private void WriteLog(string str)
        {
            if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
            {
                System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
            }

            string strDate = System.DateTime.Now.ToString("yyyyMMdd");
            System.IO.TextWriter tw = new System.IO.StreamWriter(m_szRunPath + "\\log\\TrainSceneLogic_" + strDate + ".log", true);

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

            tw.Close();
        }

        private string[] carHeadNo = null;

        private Hashtable hashtable = new Hashtable();//存储称点信息
        private void Form1_Load(object sender, EventArgs e)
        {
            //ldb- 进程已存在，则不重复打开。
            Process[] myProcess = Process.GetProcessesByName(Application.ProductName);
            if (myProcess.Length <= 1)
            {

                m_szRunPath = System.Environment.CurrentDirectory;
                //getBaseCarInfo();

                GetOrigDataPathInfo();
                BuildOrigDataTable();

                //GetUnhandledHistoryData();
                m_hTrainOrigDataCollect = new System.Threading.Thread(new System.Threading.ThreadStart(GetOrigDataFile));
                m_hTrainOrigDataCollect.Start();

            }
            else
            {
                MessageBox.Show("程序已经启动.", "提示");
                Application.Exit();
            }
        }
        /// <summary>
        /// 线程读取原始数据
        /// </summary>
        private void GetOrigDataFile()
        {
            System.Threading.Thread.Sleep(1000);

            // int i = 0;
            string FileContent = "";

            while (m_bRun)
            {
                System.Threading.Thread.Sleep(1000);

                // Create a reference to the current directory.
                foreach (string strPath in m_szOrigDataPath)
                {
                    //读取称点配置信息并存入hashtable
                    hashtable.Clear();
                    //读取配置
                    string[] list = System.Configuration.ConfigurationSettings.AppSettings["spotConfig"].ToString().Split(';');
                    foreach (var item in list)
                    {
                        string path = item.Split(',')[0];
                        string spotNo = item.Split(',')[1];
                        string spotName = item.Split(',')[2];
                        //判断是否为配置信息中的某个
                        if (strPath == path)
                        {
                            hashtable.Add("spotNo", spotNo);
                            hashtable.Add("spotName", spotName);
                        }
                    }
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(strPath);
                    FileInfo[] fis = null;

                    System.IO.DirectoryInfo dicar = new System.IO.DirectoryInfo(strPath + "\\chehao");
                    FileInfo[] fiscar = null;
                    try
                    {
                        FileContent = "";

                        // Create an array representing the files in the current directory.
                        fis = di.GetFiles("*.txt");

                        foreach (FileInfo fi in fis)
                        {
                            //读文件
                            FileContent = System.IO.File.ReadAllText(fi.FullName, Encoding.Default);

                            string strSequenceNumber = System.DateTime.Now.ToString("yyyyMMddHHmmss");

                            if (HandleOrigData(strSequenceNumber, FileContent, strPath) == true)
                            {
                                if (System.IO.Directory.Exists(strPath + "\\history") == false)
                                {
                                    System.IO.Directory.CreateDirectory(strPath + "\\history");
                                }
                                //移到历史文件夹
                                if (System.IO.File.Exists(strPath + "\\history\\" + fi.Name))
                                {
                                    //20181130 原来同名txt文档先备份
                                    if (System.IO.Directory.Exists(strPath + "\\history\\existBak") == false)
                                    {
                                        System.IO.Directory.CreateDirectory(strPath + "\\history\\existBak");
                                    }
                                    System.IO.File.Copy(strPath + "\\history\\" + fi.Name, strPath + "\\history\\existBak" + fi.Name, true);

                                    System.IO.File.Delete(strPath + "\\history\\" + fi.Name);
                                    fi.MoveTo(strPath + "\\history\\" + fi.Name);
                                }
                                else
                                {
                                    fi.MoveTo(strPath + "\\history\\" + fi.Name);
                                }
                                //newRow_Flag = true;
                            }

                            System.Threading.Thread.Sleep(1000);
                        }

                        if (dicar.Exists)
                        {
                            fiscar = dicar.GetFiles("*.txt");
                            foreach (FileInfo fi in fiscar)
                            {
                                //读文件
                                FileContent = System.IO.File.ReadAllText(fi.FullName, Encoding.Default);

                                string strSequenceNumber = System.DateTime.Now.ToString("yyyyMMddHHmmss");

                                if (HandleOrigDatas(strSequenceNumber, FileContent, strPath, fi.Name.Split('c')[0]) == true)
                                {
                                    if (System.IO.Directory.Exists(strPath + "\\history\\chehao") == false)
                                    {
                                        System.IO.Directory.CreateDirectory(strPath + "\\history\\chehao");
                                    }
                                    //移到历史文件夹
                                    if (System.IO.File.Exists(strPath + "\\history\\chehao\\" + fi.Name))
                                    {
                                        System.IO.File.Delete(strPath + "\\history\\chehao\\" + fi.Name);
                                        fi.MoveTo(strPath + "\\history\\chehao\\" + fi.Name);
                                    }
                                    else
                                    {
                                        fi.MoveTo(strPath + "\\history\\chehao\\" + fi.Name);
                                    }
                                    //newRow_Flag = true;
                                }
                                System.Threading.Thread.Sleep(1000);
                            }
                        }
                    }
                    catch (System.Exception error)
                    {
                        WriteLog("GetOrigDataFile:" + error.Message);
                    }
                }
            }
        }

        connection con1 = new connection();
        private bool HandleOrigDatas(string strSequenceNo, string strContent, string strPath, string fileTime)
        {
            string[] Lines = null;
            string[] Fields = null;
            //拆分行
            Lines = strContent.Split(new string[] { "\r\n" }, StringSplitOptions.None);

            if (Lines == null || Lines.Length == 0)
            {
                return false;
            }

            try
            {

                List<string[]> lss = new List<string[]>();
                if (lss.Count == 0)
                {
                    // 默认把空文件处理掉
                    return true;
                }
                for (int i = 0; i < Lines.Length - 1; i++)
                {
                    Fields = Lines[i].Split(',');
                    //================eason update 2019-10-21，增加一个不为9的判断===============
                    if (Fields.Length != 4)
                    {
                        WriteLog("轨道衡车号数据格式不正确！" + Lines[i]);
                        return false;
                    }


                    sModel sm = lm.Where(s => s.key == Fields[1].TrimStart('0').PadLeft(4, '0')).FirstOrDefault();

                    // 写入采集主表

                    // 写入采集从表


                    /*
                    if (sm != null)//车头数据
                    {
                        //若存在数据则将其写入
                        string strSql = "INSERT INTO JL_TRAINOINFO(SEQUENCENUMBER,INDEXNO,TRAINNO,WEIGHTTIME,POINTNAME,IS_HEAD)VALUES"
                                          + "('" + strSequenceNo + "','" + Fields[0] + "','" + sm.value + "',TO_DATE('" + fileTime + "', 'YYYYMMDDHH24MISS'),"
                                          + "'" + Fields[3] + "','1')";

                        OracleCommand ERP_InsertDB = new OracleCommand(strSql, con1.GetDefaultDatabaseConnectionForMain());
                        int ERPint = ERP_InsertDB.ExecuteNonQuery();
                        if (ERPint < 0)
                        {
                            WriteLog("轨道衡车号数据添加失败！");
                            return false;
                        }
                        else
                        {
                            WriteLog(strSequenceNo + "轨道衡车号数据上传成功！");
                        }

                        string strUpdate = "update jl_trainorigdatadetail set ENGINE_NO='" + sm.value + "' where POINTNAME='" + Fields[3] + "' and WEIGHTTIME=TO_DATE('" + fileTime + "', 'YYYYMMDDHH24MISS')";
                        ERP_InsertDB = new OracleCommand(strUpdate, con1.GetDefaultDatabaseConnectionForMain());
                        ERPint = ERP_InsertDB.ExecuteNonQuery();
                        if (ERPint < 0)
                        {
                            WriteLog("轨道衡车号数据更新失败！");
                            return false;
                        }
                        else
                        {
                            WriteLog(strSequenceNo + "轨道衡车号数据更新成功！");
                        }
                    }
                    else
                    {
                        //车厢数据
                        lss.Add(Fields);
                        //若存在数据则将其写入
                        string strSql = "INSERT INTO JL_TRAINOINFO(SEQUENCENUMBER,INDEXNO,TRAINNO,WEIGHTTIME,POINTNAME,IS_HEAD)VALUES"
                                          + "('" + strSequenceNo + "','" + Fields[0] + "','" + Fields[1].TrimStart('0') + "',TO_DATE('" + Fields[2] + "', 'YYYYMMDDHH24MISS'),"
                                          + "'" + Fields[3] + "','0')";

                        OracleCommand ERP_InsertDB = new OracleCommand(strSql, con1.GetDefaultDatabaseConnectionForMain());
                        int ERPint = ERP_InsertDB.ExecuteNonQuery();
                        if (ERPint < 0)
                        {
                            WriteLog("轨道衡车号数据添加失败！");
                            return false;
                        }
                        else
                        {
                            WriteLog(strSequenceNo + "轨道衡车号数据上传成功！");
                        }
                    }
                    */
                }
                return true;
            }
            catch (Exception exp)
            {
                WriteLog("保存数据异常原因！:" + exp.Message);
                return false;
            }
        }

        /// <summary>
        /// 处理轨道衡上传的原始数据
        /// </summary>
        /// <param name="strSequenceNo">流水号，客户端回传应使用该流水号</param>
        /// <param name="strContent">文件内容</param>
        private bool HandleOrigData(string strSequenceNo, string strContent, string strPath)
        {
            string[] Lines = null;
            string[] Fields = null;
            string strWeightTime = "";
            string strPointNo = "";
            string strPointName = "";
            string strVideoFileName = "";
            DataRow dr = null;

            //拆分行
            Lines = strContent.Split(new string[] { "\r\n" }, StringSplitOptions.None);

            if (Lines == null || Lines.Length == 0)
            {
                return false;
            }

            m_dtTrainWeightOrigData.Clear();

            //处理每行
            for (int i = 0; i < Lines.Length - 1; i++)
            {
                Fields = Lines[i].Split(',');
                //================eason update 2019-10-21，增加一个不为9的判断===============
                //if (Fields.Length != 8 && Fields.Length != 9)
                //{
                //    WriteLog("轨道衡数据格式不正确！" + Lines[i]);
                //    return false;
                //}

                dr = m_dtTrainWeightOrigData.NewRow();

                //strSequenceNo = Fields[6]; //20181130增加： 改取现场生成时间 //20181207 取此字段容易主键冲突
                if (dtCarInfo != null && dtCarInfo.Rows.Count > 0)
                {
                    foreach (DataRow drs in dtCarInfo.Rows)
                    {
                        if (drs["CARD_NO"].ToString().TrimStart('0') == Fields[1])
                        {
                            Fields[1] = drs["CAR_NO"].ToString().Trim();
                            break;
                        }
                    }
                }
                if (lm.Where(s => s.value == Fields[1].TrimStart('0').PadLeft(s.value.Length, '0')).Count() > 0)
                {
                    //说明是车头信息
                    continue;
                }

                dr["SEQUENCENUMBER"] = strSequenceNo;
                dr["INDEXNO"] = Fields[1];//车厢号
                dr["RAILWAYMODELNAME"] = Fields[2];//车型
                dr["TRAINNO"] = Fields[3];//车号
                dr["WEIGHT"] = Fields[4];//重量
                dr["RAILWAYWORKNO"] = Fields[8];//列车作业编号
                if (Fields[3] == "")
                {//lck20150109静态过磅时车速处理
                    Fields[3] = "3";
                }
                dr["SPEED"] = Fields[5];//速度
                dr["POINTNO"] = hashtable["spotNo"].ToString();//称点信息
                dr["POINTNAME"] = hashtable["spotName"].ToString();//称点信息
                strPointNo = hashtable["spotNo"].ToString();//称点信息
                strPointName = hashtable["spotName"].ToString();//称点信息
                string _path = strPath.Substring(2);//录像地址
                string _strPath = "\\\\194.168.0.38" + _path;//194.168.0.38//录像地址
                strVideoFileName = _strPath + "\\" + Fields[4];//录像地址
                dr["WEIGHTTIME"] = Fields[6];//时间
                strWeightTime = Fields[6];//时间
                dr["ISVALID"] = "1";//是否有效
                m_dtTrainWeightOrigData.Rows.Add(dr);
            }

            m_dtTrainWeightOrigDataMain.Clear();
            DataRow newRow = m_dtTrainWeightOrigDataMain.NewRow();
            newRow["SEQUENCENUMBER"] = strSequenceNo;
            newRow["WEIGHTTIME"] = strWeightTime;
            newRow["POINTNO"] = strPointNo;
            newRow["POINTNAME"] = strPointName;
            newRow["TOTALCOUNT"] = (Lines.Length - 1).ToString();
            newRow["VIDEOFILENAME"] = strVideoFileName;
            m_dtTrainWeightOrigDataMain.Rows.Add(newRow);

            return SaveOrigData2DB(m_dtTrainWeightOrigDataMain, m_dtTrainWeightOrigData);
        }

        /// <summary>
        /// 保存原始数据
        /// </summary>
        /// <param name="dtMain"></param>
        /// <param name="dtDetail"></param>
        /// <returns></returns>
        private bool SaveOrigData2DB(DataTable dtMain, DataTable dtDetail)
        {
            //Guid trans = Guid.Empty;
            try
            {
                string strError = "";
                //connection con1 = new connection();
                //ArrayList list = new ArrayList();
                //保存从表数据
                foreach (DataRow dr in dtDetail.Rows)
                {
                    MeterWorkRailwayMotorialReceived meterWorkRailwayMotorialReceived = new MeterWorkRailwayMotorialReceived();
                    meterWorkRailwayMotorialReceived.actualFirstNo = dr["SEQUENCENUMBER"].ToString().Trim();//流水号
                    meterWorkRailwayMotorialReceived.baseSpotName = dr["POINTNAME"].ToString().Trim();//称点名称
                    meterWorkRailwayMotorialReceived.baseSpotNo = dr["POINTNO"].ToString().Trim();//称点编号
                    meterWorkRailwayMotorialReceived.railwayNo = dr["TRAINNO"].ToString().Trim();//车号
                    meterWorkRailwayMotorialReceived.railwaySpeed = double.Parse(dr["SPEED"].ToString().Trim());//速度
                    meterWorkRailwayMotorialReceived.valueFlag = dr["ISVALID"].ToString().Trim();//是否有效
                    meterWorkRailwayMotorialReceived.meterWeight = double.Parse(dr["WEIGHT"].ToString().Trim());//重量
                    meterWorkRailwayMotorialReceived.railwayModel = dr["RAILWAYMODELNAME"].ToString().Trim();//车型
                    meterWorkRailwayMotorialReceived.railwayWorkNo = dr["RAILWAYWORKNO"].ToString().Trim();//列车作业编号
                    meterWorkRailwayMotorialReceived.createTime = DateTime.Parse(dr["WEIGHTTIME"].ToString());//时间
                    meterWorkRailwayMotorialReceived.railwayCarriageNo = dr["INDEXNO"].ToString().Trim();//车厢号

                    RESTfulResult<String> rm = MeterWorkRailwayReceivedService.doAdd(meterWorkRailwayMotorialReceived);
                    if (!rm.Succeed)
                    {
                        WriteLog("保存数据异常原因！:" + rm.Message);
                        return false;
                    }

                }
                //保存主表数据
                foreach (DataRow dr in dtMain.Rows)
                {
                    MeterWorkRailwayRecMain meterWorkRailwayRecMain = new MeterWorkRailwayRecMain();
                    meterWorkRailwayRecMain.actualNo = dr["SEQUENCENUMBER"].ToString().Trim();
                    meterWorkRailwayRecMain.baseSpotName = dr["POINTNAME"].ToString().Trim();
                    meterWorkRailwayRecMain.baseSpotNo = dr["POINTNO"].ToString().Trim();
                    meterWorkRailwayRecMain.createTime = DateTime.Now;
                    meterWorkRailwayRecMain.videoName = dr["VIDEOFILENAME"].ToString().Trim();
                    meterWorkRailwayRecMain.carriageNum = int.Parse(dr["TOTALCOUNT"].ToString().Trim());

                    RESTfulResult<String> rm = meterWorkRailwayRecMainService.doAdd(meterWorkRailwayRecMain);
                    if (!rm.Succeed)
                    {
                        WriteLog("保存数据异常原因！:" + rm.Message);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception exp)
            {
                WriteLog("保存数据异常原因！:" + exp.Message);
                return false;
            }
        }

        //每隔一分钟读取一次基础数据
        DataTable dtCarInfo = null;
        private void timer1_Tick(object sender, EventArgs e)
        {
            getBaseCarInfo();
        }

        List<sModel> lm = new List<sModel>();
        private void getBaseCarInfo()
        {
            try
            {
                string sql = "SELECT CARD_NO,CAR_NO,CAR_TYPE FROM CMM_CARD_CAR";

                OracleCommand ERP_InsertDB = new OracleCommand(sql, con1.GetDefaultDatabaseConnectionForMain());
                OracleDataAdapter oda = new OracleDataAdapter();
                oda.SelectCommand = ERP_InsertDB;
                DataSet ds = new DataSet();
                oda.Fill(ds);
                if (ds != null && ds.Tables.Count > 0)
                {
                    dtCarInfo = ds.Tables[0];

                    if (lm.Count == 0)
                    {
                        foreach (DataRow dr in dtCarInfo.Rows)
                        {
                            if (dr["CAR_TYPE"].ToString().Trim() == "1")
                            {
                                lm.Add(new sModel { key = dr["CARD_NO"].ToString(), value = dr["CAR_NO"].ToString() });
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog("读取车号匹配信息异常！:" + ex.Message);
            }
        }
    }

    public class sModel
    {
        public string key { get; set; }
        public string value { get; set; }
    }
}
