using CommonClassLib;
//using DBFactory;
using Matrix.Utility;
using RGD.DBUtility;
using RGDWCSServices;
using RGDWCSServices.WMS;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Xml;

namespace RGDWCSServices
{
    public class CRFID
    {
        /// <summary>
        /// RFID请求
        /// </summary>
        /// <param name="RFIDRequest">入参</param>
        /// <returns>出参</returns>
        public static string RFIDRequestWithReturn(string RFIDRequest)
        {
            bool bResult = true;
            string sResult = string.Empty;

            //List<string> goodsCode = new List<string>();
            //List<string> goodsCodeLocation = new List<string>();

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(RFIDRequest);
            XmlNode nodeRoot = xmlDoc.SelectSingleNode("RFIDRequest");

            string sSTATION_CODE = nodeRoot.SelectSingleNode(@"BindingDeviceID").InnerText;

            List<long> paixu = new List<long>() { };

            XmlNodeList xnlBOX_BARCODE = nodeRoot.SelectNodes(@"BoxRFID/BoxCode");

            string sBOX_BARCODE = string.Empty;

            //新增箱条码顺序
            foreach (XmlNode nBOX_BARCODE in xnlBOX_BARCODE)
            {
                paixu.Add(Convert.ToInt64(nBOX_BARCODE.InnerText));
            }
            paixu.Sort();

            paixu = paixu.GroupBy(x => x).Select(x => x.Key).ToList(); 
            foreach (long nBOX_BARCODE in paixu)
            {
                sBOX_BARCODE += nBOX_BARCODE.ToString() + ",";
            }
            //
            sBOX_BARCODE = sBOX_BARCODE.TrimEnd(',');

            XmlNodeList xnlGOODS_BARCODE_LOCATION = nodeRoot.SelectNodes(@"GoodsRFID/Location");
            XmlNodeList xnlGOODS_BARCODE = nodeRoot.SelectNodes(@"GoodsRFID/GoodsCode");
            string sGOODS_BARCODE = string.Empty;
            foreach (XmlNode nGOODS_BARCODE in xnlGOODS_BARCODE)
            {
                sGOODS_BARCODE += nGOODS_BARCODE.InnerText + ",";
            }
            sGOODS_BARCODE = sGOODS_BARCODE.TrimEnd(',');

            System.Diagnostics.Debug.WriteLine("RFIDRequestWithReturn RFIDRequest = " + RFIDRequest);

            switch (sBOX_BARCODE)
            {
                case "371102010032":
                    sBOX_BARCODE = "345610001259";
                    break;
                case "371102010017":
                    sBOX_BARCODE = "340010041716";
                    break;
                case "371102010055":
                    sBOX_BARCODE = "345210003548";
                    break;
                case "371102010002":
                    sBOX_BARCODE = "340010013624";
                    break;
                case "371102010005":
                    sBOX_BARCODE = "340010013318";
                    break;
                case "371102010049":
                    sBOX_BARCODE = "340060005874";
                    break;
            }

            //当前任务
            DataView dv = DbHelperSQL.Query("select F_TASK_NO,F_TASK_TYPE,F_EQUIP_TYPE,F_TASK_STATUS,F_IO_WH_SORT_CODE,F_SINGLE_STANDARD from T_WareHouse").Tables[0].DefaultView;
            string TASK_NO = dv[0]["F_TASK_NO"].ToString();
            string TASK_TYPE = dv[0]["F_TASK_TYPE"].ToString();
            string EQUIP_TYPE = dv[0]["F_EQUIP_TYPE"].ToString();
            string TASK_STATUS = dv[0]["F_TASK_STATUS"].ToString();
            string IO_WH_SORT_CODE = dv[0]["F_IO_WH_SORT_CODE"].ToString();
            if (TASK_NO == "" || TASK_NO == "0")
            {
                bResult = false;
                sResult = "任务验证失败：未找到下发的任务。";
                StaticClass.CreateMove(TASK_NO, Enum.CONTROL_TYPE.Move.ToString("d"), sSTATION_CODE, "12001", "", out sResult);
                return string.Format("<RFIDResponse><Flag>{0}</Flag><Message>{1}</Message></RFIDResponse>任务验证失败：未找到下发的任务", (bResult ? "1" : "0"), sResult);
            }
            if (TASK_STATUS != "RUN" && TASK_TYPE == "In")
            {
                bResult = false;
                sResult = "任务验证失败：入库任务正在停止。";
                StaticClass.CreateMove(TASK_NO, Enum.CONTROL_TYPE.Move.ToString("d"), sSTATION_CODE, "12001", "", out sResult);
                return string.Format("<RFIDResponse><Flag>{0}</Flag><Message>{1}</Message></RFIDResponse>任务验证失败：入库任务正在停止", (bResult ? "1" : "0"), sResult);
            }

            //for (int i = 0; i < xnlGOODS_BARCODE.Count; i++)
            //{
            //    if (!xnlGOODS_BARCODE[i].InnerText.StartsWith("3430054"))
            //    {
            //        sGOODS_BARCODE += xnlGOODS_BARCODE[i].InnerText + ",";
            //        if (TASK_TYPE != "Inventory")
            //        {
            //            goodsCode.Add(xnlGOODS_BARCODE[i].InnerText);
            //            goodsCodeLocation.Add(xnlGOODS_BARCODE_LOCATION[i].InnerText);
            //        }
            //    }
            //}

            //来源
            dv = DbHelperSQL.Query("select SOURCE_CELL_CODE,box_barcode from IO_RFID where STATION_CODE='" + sSTATION_CODE + "'").Tables[0].DefaultView;

            if (dv.Count == 0)
            {
                bResult = false;
                sResult = "未找到RFID站台" + sSTATION_CODE;
                return string.Format("<RFIDResponse><Flag>{0}</Flag><Message>{1}</Message></RFIDResponse>未找到RFID站台", (bResult ? "1" : "0"), sResult);
            }

            if (TASK_TYPE == "In")
            {
                int equipperbox = 1;

                switch (EQUIP_TYPE)
                {
                    case "01":
                    case "03":
                    case "06": equipperbox = 36; break;
                    case "02":
                    case "04": equipperbox = 12; break;
                    case "05": equipperbox = 3; break;
                }

                if (EQUIP_TYPE == "05")
                {
                    if (xnlGOODS_BARCODE.Count > 0)
                    {
                        bResult = false;
                        sResult = "空箱入库时扫到表。";
                        StaticClass.CreateMove(TASK_NO, Enum.CONTROL_TYPE.Move.ToString("d"), sSTATION_CODE, "12001", "", out sResult);
                        return string.Format("<RFIDResponse><Flag>{0}</Flag><Message>{1}</Message></RFIDResponse>空箱入库时扫到表。", (bResult ? "1" : "0"), sResult);
                    }
                }
                else if (equipperbox < xnlGOODS_BARCODE.Count)
                {
                    if (xnlGOODS_BARCODE.Count > 0)
                    {
                        bResult = false;
                        sResult = "设备数量验证失败。";
                        StaticClass.CreateMove(TASK_NO, Enum.CONTROL_TYPE.Move.ToString("d"), sSTATION_CODE, "12001", "", out sResult);
                        return string.Format("<RFIDResponse><Flag>{0}</Flag><Message>{1}</Message></RFIDResponse>设备数量验证失败。", (bResult ? "1" : "0"), sResult);
                    }
                }


                if (paixu.Count > 3)// || xnlBOX_BARCODE.Count==0
                {
                    bResult = false;
                    sResult = "箱数量不为三。";
                    StaticClass.CreateMove(TASK_NO, Enum.CONTROL_TYPE.Move.ToString("d"), sSTATION_CODE, "12001", "", out sResult);
                    return string.Format("<RFIDResponse><Flag>{0}</Flag><Message>{1}</Message></RFIDResponse>箱数量不为三。", (bResult ? "1" : "0"), sResult);
                }
            }

            string SOURCE_CELL_CODE = dv[0][0].ToString() == "-" ? "" : dv[0][0].ToString();

            getInOutCheckInfo ws = new getInOutCheckInfo();
            LogUtil.WriteLog("", TASK_NO+":扫描验证启动时间");

            if (TASK_TYPE == "Out")
            {
                LogUtil.WriteLog("", TASK_NO + ":扫描验证启动时间");
                bResult = ws.Notify(TASK_NO, "02", SOURCE_CELL_CODE, sBOX_BARCODE, string.Empty, out sResult);
                if (!bResult)
                {
                    return string.Format("<RFIDResponse><Flag>{0}</Flag><Message>{1}</Message></RFIDResponse>返库验证失败", (bResult ? "1" : "0"), sResult);
                }
            }

            bResult = ws.Notify(TASK_NO, "02", SOURCE_CELL_CODE, sBOX_BARCODE, sGOODS_BARCODE, out sResult); //上报条码信息校验

            getInOutCheckInfo.DATA op = (new Base()).DeSerialize<getInOutCheckInfo.DATA>(sResult);

            if (TASK_TYPE == "Inventory")
            {
                if (bResult)
                {
                    //StaticClass.CreateMove(TASK_NO, RGDWCSServices.Enum.CONTROL_TYPE.Up.ToString("d"), sSTATION_CODE, SOURCE_CELL_CODE, sBOX_BARCODE, op.BOX_LABLE, 0, "", false, false, op != null && op.IS_LASTBOX == "1", 1, out sResult);
                    //允许射频门离开
                    DbHelperSQL.ExecuteSql("update io_rfid set split_flag='1'");
                    return string.Format("<RFIDResponse><Flag>{0}</Flag><Message>{1}</Message></RFIDResponse>盘库扫描成功，{2}目的地址为" + SOURCE_CELL_CODE, (bResult ? "1" : "0"), sResult, sBOX_BARCODE);
                }
                else
                {
                    return string.Format("<RFIDResponse><Flag>{0}</Flag><Message>{1}</Message></RFIDResponse>盘库扫描失败", (bResult ? "1" : "0"), sResult);
                }
            }

            //新增
            if (bResult)
            {
                getInStackLocation wss = new getInStackLocation();
                getInStackLocation.DATA opp = (new Base()).DeSerialize<getInStackLocation.DATA>(sResult);
                //if (xnlBOX_BARCODE[0].InnerText.Substring(0, 5) == "34005" || EQUIP_TYPE == "05")//高箱跟空箱入库不叠盘 在这里直接申请储位
                if (true)//凤阳模式不启用叠盘
                {
                    bResult = wss.Notify(TASK_NO, sBOX_BARCODE, string.Empty, out sResult); //申请储位接口

                    opp = (new Base()).DeSerialize<getInStackLocation.DATA>(sResult);
                    //StaticClass.CreateMove(TASK_NO, RGDWCSServices.Enum.CONTROL_TYPE.Up.ToString("d"), sSTATION_CODE, "01-02-01", sBOX_BARCODE, paixu[0].ToString(), 0, "", false, false, op != null && op.IS_LASTBOX == "1", 1, out sResult);
                    StaticClass.CreateMove(TASK_NO, RGDWCSServices.Enum.CONTROL_TYPE.Up.ToString("d"), sSTATION_CODE, opp.LOC_NO, sBOX_BARCODE, op.BOX_LABLE, 0, "", false, false, op != null && op.IS_LASTBOX == "1", 1, out sResult);
                }
                else
                {
                    //送去叠盘 储位叠盘完成后申请
                    StaticClass.CreateMove(TASK_NO, RGDWCSServices.Enum.CONTROL_TYPE.Up.ToString("d"), sSTATION_CODE, "12003", sBOX_BARCODE, paixu[0].ToString(), 0, "", false, false, op != null && op.IS_LASTBOX == "1", 1, out sResult);
                    //StaticClass.CreateMove(TASK_NO, RGDWCSServices.Enum.CONTROL_TYPE.Up.ToString("d"), sSTATION_CODE, opp.LOC_NO, sBOX_BARCODE, op.BOX_LABLE, 0, "", false, false, op != null && op.IS_LASTBOX == "1", 1, out sResult);
                }
                DataView InOut = DbHelperSQL.Query("select * from T_InTask_QTY").Tables[0].DefaultView;
                if (InOut.Count>0)
                {
                    int count = 0;
                    int number = 0;
                    if (EQUIP_TYPE=="05")
                    {
                        number = int.Parse(InOut[0]["count"].ToString()) - xnlBOX_BARCODE.Count;
                    }
                    else
                    {
                        number = int.Parse(InOut[0]["count"].ToString()) - xnlGOODS_BARCODE.Count;
                    }
                    if (number > 0)
                    {
                        count = number;
                    }
                    DbHelperSQL.ExecuteSql("update T_InTask_QTY set count=" + count);
                }
            }
            else
            {
                StaticClass.CreateMove(TASK_NO, RGDWCSServices.Enum.CONTROL_TYPE.Move.ToString("d"), sSTATION_CODE, "12001", sBOX_BARCODE, op.BOX_LABLE, 0, "", false, false, op != null && op.IS_LASTBOX == "1", 1, out sResult);
            }

            if (bResult)
                DbHelperSQL.ExecuteSql("update io_rfid set SOURCE_CELL_CODE='' where STATION_CODE=" + sSTATION_CODE);

            return string.Format("<RFIDResponse><Flag>{0}</Flag><Message>{1}</Message></RFIDResponse>", (bResult ? "1" : "0"), sResult);
        }

        //static DbHelperSQLperator DbHelperSQL = new DbHelperSQLperator();
        /// <summary>
        /// 监控射频读写启停信号
        /// </summary>
        /// <returns></returns>
        public static string RFIDReadyToRead(string station_code)
        {
            DataTable dt = DbHelperSQL.Query("select READ_FLAG from IO_RFID where STATION_CODE='" + station_code + "'").Tables[0];
            if (dt.Rows.Count > 0)
                return dt.Rows[0][0].ToString();
            return "0";
        }
        /// <summary>  
        /// 移除数组中重复数据  
        /// </summary>  
        /// <param name="array">需要除重的数组</param>  
        /// <returns>不重复数组</returns>  
        public static string[] DelRepeatData(string[] array)
        {
            return array.GroupBy(p => p).Select(p => p.Key).ToArray();
        }
    }
}
