using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace CNAS_DBSync
{
    public delegate void ReferenceChangeSyncParamHanlder(SyncInstrumentItemInfo syncInstrumentItem);
    public partial class frmSyncParams : Form
    {
        public List<SyncInstrumentItemInfo> lstSyncInstrument = new List<SyncInstrumentItemInfo>();
        public SyncInstrumentItemInfo currentSyncItem = new SyncInstrumentItemInfo();
        public Dictionary<string, DataTable> dictInstruTables = new Dictionary<string, DataTable>();
        private log4net.ILog log = log4net.LogManager.GetLogger("frmSyncParams");
        private SyncInstrumentItemInfo syncInstrumentItem;
        private string strMode = "";
        public ReferenceChangeSyncParamHanlder ParamsChangedDelegate;

        //public frmSyncParams()
        //{
        //    InitializeComponent();

        //    dgvInstrument.AutoGenerateColumns = false;
        //    dgvInstrument.RowHeadersVisible = false;

        //    dgvInstruDS.AutoGenerateColumns = false;
        //    dgvInstruDS.RowHeadersVisible = false;

        //    dgvCnas.AutoGenerateColumns = false;
        //    dgvCnas.RowHeadersVisible = false;

        //    dgvMapping.AutoGenerateColumns = false;
        //    dgvMapping.RowHeadersVisible = false;
        //}

        public frmSyncParams(SyncInstrumentItemInfo syncInstrumentItem=null)
        {
            InitializeComponent();

            dgvInstrument.AutoGenerateColumns = false;
            dgvInstrument.RowHeadersVisible = false;

            dgvInstruDS.AutoGenerateColumns = false;
            dgvInstruDS.RowHeadersVisible = false;

            dgvCnas.AutoGenerateColumns = false;
            dgvCnas.RowHeadersVisible = false;

            dgvMapping.AutoGenerateColumns = false;
            dgvMapping.RowHeadersVisible = false;
           
            if (syncInstrumentItem != null)
            {
                strMode = "Reference";
                this.syncInstrumentItem = syncInstrumentItem;

                this.btnAdd.Visible = false;
                this.btnDel.Visible = false;
            }
        }

        private void frmSyncParams_Load(object sender, EventArgs e)
        {
            if (syncInstrumentItem == null)
            {//读取本地文件中存储的配置信息
                XmlSerializer serializer = new XmlSerializer(lstSyncInstrument.GetType());
                FileStream stream = new FileStream(FileHelper.getBasePath() + "/Data/SyncInStrumentData.xml", FileMode.Open);
                lstSyncInstrument = (List<SyncInstrumentItemInfo>)serializer.Deserialize(stream);
                stream.Close();
            }
            else
            {
                lstSyncInstrument = new List<SyncInstrumentItemInfo>() { syncInstrumentItem };
            }
            
            
            //绑定数据源，填写相关内容
            if(lstSyncInstrument.Count!=0)
                dgvInstrument.DataSource = new BindingList<SyncInstrumentItemInfo>(lstSyncInstrument);
        }

        /// <summary>
        /// 保存当前设置到本地
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            //将配置好的信息存储到本地文件中
            try
            {
                if (strMode == "Reference")
                {
                    ////使用Linq To XML 直接修改存储，不能直接全部保存，会覆盖其他操作
                    //XDocument doc = XDocument.Load(FileHelper.getBasePath() + "/Data/SyncInStrumentData.xml");
                    //var query = from p in doc.Elements("SyncInstrumentItemInfo")
                    //            where p.Element("GUID").Value == syncInstrumentItem.GUID
                    //            select p;
                    //XElement item = query.SingleOrDefault();
                    //if (item != null)
                    //{

                    //}

                    //1.先加载所有数据  2.替换当前数据  3.重新保存
                    List<SyncInstrumentItemInfo> lstDB = new List<SyncInstrumentItemInfo>();
                    XmlSerializer serializer = new XmlSerializer(lstDB.GetType());
                    FileStream stream = new FileStream(FileHelper.getBasePath() + "/Data/SyncInStrumentData.xml", FileMode.Open);
                    lstDB = (List<SyncInstrumentItemInfo>)serializer.Deserialize(stream);
                    stream.Close();

                    var item = lstDB.Where(p => p.GUID == syncInstrumentItem.GUID).SingleOrDefault();
                    if (item != null)
                    {
                        item = syncInstrumentItem;
                    }
                    else
                    {
                        lstDB.Add(syncInstrumentItem);
                    }

                    TextWriter writer = new StreamWriter(FileHelper.getBasePath() + "/Data/SyncInStrumentData.xml");
                    serializer.Serialize(writer, lstDB);
                    writer.Close();

                    this.ParamsChangedDelegate(syncInstrumentItem);

                }
                else
                {
                    XmlSerializer serializer = new XmlSerializer(lstSyncInstrument.GetType());
                    TextWriter writer = new StreamWriter(FileHelper.getBasePath() + "/Data/SyncInStrumentData.xml");
                    serializer.Serialize(writer, lstSyncInstrument);
                    writer.Close();
                }
                MessageBox.Show("保存成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存失败！错误信息为："+ex.Message.ToString());
            }
            
        }


        /// <summary>
        /// 新增仪器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            frmInstrumentCode frmCode = new frmInstrumentCode(lstSyncInstrument);
            frmCode.InstrumentDelegate = delegate(SyncInstrumentItemInfo Instrumentitem)
            {
                lstSyncInstrument.Add(Instrumentitem);
            };
            frmCode.ShowDialog();

            //绑定数据
            dgvInstrument.DataSource = new BindingList<SyncInstrumentItemInfo>(lstSyncInstrument);
        }


        /// <summary>
        /// 删除仪器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDel_Click(object sender, EventArgs e)
        {
            if (dgvInstrument.Rows.Count <= 0) return;

            //当前选中行
            string strInstrumentCode = this.dgvInstrument.Rows[this.dgvInstrument.CurrentRow.Index].Cells[0].Value.ToString();

            //找到数据源中数据，删除
            var lstitem = lstSyncInstrument.Where(s => s.Code == strInstrumentCode).ToList<SyncInstrumentItemInfo>();
            if (lstitem == null)
                return;
            else if (lstitem.Count >= 1)
            {
                foreach (var item in lstitem)
                {
                    lstSyncInstrument.Remove(item);
                }
            }

            //绑定数据
            dgvInstrument.DataSource = new BindingList<SyncInstrumentItemInfo>();
            dgvInstrument.DataSource = new BindingList<SyncInstrumentItemInfo>(lstSyncInstrument);
        }


        //双击单元格时，触发修改
        private void dgvInstrument_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvInstrument.Rows.Count <= 0) return;

            //当前选中单元格
            string strInstrumentCode = this.dgvInstrument.Rows[this.dgvInstrument.CurrentRow.Index].Cells[0].Value.ToString();

            frmInstrumentCode frmCode = new frmInstrumentCode(lstSyncInstrument, strInstrumentCode);
            frmCode.InstrumentDelegate = delegate (SyncInstrumentItemInfo Instrumentitem)
            {
                var lstInstrument = lstSyncInstrument.Where(s => s.Code == strInstrumentCode).ToList<SyncInstrumentItemInfo>();
                if (lstInstrument.Count == 1)
                {
                    lstInstrument[0].Code = Instrumentitem.Code;
                }
            };  
            frmCode.ShowDialog();

            //绑定数据
            dgvInstrument.DataSource = new BindingList<SyncInstrumentItemInfo>(lstSyncInstrument);
        }


        private void dgvInstrument_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvInstrument.Rows.Count <= 0) return;
            if (dgvInstrument.Rows[dgvInstrument.CurrentRow.Index].Cells[0].Value == null) return;

            //当前选中单元格
            string strInstrumentCode = this.dgvInstrument.Rows[this.dgvInstrument.CurrentRow.Index].Cells[0].Value.ToString();
            var lstInstrument = lstSyncInstrument.Where(s => s.Code == strInstrumentCode).ToList<SyncInstrumentItemInfo>();
            if (lstInstrument.Count == 1)
            {
                currentSyncItem = lstInstrument[0];

                if (currentSyncItem.SyncInstrumentDSInfo != null&& currentSyncItem.SyncInstrumentDSInfo.InstrumentDataSourceType!=DataSourceType.None)
                {                    
                    dgvMapping.DataSource = new BindingList<SyncParamasInfo>(currentSyncItem.LstSyncPramas);
                }
                else
                {
                    cbxCnas.DataSource = null;
                    cbxInstrument.DataSource = null;

                    dgvInstruDS.DataSource = null;
                    dgvCnas.DataSource = null;
                    dgvMapping.DataSource = new BindingList<SyncParamasInfo>();
                }
            }
            else
            {
                cbxCnas.DataSource = null;
                cbxInstrument.DataSource = null;

                dgvInstruDS.DataSource = null;
                dgvCnas.DataSource = null;
                dgvMapping.DataSource =new BindingList<SyncParamasInfo>();
            }
        }
        /// <summary>
        /// 切换选中表时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxInstrument_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbxInstrument.SelectedValue == null) return;

            string strTableName_Instru = cbxInstrument.SelectedValue.ToString();
            if (dictInstruTables.ContainsKey(strTableName_Instru))
            {
                DataTable dt = dictInstruTables[strTableName_Instru];
                if (dt != null && dt.Rows.Count > 0)
                {
                    //DataRow drColumn = dt.Rows[0];    //第一行是列名

                    DataTable dtInstruShow = new DataTable();
                    dtInstruShow.Columns.Add("InstruFieldName");
                    dtInstruShow.Columns.Add("InstruDataType");
                    //foreach (DataColumn dc in dt.Columns)
                    //{
                    //    dtInstruShow.Rows.Add(new object[] { drColumn[dc.ColumnName] });
                    //}

                    foreach (DataColumn dc in dt.Columns)
                    {
                        dtInstruShow.Rows.Add(new object[] { dc.ColumnName,dc.DataType});
                    }

                    dgvInstruDS.DataSource = dtInstruShow;
                }
            }
        }

        /// <summary>
        /// 切换表时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxCnas_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbxCnas.Text == null) return;

            string strTableName_Cnas = cbxCnas.Text.ToString();
            //从数据库中加载数据表结构
            //DataTable dtTableStruct = SQLDB2Helper.getDB2Table(string.Format("SELECT * FROM {0} Where 1=0", strTableName_Cnas));

            DataTable dtTableStruct = CnasDataOperationFact.CnasDataOperation().GetCNASTablesStruct(strTableName_Cnas,currentSyncItem);
            if (dtTableStruct != null)
            {
                DataTable dtCnasShow = new DataTable();
                dtCnasShow.Columns.Add("CnasFieldName");
                dtCnasShow.Columns.Add("CnasDataType");
                foreach (DataColumn dc in dtTableStruct.Columns)
                {
                    dtCnasShow.Rows.Add(new object[] { dc.ColumnName ,dc.DataType});
                }

                dgvCnas.DataSource = dtCnasShow;
            }
        }

        //增加映射
        private void btnAddMapping_Click(object sender, EventArgs e)
        {
            if (cbxInstrument.SelectedValue == null) return;
            if (cbxCnas.SelectedValue == null) return;
            if (dgvInstruDS.Rows.Count <= 0) return;
            if (dgvCnas.Rows.Count <= 0) return;

            SyncParamasInfo syncParamas = new SyncParamasInfo();
            if (currentSyncItem.LstSyncPramas == null) currentSyncItem.LstSyncPramas = new List<SyncParamasInfo>();

            //检测选中表是否跟已有映射数据一致，如果不一致，则不允许继续

            var lst = currentSyncItem.LstSyncPramas.Where(s=>s.SourceTable== cbxInstrument.SelectedValue.ToString()&&s.TargetTable== cbxCnas.SelectedValue.ToString()).ToList<SyncParamasInfo>();
            if (currentSyncItem.LstSyncPramas.Count > 0 && lst.Count <= 0)
            {
                MessageBox.Show("已存在不同表单映射数据，无法添加！");
                return;
            }

            //检测是否已经存在这个数据（不允许存在重复数据）
            lst = currentSyncItem.LstSyncPramas.Where(s => s.SourceField == dgvInstruDS.Rows[dgvInstruDS.CurrentCell.RowIndex].Cells[0].Value.ToString()&&s.SourceTable== cbxInstrument.SelectedValue.ToString()).ToList<SyncParamasInfo>();
            if (lst.Count > 0)
            {
                MessageBox.Show("仪器数据库字段已分配，请重新选择！");
                return;
            }
            lst = currentSyncItem.LstSyncPramas.Where(s => s.TargetTable == cbxCnas.SelectedValue.ToString() && s.TargetField == dgvCnas.Rows[dgvCnas.CurrentCell.RowIndex].Cells[0].Value.ToString()).ToList<SyncParamasInfo>();
            if (lst.Count > 0)
            {
                MessageBox.Show("CNAS数据库字段已分配，请重新选择！");
                return;
            }
            if (dgvCnas.Rows[dgvCnas.CurrentCell.RowIndex].Cells[0].Value.ToString().ToUpper() == "ID")
            {
                MessageBox.Show("该字段为CNAS数据库保留字段，不允许插入数据，请重新选择！");
                return;
            }

            //仪器表名和选中行
            syncParamas.SourceTable = cbxInstrument.SelectedValue.ToString();
            syncParamas.SourceField = dgvInstruDS.Rows[dgvInstruDS.CurrentCell.RowIndex].Cells[0].Value.ToString();

            //CNAS表名和选中行
            syncParamas.TargetTable = cbxCnas.SelectedValue.ToString();
            syncParamas.TargetField = dgvCnas.Rows[dgvCnas.CurrentCell.RowIndex].Cells[0].Value.ToString();

            //绑定数据
            if (currentSyncItem.LstSyncPramas == null) currentSyncItem.LstSyncPramas = new List<SyncParamasInfo>();

            currentSyncItem.LstSyncPramas.Add(syncParamas);

            dgvMapping.DataSource= new BindingList<SyncParamasInfo>(currentSyncItem.LstSyncPramas);
        }

        /// <summary>
        /// 删除映射
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelMap_Click(object sender, EventArgs e)
        {
            //当前选中项
            string strSourceField = dgvMapping.Rows[dgvMapping.CurrentCell.RowIndex].Cells["InstrumentField"].Value.ToString();
            string strTargetField = dgvMapping.Rows[dgvMapping.CurrentCell.RowIndex].Cells["CnasField"].Value.ToString();

            var lstDelItems = currentSyncItem.LstSyncPramas.Where(s => s.SourceField == strSourceField && s.TargetField == strTargetField).ToList<SyncParamasInfo>();
            if (lstDelItems.Count > 0)
            {
                foreach (var item in lstDelItems)
                {
                    currentSyncItem.LstSyncPramas.Remove(item);
                }

                dgvMapping.DataSource = new BindingList<SyncParamasInfo>(currentSyncItem.LstSyncPramas);
            }
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            ////根据映射字段获取准备上传的所有数据
            //if (!dictInstruTables.ContainsKey(currentSyncItem.LstSyncPramas[0].SourceTable)) return;

            //DataTable dtReadySource = dictInstruTables[currentSyncItem.LstSyncPramas[0].SourceTable];
            //if (dtReadySource == null || dtReadySource.Rows.Count <= 0) return;

            ////构建准备插入的数据
            //DataTable dtTarget = CnasDataOperationFact.CnasDataOperation().GetCNASTablesStruct(currentSyncItem.LstSyncPramas[0].TargetTable,currentSyncItem);

            //foreach (DataRow drSource in dtReadySource.Rows)
            //{
            //    DataRow drNewTarget = dtTarget.NewRow();

            //    //遍历映射表，把所有字段插入到目标表中
            //    foreach (var item in currentSyncItem.LstSyncPramas)
            //    {
            //        var strSourceField = item.SourceField;
            //        var strTargetField = item.TargetField;

            //        //当列名存在于数据表中时才能继续
            //        if (dtReadySource.Columns.Contains(strSourceField) && dtTarget.Columns.Contains(strTargetField))
            //        {
            //            drNewTarget[strTargetField] = drSource[strSourceField];
            //        }
            //    }

            //    dtTarget.Rows.Add(drNewTarget);
            //}

            ////执行插入
            //int iReturn = CnasDataOperationFact.CnasDataOperation().InsertDataToCNASTable(dtTarget, currentSyncItem);

            //if (iReturn>0)
            //    MessageBox.Show("上传完成！");
            //else
            //    MessageBox.Show("上传过程中发生异常，请联系管理员！");
        }

        /// <summary>
        /// 配置数据库界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDatabaseConfig_Click(object sender, EventArgs e)
        {
            frmDatabaseParams frmDatabase = new frmDatabaseParams(currentSyncItem);
            frmDatabase.InstrumentDelegate = delegate (SyncInstrumentItemInfo Instrumentitem)
            {
                this.currentSyncItem = Instrumentitem;              
            };
            frmDatabase.InstrumentItemData = delegate (Dictionary<string, DataTable> dict)
              {
                  this.dictInstruTables = dict;
              };

            frmDatabase.ShowDialog();

            LoadSourceAndTargetData();
        }

        private void btnLoadDBData_Click(object sender, EventArgs e)
        {
            int iReturn=LoadSourceAndTargetData(true);
            switch (iReturn)
            {
                case -1:
                    MessageBox.Show("未能成功获取仪器数据库配置信息，请配置后重试！");
                    break;
                case -2:
                    MessageBox.Show("未能成功获取CNAS数据库配置信息，请配置后重试！");
                    break;
                case -3:
                    MessageBox.Show("未能成功获取仪器数据信息，请配置后重试！");
                    break;
                case -4:
                    MessageBox.Show("未能成功获取CNAS数据信息，请配置后重试！");
                    break;
                default:
                    break;
            }
        }

        public int LoadSourceAndTargetData(bool bIfLoading=false)
        {
            //检查配置信息
            if (currentSyncItem.SyncInstrumentDSInfo == null || currentSyncItem.SyncInstrumentDSInfo.LocalPath ==null|| currentSyncItem.SyncInstrumentDSInfo.LocalPath == "") return -1;
            if (currentSyncItem.SyncTargetDBInfo == null) return -2;

            //是否需要重新加载来源库
            if (bIfLoading)
            {
                if (currentSyncItem.SyncInstrumentDSInfo.LocalPath != null && currentSyncItem.SyncInstrumentDSInfo.LocalPath != "")
                {
                    InstrumentData instrumentData = InstrumentDataFact.CreateInstrumentDataSource(currentSyncItem.SyncInstrumentDSInfo.InstrumentDataSourceType, new object[] { currentSyncItem.SyncInstrumentDSInfo.LocalPath, currentSyncItem.SyncInstrumentDSInfo.UserId, currentSyncItem.SyncInstrumentDSInfo.UserPwd });
                    dictInstruTables = instrumentData.GetInstrumentData();
                }
            }
            if (dictInstruTables.Count <= 0) return -3;

            //绑定ComboBox
            List<string> lstTableName = new List<string>();
            foreach (var item in dictInstruTables)
            {
                lstTableName.Add(item.Key);
            }

            cbxInstrument.DataSource = lstTableName;
            cbxInstrument.ValueMember = "";

            //获取CNAS配置的数据库连接信息         
            DataTable dtCNAS = CnasDataOperationFact.CnasDataOperation().GetAllCNASTablesName(currentSyncItem);
            if (dtCNAS != null && dtCNAS.Rows.Count > 0)
            {
                List<string> lstCnasTables = new List<string>();
                foreach (DataRow dr in dtCNAS.Rows)
                {
                    lstCnasTables.Add(dr["TABNAME"].ToString());
                }

                cbxCnas.DataSource = lstCnasTables;
                cbxCnas.ValueMember = "";
            }
            else
                return -4;
            return 1;
        }
    }
}
