using DBFactory;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ControlSystem
{
    public  class CreateMonitor
    {
        static DBOperator dbo = CStaticClass.dbo;
        static CCommonFunction ccf = new CCommonFunction();
        static int AutoManageIdx = 0;
        /// <summary>
        /// 手动任务
        /// </summary>
        /// <param name="startIndex">起点</param>
        /// <param name="endIndex">终点</param>
        /// <param name="type">类型 送出还是什么</param>
        public static void CreateMove(int startIndex,int endIndex,int type)
        {
            string dtime = DateTime.Now.ToString("u");
            dtime = dtime.Substring(0, dtime.Length - 1);
            string qcell = string.Empty, scell = string.Empty;
            int hidx = 0;
            int hmindx = 0; int rehidx = 0;
            int z = startIndex, x = 0, y = 0, z1 = endIndex, x1 = 0, y1 = 0;

            //2	将取,3	将送,4	取货,5	送货
            int devicekind = ccf.GetDeviceKindIdx(startIndex);//startIndex

            string useawayfork = "0"; int xx = x + 1; int xx1 = x1 + 1;
            int routeIDsub = GetRouteIDsub(startIndex);

            hidx = GetManageHandIdx();
            hmindx = ccf.GetMonitorIndex(hidx, 4);
            string Sql = "insert into T_Monitor_Task(F_RouteID,F_ManageTaskIndex,F_ManageTaskKindIndex,F_MonitorIndex," +
                    "F_DeviceIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2,F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6,F_UseAwayFork) " +
                    "values(" + routeIDsub + "," + hidx + ",4," + hmindx + "," + startIndex
                    + "," + type + "," + z + "," + x + "," + y + "," + z1 + "," + x1 + "," + y1 + ",'" + useawayfork + "')";//6
            DataSet ds = dbo.ExceSQL(Sql);

            dbo.ExceSQL("insert into T_Manage_Task(FID,F_ManageTaskKindIndex,F_RELATIVECONTORLID,FIntoStepOK,FSTARTDEVICE,FREMARK,FSTARTCELL,FENDDEVICE,FENDCELL,FBEGTIME) values(" +
                hidx + ",4,-1,1," + startIndex + ",'" + type + "','" + z.ToString() + "-" + x.ToString() + "-" + y.ToString()
                + "'," + startIndex + ",'" + z1.ToString() + "-" + x1.ToString() + "-" + y1.ToString() + "','" + dtime + "')");

            if (rehidx > 0)
            {
                dbo.ExecuteSql("update T_Manage_Task set F_RELATIVECONTORLID=" + rehidx + " where F_ManageTaskKindIndex=4 and FID=" + hidx);
                dbo.ExecuteSql("update T_Manage_Task set F_RELATIVECONTORLID=" + hidx + " where F_ManageTaskKindIndex=4 and ID=" + rehidx);
            }
            RecordMaxHandTaskFID(hidx);
        }

        static int GetManageHandIdx()
        {
            DataSet ds = dbo.ExceSQL("SELECT F_ManageTaskKindIndex, max(FID) as mFID FROM T_Manage_Task Where F_ManageTaskKindIndex=4 group by F_ManageTaskKindIndex");
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                return (Convert.ToInt32(ds.Tables[0].DefaultView[0]["mFID"]) + 1);
            }
            else
            {
                DataSet dss = dbo.ExceSQL("SELECT F_ManageTaskIndex FROM T_Base_Manage_Task_Index_Hand_Task");
                if (dss.Tables[0].DefaultView.Count > 0)
                {
                    if ((Convert.ToInt32(dss.Tables[0].DefaultView[0]["F_ManageTaskIndex"]) + 1) >= 29998)
                    {
                        return 20001;
                    }
                    else
                    {
                        return (Convert.ToInt32(dss.Tables[0].DefaultView[0]["F_ManageTaskIndex"]) + 1);
                    }
                }
                else
                {
                    return 20001;
                }
            }
        }

        static void RecordMaxHandTaskFID(int fid)
        {
            DataSet ds = dbo.ExceSQL("select F_ManageTaskIndex from T_Base_Manage_Task_Index_Hand_Task");
            DataView dv = ds.Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                if (fid == 29998)
                {
                    dbo.ExceSQL("UPDATE T_Base_Manage_Task_Index_Hand_Task SET F_ManageTaskIndex =20001");
                    return;
                }
                if (fid > Convert.ToInt32(dv[0]["F_ManageTaskIndex"]))
                {
                    dbo.ExceSQL("UPDATE T_Base_Manage_Task_Index_Hand_Task SET F_ManageTaskIndex =" + fid);
                    return;
                }
            }
            else
            {
                dbo.ExceSQL("INSERT INTO T_Base_Manage_Task_Index_Hand_Task (F_ManageTaskIndex)VALUES (" + fid + ")");
                return;
            }
        }

        static int GetRouteIDsub(int device)
        {
            DataView dv = dbo.ExceSQL("SELECT F_RouteIDSub, F_DeviceIndex, F_RouteID FROM T_Base_Route_Device where F_DeviceIndex=" + device + "").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return Convert.ToInt32(dv[0]["F_RouteIDSub"]);
            }
            else
            {
                return -1;
            }
        }


        /// <summary>
        /// 手动任务 -- 盘库
        /// </summary>
        /// <param name="startIndex">堆垛机编号</param>
        /// <param name="endIndex">终点 货位号 03-01-01</param>
        /// <param name="type">类型 送出还是什么 2将取</param>
        /// <param name="CONTROL_ID">管理任务的ID</param>
        public static void CreateMoveInv(int startIndex, string endIndex, int type, int CONTROL_ID)
        {
            string dtime = DateTime.Now.ToString("u");
            dtime = dtime.Substring(0, dtime.Length - 1);
            string qcell = string.Empty, scell = string.Empty;
            int hidx = 0;
            int hmindx = 0; int rehidx = 0;
            int z = 0, x = 0, y = 0, z1 = 0, x1 = 0, y1 = 0;

            char[] cc = new char[1] { '-' };
            string[] sp = endIndex.Split(cc);
            if (type == 4)
            {
                z = Convert.ToInt32(sp[0]);
                x = Convert.ToInt32(sp[1]);
                y = Convert.ToInt32(sp[2]);
            }
            else if(type == 5)
            {
                z1 = Convert.ToInt32(sp[0]);
                x1 = Convert.ToInt32(sp[1]);
                y1 = Convert.ToInt32(sp[2]);
            }

            int taskType = type == 5 ? 1 : type == 4 ? 2 : 0;

            //2	将取,3	将送,4	取货,5	送货
            int devicekind = ccf.GetDeviceKindIdx(startIndex);//startIndex

            string useawayfork = "0"; int xx = x + 1; int xx1 = x1 + 1;
            int routeIDsub = GetRouteIDsub(startIndex);

            hidx = GetManageHandIdx();
            hmindx = ccf.GetMonitorIndex(hidx, 4);
            string Sql = "insert into T_Monitor_Task(F_RouteID,F_ManageTaskIndex,F_ManageTaskKindIndex,F_MonitorIndex," +
                    "F_DeviceIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2,F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6,F_UseAwayFork) " +
                    "values(" + routeIDsub + "," + hidx + ",1," + hmindx + "," + startIndex
                    + "," + type + "," + z + "," + x + "," + y + "," + z1 + "," + x1 + "," + y1 + ",'" + useawayfork + "')";//6
            DataSet ds = dbo.ExceSQL(Sql);

            dbo.ExceSQL("insert into T_Manage_Task(FID,F_ManageTaskKindIndex,FMANAGEID,F_RELATIVECONTORLID,FCONTROLTASKTYPE,FIntoStepOK,FSTARTDEVICE,FREMARK,FSTARTCELL,FENDDEVICE,FENDCELL,FBEGTIME) values(" +
                hidx + ",1," + CONTROL_ID + ",-1," + taskType + ",1," + startIndex + ",'" + type + "','" + z.ToString() + "-" + x.ToString() + "-" + y.ToString()
                + "'," + startIndex + ",'" + z1.ToString() + "-" + x1.ToString() + "-" + y1.ToString() + "','" + dtime + "')");

            if (rehidx > 0)
            {
                dbo.ExecuteSql("update T_Manage_Task set F_RELATIVECONTORLID=" + rehidx + " where F_ManageTaskKindIndex=4 and FID=" + hidx);
                dbo.ExecuteSql("update T_Manage_Task set F_RELATIVECONTORLID=" + hidx + " where F_ManageTaskKindIndex=4 and ID=" + rehidx);
            }
            RecordMaxHandTaskFID(hidx);
        }
        /// <summary>
        /// wcs 上报wms任务完成
        /// </summary>
        public static async void WcsToManageTaskOver(int CONTROL_ID)
        {
            string apiUrl = "http://localhost:58926/api/ManageTask/WcsToManageTaskOver"; 

            var requestData = new
            {
                CONTROL_ID = CONTROL_ID,
                DATA = new { } 
            };
            
            try
            {
                using ( HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoidGVzdHVzZXIiLCJyb2xlIjoiYWRtaW4iLCJleHAiOjE3NDUyMjA2OTYsImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTg5MjYvIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo1ODkyNi9hcGkifQ.Qh08-vjkukreCtxVhRNZXEwKM77v1jK3sUzCe3nn_K4");

                    string json = JsonConvert.SerializeObject(requestData);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    HttpResponseMessage response = await client.PostAsync(apiUrl, content);
                    string result = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonConvert.DeserializeObject<ApiResponse<object>>(result);

                    //MessageBox.Show($"状态: {apiResult.Status}, 代码: {apiResult.code}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("请求失败: " + ex.Message);
            }
        }

        public class ApiResponse<T>
        {
            public int Status { get; set; }
            public string msg { get; set; }
            public T data { get; set; }
            public string code { get; set; }
        }

        public static List<T> DataSetToList<T>(DataSet ds) where T : new()
        {
            var list = new List<T>();

            if (ds == null || ds.Tables.Count == 0)
                return list;

            DataTable dt = ds.Tables[0];

            foreach (DataRow row in dt.Rows)
            {
                T obj = new T();
                foreach (DataColumn col in dt.Columns)
                {
                    PropertyInfo prop = typeof(T).GetProperty(col.ColumnName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                    if (prop != null && row[col] != DBNull.Value)
                    {
                        if (Nullable.GetUnderlyingType(prop.PropertyType) != null)
                        {
                            prop.SetValue(obj, Convert.ChangeType(row[col], Nullable.GetUnderlyingType(prop.PropertyType)));
                        }
                        else
                        {
                            prop.SetValue(obj, Convert.ChangeType(row[col], prop.PropertyType));
                        }
                    }
                }
                list.Add(obj);
            }
            return list;
        }


        public class PurchaseOrdersInv 
        {
            public string CellNo { get; set; }
        }

    }

}
