/*************************************************************************************
 *
 * 文 件 名:   HandleAgvRequest
 * 描    述:   处理AGV请求
 * 备    注:
 * 创 建 者：  Du
 * 创建时间：  2022/8/2 9:42:33
*************************************************************************************/

using Newtonsoft.Json;
using RGD.DataService;
using RGD.DBUtility;
using RGD.HaiRouAPI.HaiRouModel;
using RGD.MdsAPI.WMS;
using RGD.Model;
using System;
using System.Data;

namespace RGD.HaiRouAPI
{
    public class HandleAgvRequest
    {
        private static string containercode = "";
        private static string tasktype = "";
        private static string loc_no = "";

        /// <summary>
        /// 任务状态上报回调
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string taskStatueResponse(string content)
        {
            string sResult;
            TaskStatues ts = JsonConvert.DeserializeObject<TaskStatues>(content);
            ApplyResult ar = new ApplyResult();
            //因一次动作上报不止一次,所以涉及MDS接口时只记录第一次,后续不在继续调用
            //区分逻辑为判断本次任务容器编码是否与上一次一致

            //return jsonmodel;
            bool bResult = true;
            //任务状态上报完成逻辑
            //AGV上报取货或送货完成
            //取货完成时，判断是否为MDS任务，是出库还是入库
            //首先判断是出库还是入库
            DataView warehouse = DbHelperSQL.Query("select * from t_warehouse").Tables[0].DefaultView;
            if (warehouse[0]["F_TASK_TYPE"].ToString() != "Inventory")
            {
                try
                {
                    if (ts.eventType.Equals("tote_load"))//取箱完成
                    {
                        if (ts.containerCode.Equals(containercode) && ts.eventType.Equals(tasktype))
                        {
                            ar.code = "0";
                            ar.msg = "success";
                            ar.data = "";
                            var jsonmodel = JsonConvert.SerializeObject(ar);
                            return jsonmodel;
                        }
                        containercode = ts.containerCode;
                        tasktype = ts.eventType;
                        int i = 0;
                        //取箱完成直接给取货任务报完成,只有出库是涉及两次接口接口,获取上报的调度任务号,根据调度任务号完成设备指令对应的取货任务
                        DataView dt = DbHelperSQL.Query("select * from T_Manage_task where FPALLETBARCODE='" + ts.containerCode + "'").Tables[0].DefaultView;
                        DataView task = DbHelperSQL.Query("select * from T_warehouse").Tables[0].DefaultView;
                        //本地任务直接删除取货任务
                        if (task[0]["F_TASK_STATUS"].ToString() == "FREE")
                        {
                            i = DbHelperSQL.ExecuteSql("delete t_monitor_task where F_TxtParam='" + ts.containerCode + "' and F_DeviceCommandIndex=4");

                            if (i != 0)
                            {
                                ar.code = "0";
                                ar.msg = "success";
                                ar.data = "";
                                var jsonmodel = JsonConvert.SerializeObject(ar);
                                return jsonmodel;
                            }
                        }
                        //MDS任务只有在出库时调用取货完成接口,然后放货完成接口
                        else
                        {
                            if (dt[0]["FCONTROLTASKTYPE"].ToString() == "2")
                            {
                                //bResult = (new uploadStackIODet()).Notify(task[0]["F_TASK_NO"].ToString(), "01", dt[0]["FSTARTCELL"].ToString(), out sResult);
                                //if (bResult)
                                //{
                                //    i = DbHelperSQL.ExecuteSql("delete t_monitor_task where F_TxtParam='" + ts.containerCode + "' and F_DeviceCommandIndex=4");
                                //}
                                i = DbHelperSQL.ExecuteSql("delete t_monitor_task where F_TxtParam='" + ts.containerCode + "' and F_DeviceCommandIndex=4");
                            }
                            else
                            {
                                i = DbHelperSQL.ExecuteSql("delete t_monitor_task where F_TxtParam='" + ts.containerCode + "' and F_DeviceCommandIndex=4");
                            }
                            if (1 != 0 && bResult)
                            {
                                ar.code = "0";
                                ar.msg = "success";
                                ar.data = "";
                                var jsonmodel = JsonConvert.SerializeObject(ar);
                                return jsonmodel;
                            }
                            else
                            {
                                ar.code = "1";
                                ar.msg = "false";
                                ar.data = "";
                                var jsonmodel = JsonConvert.SerializeObject(ar);
                                return jsonmodel;
                            }
                        }
                    }
                    else if (ts.eventType.Equals("tote_unload"))//放箱完成
                    {
                        if (ts.containerCode.Equals(containercode) && ts.eventType.Equals(tasktype))
                        {
                            ar.code = "0";
                            ar.msg = "success";
                            ar.data = "";
                            var jsonmodel = JsonConvert.SerializeObject(ar);
                            return jsonmodel;
                        }
                        containercode = ts.containerCode;
                        tasktype = ts.eventType;
                        //查询是否为手工或自动任务
                        DataView dt = DbHelperSQL.Query("select * from T_Manage_task where FPALLETBARCODE='" + ts.containerCode + "'").Tables[0].DefaultView;
                        DataView task = DbHelperSQL.Query("select * from T_warehouse").Tables[0].DefaultView;
                        if (task[0]["F_TASK_STATUS"].ToString() == "FREE")
                        {
                            int i = DbHelperSQL.ExecuteSql("delete t_monitor_task where F_TxtParam='" + ts.containerCode + "' and F_DeviceCommandIndex=5");
                            //本地入库任务的放箱完成,更新储位信息,放货任务为最后一条,完成后清除调度任务
                            if (dt[0]["FCONTROLTASKTYPE"].ToString() == "1")
                            {
                                i = DbHelperSQL.ExecuteSql("update st_cell set FCELLSTATUS=1,FPALLETBARCODE='" + ts.containerCode + "' where FCELLCODE='" + ts.locationCode + "'");
                                i = DbHelperSQL.ExecuteSql("delete t_manage_task where FPALLETBARCODE='" + ts.containerCode + "'");
                            }
                            //本地出库任务的放箱完成,清除储位信息
                            else if (dt[0]["FCONTROLTASKTYPE"].ToString() == "2")
                            {
                                i = DbHelperSQL.ExecuteSql("update st_cell set FCELLSTATUS=0,FPALLETBARCODE='' where FCELLCODE='" + ts.locationCode + "'");
                            }
                            if (i != 0)
                            {
                                ar.code = "0";
                                ar.msg = "success";
                                ar.data = "";
                                var jsonmodel = JsonConvert.SerializeObject(ar);
                                return jsonmodel;
                            }
                            else
                            {
                                ar.code = "1";
                                ar.msg = "false";
                                ar.data = "";
                                var jsonmodel = JsonConvert.SerializeObject(ar);
                                return jsonmodel;
                            }
                        }
                        else
                        {
                            int i = 0;
                            //MDS入库任务的放箱完成,调用放货完成接口02放,01取
                            if (dt[0]["FCONTROLTASKTYPE"].ToString() == "1")
                            {
                                bResult = (new uploadStackIODet()).Notify(task[0]["F_TASK_NO"].ToString(), "02", dt[0]["FENDCELL"].ToString(), out sResult);
                                if (bResult)
                                {
                                    i = DbHelperSQL.ExecuteSql("delete t_monitor_task where F_TxtParam='" + ts.containerCode + "' and F_DeviceCommandIndex=5");
                                    i = DbHelperSQL.ExecuteSql("update st_cell set FCELLSTATUS=1,FPALLETBARCODE='" + ts.containerCode + "' where FCELLCODE='" + ts.locationCode + "'");
                                    i = DbHelperSQL.ExecuteSql("delete t_manage_task where FPALLETBARCODE='" + ts.containerCode + "'");
                                }
                            }
                            //MDS出库任务的放箱完成,调用放货完成接口,成功后清除储位信息
                            else if (dt[0]["FCONTROLTASKTYPE"].ToString() == "2")
                            {
                                i = DbHelperSQL.ExecuteSql("delete t_monitor_task where F_TxtParam='" + ts.containerCode + "' and F_DeviceCommandIndex=5");
                                i = DbHelperSQL.ExecuteSql("update st_cell set FCELLSTATUS=0,FPALLETBARCODE='' where FCELLCODE='" + ts.locationCode + "'");
                            }
                            if (i != 0 && bResult)
                            {
                                ar.code = "0";
                                ar.msg = "success";
                                ar.data = "";
                                var jsonmodel = JsonConvert.SerializeObject(ar);
                                return jsonmodel;
                            }
                            else
                            {
                                ErrorCountAdd(11001);
                                ar.code = "1";
                                ar.msg = "false";
                                ar.data = "";
                                var jsonmodel = JsonConvert.SerializeObject(ar);
                                return jsonmodel;
                            }
                        }
                    }
                    else
                    {
                        ar.code = "0";
                        ar.msg = "success";
                        ar.data = "";
                        var jsonmodel = JsonConvert.SerializeObject(ar);
                        return jsonmodel;
                    }
                }
                catch (Exception ex)
                {
                    ar.code = "0";
                    ar.msg = "success";
                    ar.data = "";
                    var jsonmodel = JsonConvert.SerializeObject(ar);
                    return jsonmodel;
                }
            }
            else
            {
                //单步取箱完成需要查询该任务是出库还是入库，即起始位置是输送线还是货架，若是货架，必须调用取放货接口，若是入库则忽略
                DataView dt = DbHelperSQL.Query("select * from T_Manage_task where FPALLETBARCODE='" + ts.containerCode + "'").Tables[0].DefaultView;
                if (ts.eventType.Equals("tote_load"))//单步取箱完成
                {
                    if (dt[0]["FCONTROLTASKTYPE"].ToString() == "2")
                    {
                        //取货完成
                        //bResult = (new uploadStackIODet()).Notify(warehouse[0]["F_TASK_NO"].ToString(), "01", dt[0]["FSTARTCELL"].ToString(), out sResult);
                        //删除取货任务
                        DbHelperSQL.ExecuteSql("delete t_monitor_task where F_TxtParam='" + ts.containerCode + "' and F_DeviceCommandIndex=4");
                    }
                    else
                    {
                        //删除取货任务
                        DbHelperSQL.ExecuteSql("delete t_monitor_task where F_TxtParam='" + ts.containerCode + "' and F_DeviceCommandIndex=4");
                        //入库取货任务完成后将pot_flag变为0
                        DbHelperSQL.ExecuteSql("update io_rfid set put_flag='0'");
                    }
                }
                else if (ts.eventType.Equals("tote_unload"))
                {
                    //入库任务放箱即入库完成需要调用接口
                    if (dt[0]["FCONTROLTASKTYPE"].ToString() == "1")
                    {
                        if (loc_no != dt[0]["FENDCELL"].ToString())
                        {
                            bResult = (new uploadStackIODet()).Notify(warehouse[0]["F_TASK_NO"].ToString(), "02", dt[0]["FENDCELL"].ToString(), out sResult);
                        }

                        //放货完成
                        if (bResult)
                        {
                            loc_no = dt[0]["FENDCELL"].ToString();
                        }
                        //删除放货任务
                        DbHelperSQL.ExecuteSql("delete t_monitor_task where F_TxtParam='" + ts.containerCode + "' and F_DeviceCommandIndex=5");
                        //更新储位信息
                        DbHelperSQL.ExecuteSql("update st_cell set FCELLSTATUS=1,FPALLETBARCODE='" + ts.containerCode + "' where FCELLCODE='" + ts.locationCode + "'");
                        //删除调度任务
                        DbHelperSQL.ExecuteSql("delete t_manage_task where FPALLETBARCODE='" + ts.containerCode + "'");
                    }
                    else
                    {
                        DbHelperSQL.ExecuteSql("delete t_monitor_task where F_TxtParam='" + ts.containerCode + "' and F_DeviceCommandIndex=5");
                        DbHelperSQL.ExecuteSql("update st_cell set FCELLSTATUS=0,FPALLETBARCODE='' where FCELLCODE='" + ts.locationCode + "'");
                    }
                }
                ar.code = "0";
                ar.msg = "success";
                ar.data = "";
                var jsonmodel = JsonConvert.SerializeObject(ar);
                return jsonmodel;
            }

            return "";
        }

        private static void ErrorCountAdd(int DeviceIndex)
        {
            int ErrorCount = 0;
            DataView dv = DbHelperSQL.Query("select F_ErrorCount from t_base_device where F_DeviceIndex=" + DeviceIndex).Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                if (dv[0][0] == DBNull.Value)
                {
                    ErrorCount = 1;
                }
                else
                {
                    ErrorCount = ((int)dv[0][0]) + 1;
                }
            }
            DbHelperSQL.ExecuteSql("update t_base_device set F_ErrorCount=" + ErrorCount + " where F_DeviceIndex=" + DeviceIndex);
        }

        /// <summary>
        /// 异常状态上报处理
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string ErrorMesResponse(string content)
        {
            //处理逻辑,异常上报后根据内容停止与AGV相关任务的发送
            ApplyResult ar = JsonConvert.DeserializeObject<ApplyResult>(content);
            ar.code = "0";
            ar.msg = "success";
            var jsonmodel = JsonConvert.SerializeObject(ar);
            return jsonmodel;
        }

        /// <summary>
        /// 放箱申请请求处理
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string PutBoxApply(string content)
        {
            //处理逻辑,请求接收后查询重点输送线是否有物
            UnloadContainerReq ucr = JsonConvert.DeserializeObject<UnloadContainerReq>(content);
            MDevice deviceInfo = BaseDeviceService.GetDeviceInfo(12004);
            MDevice deviceInfo2 = BaseDeviceService.GetDeviceInfo(12003);
            UnloadContainerReqRes ucrr = new UnloadContainerReqRes();
            ucrrData ud = new ucrrData();
            if (deviceInfo.SplitByte_0 == 0 && deviceInfo2.SplitByte_0 == 0)
            {
                ucrr.code = "0";
                ucrr.msg = "success";
                ud.allow = true;
                ucrr.data = ud;
            }
            else
            {
                ucrr.code = "1";
                ucrr.msg = "false";
                ud.allow = false;
                ucrr.data = ud;
            }
            var jsonmodel = JsonConvert.SerializeObject(ucrr);
            return jsonmodel;
        }

        /// <summary>
        /// 放容器完成
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string PutBoxFinish(string content)
        {
            UnloadContainerFinish ucf = JsonConvert.DeserializeObject<UnloadContainerFinish>(content);
            ApplyResult ar = new ApplyResult();
            ar.code = "0";
            ar.msg = "success";
            var jsonmodel = JsonConvert.SerializeObject(ar);
            return jsonmodel;
        }

        /// <summary>
        /// 输送线取箱完成
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string TaskBoxFinish(string content)
        {
            LoadContainerFinish lcf = JsonConvert.DeserializeObject<LoadContainerFinish>(content);
            ApplyResult ar = new ApplyResult();
            ar.code = "0";
            ar.msg = "success";
            var jsonmodel = JsonConvert.SerializeObject(ar);
            return jsonmodel;
        }
    }
}