using CommonClassLib;
//using DBFactory;
using Matrix.Utility;
using RGD.DBUtility;
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 CVision
    {
        //static DbHelperSQLperator DbHelperSQL = new DbHelperSQLperator();

        /// <summary>
        /// VISION请求
        /// </summary>
        /// <param name="VisionRequest">入参</param>
        /// <returns>出参</returns>
        public static string VISIONRequestWithReturn(string VisionRequest)
        {
            LogUtil.WriteLog("webService", "CVision;VISIONRequestWithReturn：" + VisionRequest);

            bool bResult = true;
            string sResult = string.Empty;
            string sTempResult = string.Empty;

            DataView dv_task = DbHelperSQL.Query("select * from t_Warehouse").Tables[0].DefaultView;
            string TASK_NO = dv_task[0]["F_TASK_NO"].ToString();

            if (TASK_NO == "" || TASK_NO == "0")
            {
                bResult = false;
                sResult = "任务验证失败：未找到下发的任务。";
                return string.Format("<RFIDResponse><Flag>{0}</Flag><Message>{1}</Message></RFIDResponse>", (bResult ? "1" : "0"), sResult);
            }

            System.Diagnostics.Debug.WriteLine("VISIONRequestWithReturn VisionRequest = " + VisionRequest);

            if (string.IsNullOrEmpty(VisionRequest))
            {
                bResult = false;
                sResult = string.Format("VisionRequest不能为空");
                return string.Format("<VisionResponse><Flag>{0}</Flag><Message>{1}</Message></VisionResponse>", (bResult ? "1" : "0"), sResult);
            }


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

            string sSTATION_CODE = nodeRoot.SelectSingleNode(@"DeviceID").InnerText;
            string sGOODS_TYPE = dv_task[0]["f_equip_type"].ToString() == "01" ? "1" : "2";// nodeRoot.SelectSingleNode(@"EquipType").InnerText;

            string sGOODBARCODEs = nodeRoot.SelectSingleNode(@"Barcodes").InnerText;

            string[] lsBARCODE = sGOODBARCODEs.Trim(';').Split(';');

            if (sGOODBARCODEs == "0:000000")
            {
                bResult = false;
                sResult = string.Format("类型不符");
                return string.Format("<MVResponse><Flag>{0}</Flag><Message>{1}</Message></MVResponse>", (bResult ? "1" : "0"), sResult);
            }
            if (sGOODBARCODEs == "0:111111")
            {
                bResult = false;
                sResult = string.Format("识别超时");
                return string.Format("<MVResponse><Flag>{0}</Flag><Message>{1}</Message></MVResponse>", (bResult ? "1" : "0"), sResult);
            }

            try
            {
                DataView dv = DbHelperSQL.Query("select * from IO_VISION where STATION_CODE='" + sSTATION_CODE + "'").Tables[0].DefaultView;

                if ((bool)dv[0]["IS_PAST"])
                {
                    getUserBind ws = new getUserBind();
                    bResult = ws.Notify(TASK_NO, dv[0]["BOX_BARCODE"].ToString(), out sResult);
                    getUserBind.DATA op = (new Base()).DeSerialize<getUserBind.DATA>(sResult);

                    if (!bResult)
                    {
                        return string.Format("<MVResponse><Flag>{0}</Flag><Message>{1}</Message></MVResponse>", (bResult ? "1" : "0"), sResult);
                    }
                    if (op == null || op.BINDS == null || op.BINDS.Count <= 0)
                    {
                        bResult = false;
                        sResult = string.Format("绑定信息条数为0");
                        return string.Format("<MVResponse><Flag>{0}</Flag><Message>{1}</Message></MVResponse>", (bResult ? "1" : "0"), sResult);
                    }
                    int pickuplocation = 0;
                    foreach (getUserBind.BIND bind in op.BINDS)
                    {
                        bool founded = false;
                        foreach (string loc in lsBARCODE)
                        {
                            founded = false;
                            int location = int.Parse(loc.Split(':')[0]);
                            string barcode = loc.Split(':')[1];
                            if (barcode == bind.BAR_CODE)
                            {
                                int a = 1;
                                for (int i = 1; i < location; i++)
                                { a = a * 2; }
                                pickuplocation += a;
                                DbHelperSQL.ExecuteSql("insert into IO_VISION_DETAIL (BOX_BARCODE,GOODS_BARCODE,GOODS_LOCATION,USER_NO,USER_ADD,USER_NAME) values"
                                    + "('" + dv[0]["BOX_BARCODE"] + "','" + barcode + "'," + location + ",'" + bind.USER_NO + "','" + bind.USER_ADD + "','" + bind.USER_NAME + "')");
                                founded = true;
                                break;
                            }
                        }
                        if (!founded)
                        {//未找到条码
                            bResult = false;
                            sResult = string.Format("未找到条码");
                            return string.Format("<MVResponse><Flag>{0}</Flag><Message>{1}</Message></MVResponse>", (bResult ? "1" : "0"), sResult);
                        }
                    }
                    System.Diagnostics.Debug.WriteLine("VISIONRequestWithReturn IS_PAST pickuplocation = " + pickuplocation.ToString());
                    //贴标站台
                    StaticClass.CreateMove(dv_task[0]["f_TASK_NO"].ToString(), Enum.CONTROL_TYPE.Paste.ToString("d"), "12030", "17001", dv[0]["BOX_BARCODE"].ToString(), pickuplocation, sGOODS_TYPE, (bool)dv[0]["IS_PICKUP"], false, false, out sResult);
                }
                else if ((bool)dv[0]["IS_PICKUP"])
                {
                    int pickuplocation = 0;
                    foreach (string sGOODS_BARCODE in dv[0]["GOODS_BARCODES"].ToString().Split(','))
                    {
                        foreach (string loc in lsBARCODE)
                        {
                            int location = int.Parse(loc.Split(':')[0]);
                            string barcode = loc.Split(':')[1];
                            if (barcode == sGOODS_BARCODE)
                            {
                                int a = 1;
                                for (int i = 1; i < location; i++)
                                { a = a * 2; }
                                pickuplocation += a;
                                break;
                            }
                        }
                    }

                    System.Diagnostics.Debug.WriteLine("VISIONRequestWithReturn IS_PICKUP pickuplocation = " + pickuplocation.ToString());
                    //拣选站台
                    StaticClass.CreateMove(dv_task[0]["f_TASK_NO"].ToString(), Enum.CONTROL_TYPE.PickUp.ToString("d"), "12030", "17002", dv[0]["BOX_BARCODE"].ToString(), pickuplocation, sGOODS_TYPE, true, false, false, out sResult);
                }
                else
                {
                    if (lsBARCODE.Length == 0)
                    {

                    }
                    string goods_barcode = lsBARCODE[0].Split(':')[1];

                    new getBoxBarCode().Notify(dv_task[0]["f_TASK_NO"].ToString(), goods_barcode, out sResult);
                    getBoxBarCode.DATA op1 = new Base().DeSerialize<getBoxBarCode.DATA>(sResult);

                    string box_barcode = op1.BOX_BAR_CODE;


                    bResult = (new getInOutCheckInfo()).Notify(dv_task[0]["F_TASK_NO"].ToString(), "01", string.Empty, box_barcode, string.Empty, out sResult);
                    if (!bResult)
                    {
                        throw new Exception("接口调用失败。" + DateTime.Now.ToString() + "\r\n接口：getInOutCheckInfo。\r\n错误信息：" + sResult);
                    }

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

                    int pickuplocation = 0;
                    getUserBind ws;
                    getUserBind.DATA opub;
                    switch (op.OUT_MODE)
                    {
                        case "1"://整箱出库
                            bResult = StaticClass.CreateMove(dv_task[0]["f_TASK_NO"].ToString(), RGDWCSServices.Enum.CONTROL_TYPE.Move.ToString("d"), "12030", "12032", box_barcode, out sResult);
                            break;
                        case "2"://整箱回库
                            DbHelperSQL.Query("update t_warehouse set f_lastbox_barcode='" + box_barcode + "'");
                            bResult = StaticClass.CreateMove(dv_task[0]["f_TASK_NO"].ToString(), RGDWCSServices.Enum.CONTROL_TYPE.Move.ToString("d"), "12030", "12002", box_barcode, out sResult);
                            break;
                        case "3"://拣选出库
                            DbHelperSQL.Query("update t_warehouse set f_lastbox_barcode='" + box_barcode + "'");
                            foreach (string sGOODS_BARCODE in op.REPICK_ARRAY.Split(','))
                            {
                                foreach (string loc in lsBARCODE)
                                {
                                    int location = int.Parse(loc.Split(':')[0]);
                                    string barcode = loc.Split(':')[1];
                                    if (barcode == sGOODS_BARCODE)
                                    {
                                        int a = 1;
                                        for (int i = 1; i < location; i++)
                                        { a = a * 2; }
                                        pickuplocation += a;
                                        break;
                                    }
                                }
                            }

                            System.Diagnostics.Debug.WriteLine("VISIONRequestWithReturn IS_PICKUP pickuplocation = " + pickuplocation.ToString());
                            //拣选站台
                            StaticClass.CreateMove(dv_task[0]["f_TASK_NO"].ToString(), Enum.CONTROL_TYPE.PickUp.ToString("d"), "12030", "17002", box_barcode, pickuplocation, sGOODS_TYPE, true, false, false, out sResult);
                            break;
                        case "4"://贴标回库
                            DbHelperSQL.Query("update t_warehouse set f_lastbox_barcode='" + box_barcode + "'");
                            //当前任务
                            ws = new getUserBind();
                            bResult = ws.Notify(TASK_NO, box_barcode, out sResult);
                            opub = (new Base()).DeSerialize<getUserBind.DATA>(sResult);
                            if (!bResult)
                            {
                                return string.Format("<MVResponse><Flag>{0}</Flag><Message>{1}</Message></MVResponse>", (bResult ? "1" : "0"), sResult);
                            }
                            if (opub == null || opub.BINDS == null || opub.BINDS.Count <= 0)
                            {
                                bResult = false;
                                sResult = string.Format("绑定信息条数为0");
                                return string.Format("<MVResponse><Flag>{0}</Flag><Message>{1}</Message></MVResponse>", (bResult ? "1" : "0"), sResult);
                            }

                            foreach (getUserBind.BIND bind in opub.BINDS)
                            {
                                bool founded = false;
                                foreach (string loc in lsBARCODE)
                                {
                                    founded = false;
                                    int location = int.Parse(loc.Split(':')[0]);
                                    string barcode = loc.Split(':')[1];
                                    if (barcode == bind.BAR_CODE)
                                    {
                                        int a = 1;
                                        for (int i = 1; i < location; i++)
                                        { a = a * 2; }
                                        pickuplocation += a;
                                        DbHelperSQL.ExecuteSql("insert into IO_VISION_DETAIL (BOX_BARCODE,GOODS_BARCODE,GOODS_LOCATION,USER_NO,USER_ADD,USER_NAME) values"
                                            + "('" + box_barcode + "','" + barcode + "'," + location + ",'" + bind.USER_NO + "','" + bind.USER_ADD + "','" + bind.USER_NAME + "')");
                                        founded = true;
                                        break;
                                    }
                                }
                                if (!founded)
                                {//未找到条码
                                    bResult = false;
                                    sResult = string.Format("未找到条码");
                                    return string.Format("<MVResponse><Flag>{0}</Flag><Message>{1}</Message></MVResponse>", (bResult ? "1" : "0"), sResult);
                                }
                            }
                            System.Diagnostics.Debug.WriteLine("VISIONRequestWithReturn IS_PAST pickuplocation = " + pickuplocation.ToString());
                            //贴标站台
                            StaticClass.CreateMove(dv_task[0]["f_TASK_NO"].ToString(), Enum.CONTROL_TYPE.Paste.ToString("d"), "12030", "17001", box_barcode, pickuplocation, sGOODS_TYPE, false, false, false, out sResult);
                            break;
                        case "5"://贴标出库
                            DbHelperSQL.Query("update t_warehouse set f_lastbox_barcode='" + box_barcode + "'");
                            //当前任务
                            ws = new getUserBind();
                            bResult = ws.Notify(TASK_NO, box_barcode, out sResult);
                            opub = (new Base()).DeSerialize<getUserBind.DATA>(sResult);
                            if (!bResult)
                            {
                                return string.Format("<MVResponse><Flag>{0}</Flag><Message>{1}</Message></MVResponse>", (bResult ? "1" : "0"), sResult);
                            }
                            if (opub == null || opub.BINDS == null || opub.BINDS.Count <= 0)
                            {
                                bResult = false;
                                sResult = string.Format("绑定信息条数为0");
                                return string.Format("<MVResponse><Flag>{0}</Flag><Message>{1}</Message></MVResponse>", (bResult ? "1" : "0"), sResult);
                            }

                            foreach (getUserBind.BIND bind in opub.BINDS)
                            {
                                bool founded = false;
                                foreach (string loc in lsBARCODE)
                                {
                                    founded = false;
                                    int location = int.Parse(loc.Split(':')[0]);
                                    string barcode = loc.Split(':')[1];
                                    if (barcode == bind.BAR_CODE)
                                    {
                                        int a = 1;
                                        for (int i = 1; i < location; i++)
                                        { a = a * 2; }
                                        pickuplocation += a;
                                        DbHelperSQL.ExecuteSql("insert into IO_VISION_DETAIL (BOX_BARCODE,GOODS_BARCODE,GOODS_LOCATION,USER_NO,USER_ADD,USER_NAME) values"
                                            + "('" + box_barcode + "','" + barcode + "'," + location + ",'" + bind.USER_NO + "','" + bind.USER_ADD + "','" + bind.USER_NAME + "')");
                                        founded = true;
                                        break;
                                    }
                                }
                                if (!founded)
                                {//未找到条码
                                    bResult = false;
                                    sResult = string.Format("未找到条码");
                                    return string.Format("<MVResponse><Flag>{0}</Flag><Message>{1}</Message></MVResponse>", (bResult ? "1" : "0"), sResult);
                                }
                            }
                            System.Diagnostics.Debug.WriteLine("VISIONRequestWithReturn IS_PAST pickuplocation = " + pickuplocation.ToString());
                            //贴标站台
                            StaticClass.CreateMove(dv_task[0]["f_TASK_NO"].ToString(), Enum.CONTROL_TYPE.Paste.ToString("d"), "12030", "17001", box_barcode, pickuplocation, sGOODS_TYPE, false, true, false, out sResult);
                            break;
                        case "6"://贴标拣选出库
                            DbHelperSQL.Query("update t_warehouse set f_lastbox_barcode='" + box_barcode + "'");
                            //当前任务
                            ws = new getUserBind();
                            bResult = ws.Notify(TASK_NO, box_barcode, out sResult);
                            opub = (new Base()).DeSerialize<getUserBind.DATA>(sResult);
                            if (!bResult)
                            {
                                return string.Format("<MVResponse><Flag>{0}</Flag><Message>{1}</Message></MVResponse>", (bResult ? "1" : "0"), sResult);
                            }
                            if (opub == null || opub.BINDS == null || opub.BINDS.Count <= 0)
                            {
                                bResult = false;
                                sResult = string.Format("绑定信息条数为0");
                                return string.Format("<MVResponse><Flag>{0}</Flag><Message>{1}</Message></MVResponse>", (bResult ? "1" : "0"), sResult);
                            }

                            foreach (getUserBind.BIND bind in opub.BINDS)
                            {
                                bool founded = false;
                                foreach (string loc in lsBARCODE)
                                {
                                    founded = false;
                                    int location = int.Parse(loc.Split(':')[0]);
                                    string barcode = loc.Split(':')[1];
                                    if (barcode == bind.BAR_CODE)
                                    {
                                        int a = 1;
                                        for (int i = 1; i < location; i++)
                                        { a = a * 2; }
                                        pickuplocation += a;
                                        DbHelperSQL.ExecuteSql("insert into IO_VISION_DETAIL (BOX_BARCODE,GOODS_BARCODE,GOODS_LOCATION,USER_NO,USER_ADD,USER_NAME) values"
                                            + "('" + box_barcode + "','" + barcode + "'," + location + ",'" + bind.USER_NO + "','" + bind.USER_ADD + "','" + bind.USER_NAME + "')");
                                        founded = true;
                                        break;
                                    }
                                }
                                if (!founded)
                                {//未找到条码
                                    bResult = false;
                                    sResult = string.Format("未找到条码");
                                    return string.Format("<MVResponse><Flag>{0}</Flag><Message>{1}</Message></MVResponse>", (bResult ? "1" : "0"), sResult);
                                }
                            }
                            System.Diagnostics.Debug.WriteLine("VISIONRequestWithReturn IS_PAST pickuplocation = " + pickuplocation.ToString());
                            //贴标站台
                            StaticClass.CreateMove(dv_task[0]["f_TASK_NO"].ToString(), Enum.CONTROL_TYPE.Paste.ToString("d"), "12030", "17001", box_barcode, pickuplocation, sGOODS_TYPE, true, false, false, out sResult);
                            break;
                    }

                    if (op.IS_LASTBOX == "1")
                    {
                        DbHelperSQL.Query("update t_warehouse set F_LASTBOX_REACH_FLAG=1");
                    }
                }
            }
            catch (Exception e)
            {
                bResult = false;
                sResult = e.Message;

                System.Diagnostics.Debug.WriteLine("VISIONRequestWithReturn Exception sResult = " + sResult);
            }
            finally
            {
            }
            return string.Format("<MVResponse><Flag>{0}</Flag><Message>{1}</Message></MVResponse>", (bResult ? "1" : "0"), sResult);
        }

        /// <summary>
        /// 视觉检测开始检测
        /// </summary>
        /// <param name="stationCode">视觉设备编号</param>
        /// <returns>0不启动；1单相表箱进入开始检测；2三相表箱进入开始检测</returns>
        public static int ReadyToHandleVision(string stationCode)
        {
            DataTable dtBOX = DbHelperSQL.Query("select * from IO_VISION where STATION_CODE='" + stationCode + "'").Tables[0];
            if (dtBOX != null && dtBOX.Rows.Count > 0)
            {
                int readFlag = Convert.ToInt32(dtBOX.Rows[0]["READ_FLAG"]);
                if (readFlag >0 )
                {
                    return readFlag;
                }
                return 0;
            }
            else
            {
                return 0;
            }
        }

        public static int Update_IO_Vision(string device_code, int read_flag)
        {
            StringBuilder sql = new StringBuilder();

            sql.Append("update IO_VISION set READ_FLAG='" + read_flag + "' where STATION_CODE='" + device_code + "'");

            if (sql.Length > 0)
            {
                return DbHelperSQL.ExecuteSql(sql.ToString());
            }
            else
            {
                return -2;
            }
        }
    }
}
