using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Threading;
using Microsoft.VisualBasic;
using DBFactory;
using ICommLayer;
using System.Net;
namespace SocketsUDP
{
    /// <summary>
    /// 使用SocketsUDP的客户端进行通讯
    /// 发送设备命令类
    /// 创建者：Richard.Liu
    /// </summary>
    public class CSendDeviceOrder: ISendDeviceOrder
    {
        string _commLayerError;

        public string CommLayerError
        {
            get { return _commLayerError; }
            set { _commLayerError = value; }
        }
        DBOperator dbo = new DBOperator();
        
        //CClientUDP ccuR = new CClientUDP();
        public CSendDeviceOrder()
        {
            dbo.Open();
        }
        //~CSendDeviceOrder()
        //{
        //    dbo.Close();
        //}
        /// <summary>
        /// 发送堆垛机命令
        /// </summary>
        /// <param name="MessageIndex">消息编号</param>
        /// <param name="TaskIndex">任务编号</param>
        /// <param name="Order">堆垛机命令字</param>
        ///单叉单进伸：
        ///1-复位 
        ///2-将取 
        ///3-将送
        ///4-取货
        ///5-放货
        ///6-取放货
        ///双叉单进伸：
        ///1-复位 
        ///2-将取 
        ///3-将送
        ///4-左叉取货
        ///5-左叉放货
        ///6-左叉取放货
        ///14-右叉取货
        ///15-右叉放货
        ///16-右叉取放货
        ///24-双叉取货
        ///25-双叉放货
        ///26-双叉取放货
        ///单叉双进伸：
        ///1-复位 
        ///2-将取 
        ///3-将送
        ///4-近位取货
        ///5-近位放货
        ///6-近位取放货
        ///14-远位取货
        ///15-远位放货
        ///16-远位取放货
        /// <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
            {
                byte[] _Sdata = new byte[16];
                ushort[] _sIntdata = new ushort[8];
                ushort wIntXor = 0;
                byte[] _temp = new byte[2];
                
                _Sdata[0] = 16;
                _Sdata[1] = Convert.ToByte(MessageIndex);
                _temp=CommonClassLib.CCarryConvert.GetByteFromInt16(Convert.ToUInt16( TaskIndex));
                _Sdata[2] = _temp[0];//高八位
                _Sdata[3] = _temp[1];//低八位
                _Sdata[4] = Convert.ToByte(Order);
                _Sdata[5] = Convert.ToByte(DeviceIndex);
                _Sdata[6] = Convert.ToByte(StartX);
                _Sdata[7] = Convert.ToByte(StartY);
                _Sdata[8] = Convert.ToByte(StartZ);
                _Sdata[9] = Convert.ToByte(EndX);
                _Sdata[10] = Convert.ToByte(EndY);
                _Sdata[11] = Convert.ToByte(EndZ);
                _Sdata[12] = 0;
                _Sdata[13] = 0;
                _Sdata[14] = 0;
                //把两个字节转换成一个字
                for (int i = 0; i <= 6; i++)
                {
                    _temp[0] = _Sdata[(2 * i)];
                    _temp[1] = _Sdata[(2 * i+1)];
                    _sIntdata[i] = CommonClassLib.CCarryConvert.GetInt16FromBytes(_temp);
                }

                //0字到5字（0--11字节）异或值放入第7个字（14和15字节）;第六字（12和13字节）默认值0不参与异或
                wIntXor = _sIntdata[0];
                for (int i = 1; i <= 5; i++)
                {
                    wIntXor =(ushort)( wIntXor ^ _sIntdata[i]);
                }
                _sIntdata[7] = wIntXor;
                _temp=CommonClassLib.CCarryConvert.GetByteFromInt16(_sIntdata[7]);
                _Sdata[14] =_temp[0];
                _Sdata[15] = _temp[1];
                

                //根据DeviceIndex,得到Sockets通讯的初始设置
                DataSet ds = dbo.ExceSQL("SELECT  F_DeviceIndex,F_DeviceKindIndex, F_LocalIP,  F_LocalPort, F_RemoteIP,  F_RemotePort  FROM T_Base_Device where F_DeviceIndex=" + DeviceIndex);
                DataView dv = ds.Tables[0].DefaultView;

                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    CClientUDP.RemoteServer = (EndPoint)new IPEndPoint(IPAddress.Parse(dv[0]["F_RemoteIP"].ToString()), Convert.ToInt32(dv[0]["F_RemotePort"]));
                    CClientUDP.LocalServer = (EndPoint)new IPEndPoint(IPAddress.Parse(dv[0]["F_LocalIP"].ToString()), Convert.ToInt32(dv[0]["F_LocalPort"]));
                    
                    
                    CClientUDP.ReceiveUdp(dv[0]["F_LocalIP"].ToString(), Convert.ToInt32(dv[0]["F_LocalPort"]));
                }
                else
                {

                    return false;
                }

                //////////////////////////////////////考虑重发
                if (CClientUDP.SendUdp(_Sdata) == true)
                {
                    Thread.Sleep(300);
                    CClientUDP.ReceiveUdp();
                    byte[] _GetData = CClientUDP.ByteData;
                    if (_GetData != null)
                    {
                        //if ((_GetData[0] == 8) && (_GetData[1] == 240) && (_GetData[2] == MessageIndex) &&
                        //    ((_GetData[3] * Math.Pow(2, 8) + _GetData[4]) == TaskIndex) &&
                        //    (_GetData[5] == DeviceIndex) && (_GetData[6] == 170))
                        //{
                        //    //////////////////////////////////////考虑重发


                        //    byte GXor = 0;
                        //    GXor = _GetData[0];
                        //    for (int i = 1; i <= 6; i++)
                        //    {
                        //        GXor = Convert.ToByte(Convert.ToInt16(GXor) ^ Convert.ToInt16(_GetData[i]));
                        //    }
                        //    if (GXor == _GetData[7])
                        //    {
                        CClientUDP.CloseUDP();
                        return true;
                        //    }
                        //    else
                        //    {
                        //        ccu.CloseUDP();
                        //        return false;
                        //    }
                        //}
                        //else
                        //{
                        //    ccu.CloseUDP();
                        //    return false;
                        //}
                    }
                    else
                    {
                        CClientUDP.CloseUDP();
                        return false;
                    }
                }
                else
                {
                    CClientUDP.CloseUDP();
                    _commLayerError = this.ToString() + "：SendDeviceOrder---" + CClientUDP.UdpError;
                    return false;
                }
            }
            catch (Exception ex)
            {
                CClientUDP.CloseUDP();
                _commLayerError = this.ToString() + "：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-运动到1#位置
        ///8-运动到2#位置
        ///     …
        ///输送机、台车命令字：
        ///1-入库（朝向库）
        ///        2-出库（背向库）
        ///        3-送货
        ///        4-停止
        /// <param name="DeviceIndex">设备编号</param>
        /// <returns>发送其它设备命令是否成功</returns>
        public bool SendDeviceOrder(int MessageIndex, int TaskIndex, int Order, int DeviceIndex)
        {
            try
            {
                byte[] _Sdata = new byte[16];
                byte WXor = 0;
                _Sdata[0] = 16;
                _Sdata[1] = Convert.ToByte(MessageIndex);
                _Sdata[2] = Convert.ToByte(TaskIndex >> 8);//高八位
                _Sdata[3] = Convert.ToByte(TaskIndex & 255);//低八位
                _Sdata[4] = Convert.ToByte(Order);
                _Sdata[5] = Convert.ToByte(DeviceIndex);
                _Sdata[6] = 0;
                _Sdata[7] = 0;
                _Sdata[8] = 0;
                _Sdata[9] = 0;
                _Sdata[10] = 0;
                _Sdata[11] = 0;
                _Sdata[12] = 0;
                _Sdata[13] = 0;
                _Sdata[14] = 0;
                WXor = _Sdata[0];
                for (int i = 1; i <= 14; i++)
                {
                    WXor = Convert.ToByte(Convert.ToInt16(WXor) ^ Convert.ToInt16(_Sdata[i]));
                }
                _Sdata[15] = WXor;
                //根据DeviceIndex,得到Sockets通讯的初始设置
                DataSet ds = dbo.ExceSQL("SELECT  F_DeviceIndex,F_DeviceKindIndex, F_LocalIP,  F_LocalPort, F_RemoteIP,  F_RemotePort  FROM T_Base_Device where F_DeviceIndex=" + DeviceIndex);
                DataView dv = ds.Tables[0].DefaultView;

                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    CClientUDP.RemoteServer = (EndPoint)new IPEndPoint(IPAddress.Parse(dv[0]["F_RemoteIP"].ToString()), Convert.ToInt32(dv[0]["F_RemotePort"]));
                    CClientUDP.LocalServer = (EndPoint)new IPEndPoint(IPAddress.Parse(dv[0]["F_LocalIP"].ToString()), Convert.ToInt32(dv[0]["F_LocalPort"]));
                    
                    
                    CClientUDP.ReceiveUdp(dv[0]["F_LocalIP"].ToString(), Convert.ToInt32(dv[0]["F_LocalPort"]));
                }
                else
                {
                    return false;
                }
                //////////////////////////////////////考虑重发
                if (CClientUDP.SendUdp(_Sdata) == true)
                {
                    Thread.Sleep(300);
                    byte[] _GetData = CClientUDP.ByteData;

                    if (_GetData != null)
                    {
                        if ((_GetData[0] == 8) && (_GetData[1] == 240) && (_GetData[2] == MessageIndex) &&
                            ((_GetData[3] * Math.Pow(2, 8) + _GetData[4]) == TaskIndex) &&
                            (_GetData[5] == DeviceIndex) && (_GetData[6] == 170))
                        {
                            //////////////////////////////////////考虑重发


                            byte GXor = 0;
                            GXor = _GetData[0];
                            for (int i = 1; i <= 6; i++)
                            {
                                GXor = Convert.ToByte(Convert.ToInt16(GXor) ^ Convert.ToInt16(_GetData[i]));
                            }
                            if (GXor == _GetData[7])
                                return true;
                            else
                                return false;
                        }
                        else
                            return false;
                    }
                    else
                    {
                        _commLayerError = this.ToString() + ":SendDeviceOrder---" + CClientUDP.UdpError;
                        return false;
                    }
                }
                else
                {
                    _commLayerError = this.ToString() + ":SendDeviceOrder---" + CClientUDP.UdpError;
                    return false;
                }
            }
            catch (Exception ex)
            {
                _commLayerError = this.ToString() + "：SendDeviceOrder---" + ex.Message;
                return false;
            }

        }
    }
}
