//时间：20200610
//作者：郝爽
//功能：测量文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using FileManager;
using System.Xml;
using System.IO;
using System.Drawing;

namespace MeasureData
{

    public class MeasureFile : ISlo
    {
        public const string UNTITLED_FILE_NAME = "Untitled";
        public string m_SavePath = "";
        #region 内容
        //文件名
        private string m_fileName;
        public string FileName
        {
            get { return this.m_fileName; }
            set { this.m_fileName = value; }
        }

        //文件路径
        private string m_filepath;
        public string FilePath
        {
            get { return this.m_filepath; }
            set { this.m_filepath = value; }
        }

        //切孔文件路径
        private string m_CutHoleFilePath;
        public string CutHoleFilePath
        {
            get { return this.m_CutHoleFilePath; }
            set { this.m_CutHoleFilePath = value; }
        }

        //切孔链表
        private List<CutHole> m_listCutHole;
        public List<CutHole> ListCutHole
        {
            get { return this.m_listCutHole; }
            set { this.m_listCutHole = value; }
        }

        //测量参数
        private MeasureParam m_measureParam;
        public MeasureParam MParam
        {
            get { return this.m_measureParam; }
            set { this.m_measureParam = value; }
        }

        //是否需要保存文件
        private bool m_IsModified;
        public bool IsModified
        {
            get { return this.m_IsModified; }
            set { this.m_IsModified = value; }
        }
        #endregion
        /// <summary>
        /// 创建XML文件
        /// </summary>
        /// <returns></returns>
        public bool CreateXml()
        {
            if (File.Exists(this.FileName))
            {
                return true;
            }
            else
            {
                //重新创建
                XmlManager.CreateXmlFile(this.FileName);
                return true;
            }
        }

        //XML文件保存
        //样品孔存储xml文档
        public override void Serialize(bool isStoring, XmlDocument xml, XmlNode rootNode)
        {
            Slo sFile = new Slo();
            Slo sParam = new Slo();
            Collection<CutHole> sCutHoles = new Collection<CutHole>();

            foreach (CutHole hole in ListCutHole)
            {
                sCutHoles.addItem(hole);
            }

            xString FileName = new xString();
            xString FilePath = new xString();
            FileName.AssignValue(this.FileName);
            FilePath.AssignValue(this.FilePath);
            sFile.Register("FileName", FileName);
            sFile.Register("FilePath", FilePath);
            sFile.Register("Param", this.MParam);
            sFile.Register("ListCutHole", sCutHoles);

            if (isStoring)
            {
                sFile.Serialize(true, xml, rootNode);
            }
            else
            {
                sFile.Serialize(false, xml, rootNode);

                this.FileName = FileName.value();
                this.FilePath = FilePath.value();
                List<CutHole> tempCutHoleList = new List<CutHole>();
                for (int i = 0; i < sCutHoles.size(); i++)
                {
                    tempCutHoleList.Add(sCutHoles.getItem(i));
                }
                if (tempCutHoleList.Count == sCutHoles.size())
                {
                    ListCutHole.Clear();
                    ListCutHole = tempCutHoleList;
                }
            }
        }

        //构造函数
        public MeasureFile()
        {
            Init();
        }

        public void Init()
        {
            this.ListCutHole = new List<CutHole>();
            this.FileName = @"";
            this.FilePath = @"";
            this.MParam = new MeasureParam();
        }
        #region 操作

        //新建
        public bool New()
        {
             CreateXml();
           
                XmlDocument doc = new XmlDocument();
                doc.Load(this.FileName);//载入xml文件

                XmlNode root = doc.SelectSingleNode("XMLData");

                Serialize(true, doc, root);

                doc.Save(this.FileName);
          

            // 设置路径为初始默认路径
            this.FileName = UNTITLED_FILE_NAME;
            this.IsModified = false;
            // Ok, return TRUE
            return true;
        }

        //打开
        public void Open()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(this.FileName);//载入xml文件

            XmlNode root = doc.SelectSingleNode("XMLData");

            Serialize(false, doc, root);

            this.IsModified = false;

            doc.Save(this.FileName);
        }

        //保存
        public bool Save()
        {
            //没有修改不需要重新保存文件
            if (this.IsModified == false)
            {
                return true;
            }

            //如果是新文件
            this.FileName.Trim();
            if (this.FileName == "Untitled")
            {
                return true;
            }
      

           
            CreateXml();

            XmlDocument doc = new XmlDocument();
            doc.Load(this.FileName);//载入xml文件   
          

            XmlNode root = doc.SelectSingleNode("XMLData");
            Serialize(true, doc, root);
            doc.Save(this.FileName);
            return true;
        }

        //另存为
        public bool SaveAs()
        {
       

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "保存测量文件";
            sfd.InitialDirectory = @"D:\FIB_AUTO\";
            sfd.Filter = "测量文件（*.msf）|*.msf";

            

            if (sfd.ShowDialog() == DialogResult.OK)
            {

                this.FileName = sfd.FileName.ToString(); //获得文件路径
                m_SavePath = Convert.ToString(this.FileName);
                FilePath = System.IO.Path.GetDirectoryName(this.FileName);

                //创建一个新的文件
                XmlDocument doc = new XmlDocument();
                CreateXml();
               
                doc.Load(this.FileName);
                XmlNode root = doc.SelectSingleNode("XMLData");
                Serialize(true, doc, root);
                doc.Save(this.FileName);
                return true;
            }
            else
            {
                return false;
            }
        }

        //从文件生成切割孔信息
        public bool GetCutHolesFromFile(string a_FilePathName)
        {
            try
            {
                //清空原文件中的切孔
                this.ListCutHole.Clear();

                //弹出打开txt文件的对话矿
                a_FilePathName.Trim();
                if (string.IsNullOrEmpty(a_FilePathName))
                {
                    //新建一个文件对话框
                    OpenFileDialog pOpenFileDialog = new OpenFileDialog();
                    //设置对话框标题
                    pOpenFileDialog.Title = "打开电镜位置列表文件";
                    //设置打开文件类型
                    pOpenFileDialog.Filter = "txt文件（*.txt）|*.txt";
                    //文件打开路径
                    pOpenFileDialog.InitialDirectory = @"\\192.168.1.101\Service";
                    //监测文件是否存在
                    pOpenFileDialog.CheckFileExists = true;
                    //文件打开后执行以下程序
                    if (pOpenFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        a_FilePathName = System.IO.Path.GetFullPath(pOpenFileDialog.FileName);
                        //绝对路径
                        CutHoleFilePath = a_FilePathName;

                    }
                }

                //按行取出txt文件
                string[] lines = File.ReadAllLines(a_FilePathName, System.Text.Encoding.Default);

                LogManager.AddHardwareLog("read " + lines.Count().ToString() + "lines", true);
                //按现有的文件格式生成
                string posMode = lines[1];
                if (posMode.CompareTo(@"Absolute") != 0)
                {
                    return false;
                }

                //解析切孔生成带有位置的切孔
                //验证数量是否正确
                int nNum = Convert.ToInt32(lines[3]);
                int nLines = lines.Length;
                if (nNum != (lines.Length - 4))
                {
                    return false;
                }

                //行内标识的个数及位置
                string[] titles = lines[2].Split(',');
                int numPos = titles.Length;

                int nLabelPos = Array.IndexOf(titles, "Label");
                int nXPos = Array.IndexOf(titles, "X");
                int nYPos = Array.IndexOf(titles, "Y");
                int nZPos = Array.IndexOf(titles, "Z");
                int nTPos = Array.IndexOf(titles, "T");
                int nRPos = Array.IndexOf(titles, "R");
                int nMPos = Array.IndexOf(titles, "M");
                int nWDPos = Array.IndexOf(titles, "WD");

                for (int i = 0; i < nNum; i++)
                {
                    int currentLine = i + 4;
                    string currentString = lines[currentLine];

                    LogManager.AddHardwareLog(currentString, true);

                    string[] CurrentPos = currentString.Split(',');
                    int nCurrentPosNum = CurrentPos.Length;

                    //当前行内的标识及位置个数不够
                    if (nCurrentPosNum != numPos)
                    {
                        return false;
                    }

                    //切孔标识
                    CutHole CHole = new CutHole();
                    CHole.HoleName = CurrentPos[nLabelPos];
                    //切孔位置
                    SemPosition holePos = new SemPosition();
                    holePos.X = Convert.ToSingle(CurrentPos[nXPos]);
                    holePos.Y = Convert.ToSingle(CurrentPos[nYPos]);
                    holePos.Z = Convert.ToSingle(CurrentPos[nZPos]);
                    holePos.M = Convert.ToSingle(CurrentPos[nMPos]);
                    holePos.T = Convert.ToSingle(CurrentPos[nTPos]);
                    holePos.R = Convert.ToSingle(CurrentPos[nRPos]);
                    holePos.WD = Convert.ToSingle(CurrentPos[nWDPos]);

                    CHole.Position = holePos;
                    //默认切割点均参与测试
                    CHole.SWITCH = true;

                    //更新切孔链表
                    this.ListCutHole.Add(CHole);
                    LogManager.AddHardwareLog("X =" + CurrentPos[nXPos]
                        + "Y =" + CurrentPos[nYPos]
                        + "Z =" + CurrentPos[nZPos]
                        + "M =" + CurrentPos[nTPos]
                        + "T =" + CurrentPos[nRPos]
                        + "R =" + CurrentPos[nMPos]
                        , true);

                }

                this.IsModified = true;

                return true;
            }
            catch (Exception ex)
            {
                LogManager.LogError(ex.Message);
                return false;
            }
        }

        //从点集合对象中生成切割孔信息
        public bool GetCutHolesFromAnalysisPosition(List<PointF> cutHolePointF)
        {
            //集合中的数量
            int nNum = Convert.ToInt32(cutHolePointF.Count);
            if (nNum == 0)
            {
                return false;
            }
            else
            {
                List<CutHole> tempCutHoleList = new List<CutHole>();
                for (int i = 0; i < nNum; i++)
                {
                    //切孔标识
                    CutHole CHole = new CutHole();
                    CHole.HoleName = (i + 1).ToString();
                    //切孔位置
                    SemPosition holePos = new SemPosition();
                    holePos.X = Convert.ToSingle(cutHolePointF[i].X);
                    holePos.Y = Convert.ToSingle(cutHolePointF[i].Y);
                    holePos.Z = Convert.ToSingle(0);
                    holePos.M = Convert.ToSingle(0);
                    holePos.T = Convert.ToSingle(0);
                    holePos.R = Convert.ToSingle(0);
                    CHole.Position = holePos;
                    //默认切割点均参与测试
                    CHole.SWITCH = true;

                    //更新切孔链表
                    tempCutHoleList.Add(CHole);
                    LogManager.AddHardwareLog("X =" + cutHolePointF[i].X
                        + "Y =" + cutHolePointF[i].Y
                        + "Z =" + 0
                        + "M =" + 0
                        + "T =" + 0
                        + "R =" + 0
                        , true);
                }
                if (tempCutHoleList.Count > 0)
                {
                    this.ListCutHole.Clear();
                    this.ListCutHole = tempCutHoleList;
                }
            }
            return true;
        }
        #endregion
    }
}
