using Microsoft.VisualBasic;
using RGD.Common;
using RGD.DataService;
using RGD.DBUtility;
using RGD.MdsAPI;
using RGD.MdsAPI.WMS;
using RGD.Model;
using RGD.OPCClient;
using System;
using System.Data;

namespace RGD.WCS
{
    /// <summary>
    /// Creator:RGD
    /// 一、下位机给上位机发送现场控制触摸屏申请信号：
    /// 1-重发当前设备指令
    /// 2-申请修改当前设备所执行任务的目标位置
    /// 3-报告当前设备所执行的任务完成
    /// 4-删除当前设备所执行的任务（托盘拿走）
    /// 二、检测PLC创建自动调度任务请求
    /// </summary>
    public class CListenPLCAsk
    {
        private string _listenPLCAskError = "";

        public string ListenPLCAskError
        {
            get { return _listenPLCAskError; }
            set { _listenPLCAskError = value; }
        }

        private CCommonFunction ccf = new CCommonFunction();
        private CGetState cgs = new CGetState();
        private ISendDeviceOrder sdo;
        private Model.MDevice devinfo;

        public CListenPLCAsk()
        {
        }

        /// <summary>
        /// 检测PLC创建自动调度任务请求:1:申请贴标;2：叠盘机上报叠盘完成；
        /// 3：PLC码盘完成；4：条码扫描器申请入库任务；5：拆盘机申请空托盘组出库;6:射频启停信号
        /// </summary>
        public void DealwithPLCAsk()
        {
            string sql = "";
            string[] wv = new string[1] { "2" };
            string[] witemnames = new string[1];
            DataView dv;
            DataView dv0;
            //射频信息
            DataView dvs;
            DataView dvt = DbHelperSQL.Query("select F_TASK_NO,F_TASK_TYPE,F_EQUIP_TYPE from T_WareHouse").Tables[0].DefaultView;
            string TASK_NO = dvt[0]["F_TASK_NO"].ToString();
            string TASK_TYPE = dvt[0]["F_TASK_TYPE"].ToString();
            try
            {
                dv = DbHelperSQL.Query("SELECT T_Base_PLC_Ask.F_DeviceIndex,T_Base_PLC_Ask.F_BindingDevice, F_Askkind,F_TaskIndex,F_BarCode,F_Remark" +
                   ",F_FirstProject,F_BoxBarcode,f_AskNo FROM T_Base_Device,T_Base_PLC_Ask" +
                   " where  T_Base_Device.F_DeviceIndex=T_Base_PLC_Ask.F_DeviceIndex " +
                   " order by T_Base_Device.F_DeviceIndex desc").Tables[0].DefaultView;
                for (int i = 0; i < dv.Count; i++)
                {
                    int deviceindex = Convert.ToInt32(dv[i]["F_DeviceIndex"]);
                    int bindingdeviceindex = Convert.ToInt32(dv[i]["F_BindingDevice"]);
                    devinfo = BaseDeviceService.GetDeviceInfo(deviceindex);
                    witemnames[0] = "DB2,byte" + Convert.ToString((devinfo.Dbw2Address + 0));
                    sdo = CommModeCreate.CreateSendDeviceOrder(deviceindex);

                    #region 射频启停6

                    if (dv[i]["F_Askkind"].ToString() == "6")
                    {
                        MDevice deviceInfo = BaseDeviceService.GetDeviceInfo(deviceindex);

                        sql = "select READ_FLAG,HAVE_GOODS,BEGIN_TIME from IO_RFID where STATION_CODE='" + deviceindex + "'";

                        dvs = DbHelperSQL.Query(sql).Tables[0].DefaultView;
                        if (deviceInfo.SplitByte_6 == 1)//有东西
                        {
                            if ((bool)dvs[0]["HAVE_GOODS"])
                            {
                                int time = 3;
                                if (TASK_TYPE == "Inventory")
                                {
                                    time = 5;
                                }
                                double s = (DateTime.Now - DateTime.Parse(dvs[0]["BEGIN_TIME"].ToString())).TotalSeconds;
                                //LogUtil.WriteLog("", "line380射频超时停止;READ_FLAG:" + dvs[0]["READ_FLAG"]+ ";s:"+s.ToString());
                                if (dvs[0]["READ_FLAG"].ToString() == "1" && (DateTime.Now - DateTime.Parse(dvs[0]["BEGIN_TIME"].ToString())).TotalSeconds >= time)
                                {
                                    sql = "update IO_RFID set READ_FLAG='0' where STATION_CODE='" + deviceindex + "'";
                                    DbHelperSQL.ExecuteSql(sql);
                                }

                                continue;
                            }
                            sql = "update IO_RFID set READ_FLAG='1',HAVE_GOODS=1,BEGIN_TIME='" + DateTime.Now.ToString() + "' where STATION_CODE='" + deviceindex + "'";
                            DbHelperSQL.ExecuteSql(sql);
                            CCarryConvert.WriteDarkCasket("PLCAsk", "射频触发", deviceindex.ToString(), deviceInfo.SplitByte_6 + "**" + dvs[0]["BEGIN_TIME"]);
                        }
                        else
                        {
                            if ((bool)dvs[0]["HAVE_GOODS"])//重置有物状态
                            {
                                sql = "update IO_RFID set HAVE_GOODS=0,read_flag='0' where STATION_CODE='" + deviceindex + "'";
                                DbHelperSQL.ExecuteSql(sql);
                                //LogUtil.WriteLog("", "line397射频置为无物:" + sql);
                            }
                        }
                    }

                    #endregion 射频启停6
                    #region 叠盘完成2
                    if (dv[i]["F_Askkind"].ToString() == "2")
                    {
                        #region 与管理系统的交互
                        //叠盘完成//20101220
                        int sendouttype = CStaticClass.GetOverlapStatus(deviceindex);
                        if (sendouttype > 0) // 获取叠盘机是否叠盘完成，第0位＞0,第1位>2
                        {

                            if (CStaticClass.GetDevicePhotoelectric(ccf.GetSendOutDetect(Convert.ToInt32(dv[i]["F_BindingDevice"]))) != 1)// 获取叠盘机关联设备的开关的值 (有物)
                            {
                                continue;
                            }

                            int[] state;

                            state = CStaticClass.GetDeviceState(Convert.ToInt32(dv[i]["F_BindingDevice"])); //获取关联设备的状态数组
                                                                                                            // state[1] = 0; // 测试用 空闲dzf
                            if (state == null)
                            {
                                continue;
                            }
                            if ((state[1] >= 30) || (state[1] == 1) || (state[1] == 2))//空闲时，采集数据
                            {
                                //20091128
                                state = null;
                                continue;

                            }

                            #region 如果5s内只处理一次
                            if (Information.IsDate(dv[i]["F_FirstProject"]))//20110513时间
                            {
                                if (Convert.ToDateTime(dv[i]["F_FirstProject"]).AddSeconds(5) > DateTime.Now)//如果5s内，不进行处理
                                {
                                    CCarryConvert.WriteDarkCasket("PLCAsk", "5秒内上报叠盘完成", bindingdeviceindex.ToString(), "");

                                    continue;
                                }

                            }
                            #endregion

                            #region 已处理
                            dv0 = DbHelperSQL.Query("SELECT FSTARTDEVICE, FENDDEVICE FROM T_Manage_Task WHERE (FSTARTDEVICE = " + Convert.ToInt32(dv[i]["F_BindingDevice"]) + ") and FSTATUS=0").Tables[0].DefaultView;
                            if (dv0.Count > 0)
                            {
                                continue;
                            }
                            #endregion

                            #region 没有调度任务
                            //if (TASK_NO == "")
                            //{
                            //    continue;
                            //}
                            #endregion
                            string dtime = DateTime.Now.ToString("u");//20101028
                            dtime = dtime.Substring(0, dtime.Length - 1);//20101028

                            //20110331
                            if (TASK_NO != "" && dv[i]["F_BarCode"].ToString() != "")
                            {
                                string stackcode = dv[i]["F_BarCode"].ToString().TrimEnd('|').Replace('|', ',');

                                string sResult = "";
                                FrmControlMonitor.FormInstance.AddDebugMessage("getInStackLocation sending stackcode = " + stackcode);
                                getInStackLocation gisl = new getInStackLocation();
                                //bool bResult = true;
                                bool bResult = gisl.Notify(dvt[0]["F_TASK_NO"].ToString(), stackcode, string.Empty, out sResult);//叠盘结束申请储位
                                FrmControlMonitor.FormInstance.AddDebugMessage(gisl.GetType().Name + " WCS->WMS\r\n" + gisl.XML_IN + sResult, sResult.IndexOf("<RESULT_FLAG>1</RESULT_FLAG>") > 0 ? 0 : 1);
                                getInStackLocation.DATA outData = new Base().DeSerialize<getInStackLocation.DATA>(sResult);

                                if (bResult)
                                {
                                    bResult = new ManageTaskService().CreateMove(TASK_NO, "1", bindingdeviceindex.ToString(), outData.LOC_NO, stackcode, out sResult);
                                    //bResult = new ManageTaskService().CreateMove(TASK_NO, "1", bindingdeviceindex.ToString(), "12004", stackcode, out sResult);
                                }
                                else
                                {//获取失败，异常送出
                                    if (!sResult.Contains("RESULT_FLAG"))
                                    {
                                        continue;
                                    }
                                    bResult = new ManageTaskService().CreateMove(TASK_NO, 2, "3", bindingdeviceindex.ToString(), "12001", stackcode, out sResult);
                                }

                                wv[0] = "0";
                                sdo.WriteDBData(witemnames, wv);// 给叠盘机状态恢复为空闲状态
                                CCarryConvert.WriteDarkCasket("PLCAsk", "叠盘完成申请离开", stackcode, "");
                                DbHelperSQL.ExecuteSql("update T_Base_PLC_Ask set F_BarCode='',F_FirstProject='" + dtime + "',F_BOX_LABLE='' where (F_DeviceIndex=" + deviceindex + ")");
                            }
                            else if (dv[i]["F_BarCode"].ToString() != "")
                            {
                                string stackcode = dv[i]["F_BarCode"].ToString().TrimEnd('|').Replace('|', ',');

                                wv[0] = "0";
                                sdo.WriteDBData(witemnames, wv);// 给叠盘机状态恢复为空闲状态
                                CCarryConvert.WriteDarkCasket("PLCAsk", "叠盘完成申请离开", stackcode, "");
                                DbHelperSQL.ExecuteSql("update T_Base_PLC_Ask set F_BarCode='',F_FirstProject='" + dtime + "',F_BOX_LABLE='' where (F_DeviceIndex=" + deviceindex + ")");
                            }
                        }

                        #endregion
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                _listenPLCAskError = "监听PLC请求时：" + ex.Message;
            }
            finally
            {
                sql = null;
                wv = null;
                witemnames = null;
                dv = null;
                dv0 = null;
                dvs = null;
            }
        }

        private int GetAutoManageIdx()
        {
            DataSet ds;
            try
            {
                int maxIdx = 1;
                ds = DbHelperSQL.Query("SELECT F_ManageTaskIndex FROM T_Base_Manage_Task_Index_Auto_Task");
                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    if ((Convert.ToInt32(ds.Tables[0].DefaultView[0]["F_ManageTaskIndex"]) + 1) >= 9998)
                    {
                        maxIdx = 1;
                    }
                    else
                    {
                        maxIdx = (Convert.ToInt32(ds.Tables[0].DefaultView[0]["F_ManageTaskIndex"]) + 1);
                    }
                }
                else
                {
                    maxIdx = 1;
                }

                DataView dv = DbHelperSQL.Query("select F_ManageTaskIndex from T_Base_Manage_Task_Index_Auto_Task").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    if (maxIdx > Convert.ToInt32(dv[0]["F_ManageTaskIndex"]))
                    {
                        DbHelperSQL.ExecuteSql("UPDATE T_Base_Manage_Task_Index_Auto_Task SET F_ManageTaskIndex =" + maxIdx);
                    }
                }
                else
                {
                    DbHelperSQL.ExecuteSql("INSERT INTO T_Base_Manage_Task_Index_Auto_Task (F_ManageTaskIndex)VALUES (" + maxIdx + ")");
                }

                return maxIdx;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ds = null;
            }
        }
    }
}