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

using Newtonsoft.Json;
using RGD.DataService;
using RGD.DBUtility;
using RGD.MdsAPI.WMS;
using RGD.Model;
using System.Data;
using RGD.ZhiQianAPI.ZhiQianModel;
using System;
using System.Threading;
using System.Threading.Tasks;

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

        /// <summary>
        /// agv请求从输送线取货
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string takeDiliveryRequest(string content)
        {
            RequestDilivery rd = JsonConvert.DeserializeObject<RequestDilivery>(content);
            BaseResponse baseResponse = new BaseResponse();
            baseResponse.success = false;
            baseResponse.code = "1";
            baseResponse.message = "pick up location have not goods";
            Object isInvTask = DbHelperSQL.GetSingle("select F_TASK_TYPE from t_warehouse");
            Object split_flag = DbHelperSQL.GetSingle("select split_flag from io_rfid");
            //如果是盘库任务,重置允许拆分标志
            if (isInvTask.ToString() == "Inventory")
            {
                if (split_flag.ToString() == "True")
                {
                    MDevice deviceInfo = BaseDeviceService.GetDeviceInfo(12004);
                    if (deviceInfo.SplitByte_0 == 1)
                    {
                        Thread.Sleep(2000);
                        baseResponse.success = true;
                        baseResponse.code = "0";
                        baseResponse.message = null;
                    }
                }
            }
            else
            {
                MDevice deviceInfo = BaseDeviceService.GetDeviceInfo(12004);
                if (deviceInfo.SplitByte_0 == 1)
                {
                    baseResponse.success = true;
                    baseResponse.code = "0";
                    baseResponse.message = null;
                }
            }
            var jsonModel = JsonConvert.SerializeObject(baseResponse);
            return jsonModel;
        }

        /// <summary>
        /// agv上报从输送线取货完成
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string takeDiliveryComplete(string content)
        {
            ConfirmDilivery cd = JsonConvert.DeserializeObject<ConfirmDilivery>(content);
            //删除agv从输送线取任务
            DbHelperSQL.ExecuteSql("delete t_monitor_task where F_DeviceCommandIndex=4 and F_TxtParam='" + cd.box + "'");
            DbHelperSQL.ExecuteSql("update t_monitor_task set F_Status=1 where F_DeviceCommandIndex=5 and F_TxtParam='" + cd.box + "'");

            Object isInvTask = DbHelperSQL.GetSingle("select F_TASK_TYPE from t_warehouse");
            //如果是盘库任务,重置允许拆分标志
            if (isInvTask.ToString() == "Inventory")
            {
                //DbHelperSQL.ExecuteSql($"delete t_monitor_task where F_DeviceCommandIndex=4 and F_TxtParam='{cd.box}b'");
                DbHelperSQL.ExecuteSql("update io_rfid set split_flag=0");
                DbHelperSQL.ExecuteSql("update IO_RFID set HAVE_GOODS=0 where STATION_CODE='12002'");
            }
            BaseResponse baseResponse = new BaseResponse();
            baseResponse.success = true;
            baseResponse.code = "0";
            baseResponse.message = null;
            var jsonModel = JsonConvert.SerializeObject(baseResponse);
            return jsonModel;
        }

        /// <summary>
        /// agv请求往输送线放箱
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string putDiliveryRequest(string content)
        {
            RequestStore es = JsonConvert.DeserializeObject<RequestStore>(content);
            MDevice deviceInfo2 = BaseDeviceService.GetDeviceInfo(12004);
            BaseResponse baseResponse = new BaseResponse();
            //只有12004和12004同时没有箱子的时候才能放,避免堵塞
            if (deviceInfo2.SplitByte_0 == 0)
            {
                baseResponse.success = true;
                baseResponse.code = "0";
                baseResponse.message = null;
            }
            else
            {
                baseResponse.success = false;
                baseResponse.code = "1";
                baseResponse.message = "destination has been occupied";
            }
            var jsonModel = JsonConvert.SerializeObject(baseResponse);
            return jsonModel;
        }

        /// <summary>
        /// agv请求往输送线放箱完成
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string putDiliveryComplete(string content)
        {
            ConfirmStore cs = JsonConvert.DeserializeObject<ConfirmStore>(content);
            //删除agv往输送线送货任务
            DbHelperSQL.ExecuteSql("delete t_monitor_task where F_DeviceCommandIndex=5 and F_TxtParam='" + cs.box + "'");
            Object isInvTask = DbHelperSQL.GetSingle("select F_TASK_TYPE from t_warehouse");
            //如果是盘库任务,重置允许拆分标志
            if (isInvTask.ToString() == "Inventory")
            {
                //DbHelperSQL.ExecuteSql($"delete t_monitor_task where F_DeviceCommandIndex=5 and F_TxtParam='{cs.box}b'");
                DbHelperSQL.ExecuteSql("update IO_RFID set HAVE_GOODS=1 where STATION_CODE='12002'");
            }
            BaseResponse baseResponse = new BaseResponse();
            baseResponse.success = true;
            baseResponse.code = "0";
            baseResponse.message = null;
            var jsonModel = JsonConvert.SerializeObject(baseResponse);
            return jsonModel;
        }

        /// <summary>
        /// agv上报wms放货完成
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string putComplete(string content)
        {
            string sResult;
            bool bResult;
            BoxReleased br = JsonConvert.DeserializeObject<BoxReleased>(content);
            //需要区分是入库任务还是出库任务,如果是入库任务那么放货完成时需要调用取放货完成接口
            DataView warehouse = DbHelperSQL.Query("select * from t_warehouse").Tables[0].DefaultView;
            DataView dt = DbHelperSQL.Query("select * from T_Manage_task where FPALLETBARCODE='" + br.containerCode + "'").Tables[0].DefaultView;

            string FCONTROLTASKTYPE = dt[0]["FCONTROLTASKTYPE"].ToString();
            string FENDCELL = dt[0]["FENDCELL"].ToString();

            DbHelperSQL.ExecuteSql("delete t_monitor_task where F_DeviceCommandIndex=5 and F_TxtParam='" + br.containerCode + "'");
            if (dt.Count > 0 && dt[0]["FCONTROLTASKTYPE"].ToString() == "1")
            {
                DbHelperSQL.ExecuteSql("delete t_manage_task where FPALLETBARCODE='" + br.containerCode + "'");
            }
            //AGV货位测试使用 测试完注释并把下方注释的解开
            //DbHelperSQL.ExecuteSql("update st_cell set FPALLETBARCODE ='" + br.containerCode + "' where FCELLCODE='" + br.locationCode + "'");
            if (warehouse[0]["F_TASK_STATUS"].ToString() != "FREE" && dt.Count > 0)
            {
                //入库任务调用接口
                if (FCONTROLTASKTYPE == "1")
                {
                    Task.Run(() =>
                    {
                        bResult = (new uploadStackIODet()).Notify(warehouse[0]["F_TASK_NO"].ToString(), "02", FENDCELL, out sResult);
                    });
                }
            }
            BaseResponse baseResponse = new BaseResponse();
            baseResponse.success = true;
            baseResponse.code = "0";
            baseResponse.message = null;
            var jsonModel = JsonConvert.SerializeObject(baseResponse);
            return jsonModel;
        }

        /// <summary>
        /// agv上报wms取货完成
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string takeComplete(string content)
        {
            BoxTaken bt = JsonConvert.DeserializeObject<BoxTaken>(content);

            DbHelperSQL.ExecuteSql("delete t_monitor_task where F_DeviceCommandIndex=4 and F_TxtParam='" + bt.containerCode + "'");
            DbHelperSQL.ExecuteSql("update t_monitor_task set F_Status=2 where F_DeviceCommandIndex=5 and F_TxtParam='" + bt.containerCode + "'");
            //AGV货位测试使用 测试完注释
            //DbHelperSQL.ExecuteSql("update st_cell set FPALLETBARCODE ='-' where FCELLCODE='" + bt.locationCode + "'");
            //返回内容不关注接口或删除任务,直接返回
            BaseResponse baseResponse = new BaseResponse();
            baseResponse.success = true;
            baseResponse.code = "0";
            baseResponse.message = null;
            var jsonModel = JsonConvert.SerializeObject(baseResponse);
            return jsonModel;
        }

        /// <summary>
        /// 任务状态上报
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string taskStatusHandle(string content)
        {
            BoxStatus bs = JsonConvert.DeserializeObject<BoxStatus>(content);
            
            BaseResponse baseResponse = new BaseResponse();
            baseResponse.success = true;
            baseResponse.code = "0";
            baseResponse.message = null;
            var jsonModel = JsonConvert.SerializeObject(baseResponse);
            return jsonModel;
        }
    }
}