using System;
using System.Collections.Generic;
using System.Text;
using ICommLayer;
using DBFactory;
using System.Data;
using Microsoft.VisualBasic;
namespace SimensProdave6
{
    public class CSendDeviceOrder:ISendDeviceOrder
    {
        string _commLayerError;

        public string CommLayerError
        {
            get { return _commLayerError; }
            set { _commLayerError = value; }
        }
        DBOperator dbo = CSimensProdave6_S7.dbo;
        public CSendDeviceOrder()
        {
            dbo.Open();
        }
        /// <summary>
        /// 发送堆垛机命令
        /// </summary>
        /// <param name="MessageIndex">消息编号</param>
        /// <param name="TaskIndex">任务编号</param>
        /// <param name="Order">堆垛机命令字</param>
        ///1-复位 
        ///2-将取 
        ///3-将送
        ///4-取货
        ///5-放货
        ///6-取放货
        /// <param name="DeviceIndex">设备编号</param>
        /// <param name="StartX">起始x坐标，排-沿轨道方向</param>
        /// <param name="StartY">起始y坐标，层-高度方向</param>
        /// <param name="StartZ">起始z坐标，列-面向堆垛机操作面板，1-左侧，2-右侧</param>
        /// <param name="EndX">目标x坐标，列-沿轨道方向</param>
        /// <param name="EndY">目标y坐标，层-高度方向</param>
        /// <param name="EndZ">目标z坐标，排-面向堆垛机操作面板，1-左侧，2-右侧</param>
        /// <returns>发送堆垛机命令是否成功</returns>
        public bool SendDeviceOrder(int MessageIndex, int TaskIndex, int Order, int DeviceIndex, int StartX, int StartY, int StartZ, int EndX, int EndY, int EndZ)
        {
            try
            {
                int sn = 0;
                Model.MDevice devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIndex);
                //DataView dv = dbo.ExceSQL("SELECT F_DBW1Address,F_DBWSendLength,F_DeviceIndex,F_DeviceKindIndex,F_OPCProgID, F_RemoteIP FROM T_Base_Device where F_DeviceIndex=" + DeviceIndex).Tables[0].DefaultView;
                if (devinfo.DeviceIndex == 0)
                {
                    _commLayerError = "SimensProdave6.CSendDeviceOrder.SendDeviceOrder发生错误：在设备表中没找到设备所引！";
                    return false;
                }
                else
                {
                    if ((devinfo.DeviceKind.ToString() != "1") )
                    {//堆垛机使用此方法
                        _commLayerError = "SimensProdave6.CSendDeviceOrder.SendDeviceOrder发生错误：堆垛机和RGV以外的设备使用此方法不正确!";
                        return false;
                    }
                    #region 堆垛机
                    
                    if (devinfo.DeviceKind.ToString() == "1")
                    {
                        byte[] wdata = new byte[10];
                        sn = Convert.ToInt32(devinfo.Dbw1Address);
                        wdata[0] =(byte) MessageIndex;
                        wdata[1] = (byte)Order;
                        wdata[2] = (byte)(TaskIndex>>8);
                        wdata[3] = (byte)(TaskIndex & 255);
                        if (MessageIndex == 1)
                        {
                            wdata[4] = (byte)(StartX + 1);
                        }
                        else
                        {
                            wdata[4] = (byte)StartX;
                        }
                        wdata[5] = (byte)StartY;
                        wdata[6] = (byte)StartZ;
                        if (MessageIndex == 1)
                        {
                            wdata[7] = (byte)(EndX + 1);
                        }
                        else
                        {
                            wdata[7] = (byte)EndX;
                        }
                        //wdata[7] = (byte)EndX;
                        wdata[8] = (byte)EndY;
                        wdata[9] = (byte)EndZ;
                        if (CSimensProdave6_S7.DB_Write_Prodave(0, 1, Convert.ToUInt16(sn), Convert.ToUInt32(devinfo.Dbw1SendLength), wdata) == false)
                        {
                            _commLayerError = "SimensProdave6.CSendDeviceOrder.SendDeviceOrder发生错误：" + CSimensProdave6_S7.ErrorsText;
                            return false;
                        }
                        if (WriteBarcode(DeviceIndex, TaskIndex) == false)
                        {
                            return false;
                        }
                    }

                    #endregion
                   
                }
                return true;
            }
            catch (Exception ex)
            {
                _commLayerError = "SimensProdave6.CSendDeviceOrder.SendDeviceOrder发生错误：" + ex.Message;
                return false;
            }
            
        }
        /// <summary>
        /// 发送穿梭车、输送机设备命令
        /// </summary>
        /// <param name="MessageIndex">消息编号</param>
        /// <param name="TaskIndex">任务编号</param>
        /// <param name="Order">命令字</param>
        /// 穿梭车命令字： 
        ///1-复位 
        ///2-左接货
        ///3-左送货
        ///4-右接货
        ///5-右送货
        ///6-停止
        ///7-运动（运动到第4、5字节指定的目标设备所引）
        ///输送机命令字：
        ///1-入库（朝向库）
        ///2-出库（背向库）
        ///3-送货
        ///4-接货
        ///5-停止
        /// <param name="DeviceIndex">设备编号</param>
        ///<param name="ArrowDeviceIndex">对于输送机、穿梭车代表目标设备所引，
        /// 0-代表单一设备控制，无目标设备所引；1…65535代表目标设备所引（终点输送机的设备所引）</param>
        /// <returns>发送穿梭车、输送机设备命令是否成功</returns>
        public bool SendDeviceOrder(int MessageIndex, int TaskIndex, int Order, int DeviceIndex, int ArrowDeviceIndex)
        {
            try
            {
                string[] itemnames = new string[4];
                string[] itemvalues = new string[4];
                int sn = 0;
                Model.MDevice devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIndex);
                //DataView dv = dbo.ExceSQL("SELECT F_DBW1Address,F_DBWSendLength,F_DeviceIndex,F_DeviceKindIndex,F_OPCProgID, F_RemoteIP FROM T_Base_Device where F_DeviceIndex=" + DeviceIndex).Tables[0].DefaultView;
                if (devinfo.DeviceIndex == 0)
                {
                    _commLayerError = "SimensProdave6.CSendDeviceOrder.SendDeviceOrder发生错误：设备索引不存在!";
                    return false;
                }
                else
                {
                    if (devinfo.DeviceKind.ToString() == "7")
                    {
                        return true;
                    }
                    if ((devinfo.DeviceKind.ToString() == "1") )
                    {//堆垛机不允许使用此方法
                        _commLayerError = "SimensProdave6.CSendDeviceOrder.SendDeviceOrder发生错误：堆垛机和RGV不允许使用此方法!";
                        return false;
                    }
                    byte[] wdata = new byte[6];
                    sn = Convert.ToInt32(devinfo.Dbw1Address);
                    wdata[0] = (byte)MessageIndex;
                    wdata[1] = (byte)Order;
                    wdata[2] = (byte)(TaskIndex >> 8);
                    wdata[3] = (byte)(TaskIndex & 255);
                    wdata[4] = (byte)(ArrowDeviceIndex >> 8);
                    wdata[5] = (byte)(ArrowDeviceIndex & 255);
                    if (CSimensProdave6_S7.DB_Write_Prodave(0, 1, Convert.ToUInt16(sn), Convert.ToUInt32(devinfo.Dbw1SendLength), wdata) == false)
                    {
                        _commLayerError = "SimensProdave6.CSendDeviceOrder.SendDeviceOrder发生错误：" + CSimensProdave6_S7.ErrorsText;
                        return false;
                    }
                    byte[] www = new byte[6];
                    Array.Copy(wdata, www, 6);
                    CommonClassLib.CCarryConvert.WriteDarkCasket("SimensProdave6", "SendDeviceOrder", DeviceIndex.ToString(), www);
                    if (WriteBarcode(DeviceIndex, TaskIndex) == false)
                    {
                        return false;
                    }
                    
                }
                return true;
            }
            catch (Exception ex)
            {
                _commLayerError = "SimensProdave6.CSendDeviceOrder.SendDeviceOrder发生错误：" + ex.Message;
                return false;
            }
           
        }
        /// <summary>
        /// 上位机给下位机发送烟箱按品牌码分道信息共15字节,有数据时写入实际数据，否则全部写零
        /// </summary>
        /// <param name="DeviceIndex">码垛位设备号索引</param>
        /// <param name="TobaccoCode">第1--13字节,烟箱码</param>
        /// <param name="HaveFirstProjectCode">第14字节,1-有一号工程码,0-无一号工程码</param>
        /// <param name="IfSmallTobacco">第15字节,1-小烟箱,0-正常烟箱</param>
        /// <returns>发送烟箱按品牌码分道信息是否成功</returns>
        public bool SendDeviceOrder(int DeviceIndex, string TobaccoCode, bool HaveFirstProjectCode, bool IfSmallTobacco,int Count)
        {
            try
            {
                byte[] wdata = new byte[15];
                Model.MDevice devinfo = Model.CGetInfo.GetDeviceInfo(DeviceIndex);
                //DataView dv = dbo.ExceSQL("SELECT F_DBW1Address,F_DBWSendLength,F_DeviceIndex,F_DeviceKindIndex,F_OPCProgID, F_RemoteIP FROM T_Base_Device where F_DeviceIndex=" + DeviceIndex).Tables[0].DefaultView;
                if (devinfo.DeviceIndex == 0)
                {
                    _commLayerError = "SimensProdave6.CSendDeviceOrder.SendDeviceOrder发生错误：设备所引不存在!";
                    return false;
                }
                else
                {
                    for (int i = 0; i < 13; i++)
                    {
                        wdata[i]=(byte)Strings.Asc(TobaccoCode.Substring(i,1));
                    }

                    if (HaveFirstProjectCode == true)
                    {
                        wdata[13] = 1;
                    }
                    else
                    {
                        wdata[13] = 0;
                    }
                    if (IfSmallTobacco == true)
                    {
                        wdata[14] = 1;
                    }
                    else
                    {
                        wdata[14] = 1;
                    }

                    if (CSimensProdave6_S7.DB_Write_Prodave(0, 1, Convert.ToUInt16(devinfo.Dbw1Address), Convert.ToUInt32(devinfo.Dbw1SendLength), wdata) == false)
                    {
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                _commLayerError = "SimensProdave6.CSendDeviceOrder.SendDeviceOrder发生错误：" + ex.Message;
                return false;
            }
        }
        bool WriteBarcode(int deviceindex,int taskindex)
        {
            string barcode="";
            byte[] wdata = new byte[11];
            DataView dvb = dbo.ExceSQL("SELECT F_MonitorIndex, F_TxtParam FROM T_Monitor_Task WHERE (F_MonitorIndex = "+taskindex +")").Tables[0].DefaultView;
            if (dvb.Count > 0)
            {
                barcode = dvb[0]["F_TxtParam"].ToString();
                if (barcode == "-") return true;
            }
            else
            {
                _commLayerError = "SimensProdave6.CSendDeviceOrder.SendDeviceOrder发生错误：写入附加条码时在调度任务表内没找到条码!";
                return false;
            }
            Model.MDevice devinfo = Model.CGetInfo.GetDeviceInfo(deviceindex);
            
            //DataView dv0 = dbo.ExceSQL("SELECT F_AppendBarcode, F_DeviceIndex FROM T_Base_Device WHERE (F_AppendBarcode <>-1) AND (F_DeviceIndex = "+deviceindex +")").Tables[0].DefaultView;
            if (devinfo.AppendBarcode > 0)
            {
                Model.MDevice devinfo1 = Model.CGetInfo.GetDeviceInfo(devinfo.AppendBarcode);
                //DataView dv = dbo.ExceSQL("SELECT F_DBW1Address,F_DBWSendLength,F_DeviceIndex,F_DeviceKindIndex,F_OPCProgID, F_RemoteIP FROM T_Base_Device where F_DeviceIndex=" + Convert.ToInt32(dv0[0]["F_AppendBarcode"])).Tables[0].DefaultView;
                if (devinfo1.DeviceIndex == 0)
                {
                    _commLayerError = "SimensProdave6.CSendDeviceOrder.SendDeviceOrder发生错误：写入附加条码时设备索引不存在!";
                    return false;
                }
                else
                {
                    wdata[0] = 1;
                    for (int i = 1; i <= barcode.Length; i++)
                    {
                        wdata[i] =(byte) Strings.Asc(barcode.Substring(i-1, 1));
                    }
                    if (CSimensProdave6_S7.DB_Write_Prodave(0, 1, Convert.ToUInt16(devinfo1.Dbw1Address), Convert.ToUInt32(devinfo1.Dbw1SendLength), wdata) == false)
                    {
                        _commLayerError = "SimensProdave6.CSendDeviceOrder.SendDeviceOrder发生错误：写入附加条码失败!";
                        return false;
                    }
                }
                return true;
            }
            else
            {
                return true; ;
            }
        }
        /// <summary>
        /// 向PLC的DB区写入数据
        /// </summary>
        /// <param name="ItemNames">标签变量名称数组</param>
        /// <param name="ItemValues">标签值数组</param>
        /// <returns></returns>
        public bool WriteDBData(string[] ItemNames, string[] ItemValues)
        {
            return true;
        }
    }
}
