using ryCommon;
using ryCommonDb;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace VSoft.Prams
{
    public static class Run
    {
        [DllImportAttribute("shell32.dll")]
        private static extern int SHEmptyRecycleBin(IntPtr handle, string root, int falgs);
        const int SHERB_NOCONFIRMATION = 0x000001;
        const int SHERB_NOPROGRESSUI = 0x000002;
        const int SHERB_NOSOUND = 0x000004;
        /// <summary>
        /// 打开软件
        /// </summary>
        /// <param name="info"></param>
        /// <param name="RunasAdmin"></param>
        /// <returns></returns>
        public static int Open(SoftInfo info, bool RunasAdmin)
        {
            var path = info.TruePath;
            var parm = info.RunPram;
            var StartPath = info.StartPath;
            var SetJson = info.SetJson;
            if (info.SoftType == 1)
            {
                #region 重新载入数据
                DataProvider mydb = new DataProvider();
                IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
                if (db.ConnDb(info.Path) == 1)
                {
                    RyQuickSQL mySQL = new RyQuickSQL("Softs");
                    string where = "";
                    if(parm.StartsWith("cmdid=",StringComparison.OrdinalIgnoreCase))
                    {
                        where = "CmdId=@CmdId";
                        mySQL.AddField("CmdId", parm.Substring(6));
                    }
                    else if (parm.StartsWith("id=", StringComparison.OrdinalIgnoreCase))
                    {
                        where = "id=@id";
                        mySQL.AddField("id", parm.Substring(3).ToInt());
                    }
                    if (where.Length > 0)
                    {
                        DataSet ds = db.ReadData("select * from Softs where " + where, mySQL);
                        if (mydb.HaveData(ds))
                        {
                            DataRow row = ds.Tables[0].Rows[0];
                            path = RyFiles.GetRealPath(row["Path"].ToString());
                            parm = row["RunPram"].ToString();
                            SetJson = row["SetJson"].ToString();
                            StartPath = row["StartPath"].ToString();
                        }
                    }
                    db.Free();
                }
                #endregion
            }
            if (StartPath.Length == 0) 
            {
                if (System.IO.File.Exists(path) || System.IO.Directory.Exists(path))
                {
                    StartPath = System.IO.Path.GetDirectoryName(path.TrimEnd('\\'));
                }
                else
                {
                    StartPath = null;
                }
            }
            if (path.StartsWith("@", StringComparison.OrdinalIgnoreCase)) //如果路径是@开头,则表示这个是一个命令
            {
                switch(path.Substring(1).ToLower())
                {
                    case "emptyrecyclebin"://清空回收站

                        switch (MessageBox.Show("是否确认要清空回收站?\r\n\r\n该操作不可逆！！！", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2))
                        {
                            case DialogResult.Yes:
                                SHEmptyRecycleBin(IntPtr.Zero, "", SHERB_NOCONFIRMATION + SHERB_NOPROGRESSUI + SHERB_NOSOUND);
                                return 1;
                        }
                        break;
                }
                return 0;
            }
            if (RunasAdmin)
            {
                return RunProcessAsAdmin(path, parm, StartPath);
            }
            else
            {
                Json json = new Json(SetJson);
                if (json.GetJsonValue("RunAsAdmin", false))
                {
                    return RunProcessAsAdmin(path, parm, StartPath);
                }
                else
                {
                    return RyFiles.RunFile(path, parm, StartPath);
                }
            }
        }
        /// <summary>
        /// 以管理员方式打开
        /// </summary>
        /// <param name="exeName"></param>
        /// <param name="parameters"></param>
        /// <param name="CurrentDirectory"></param>
        /// <returns></returns>
        public static int RunProcessAsAdmin(string exeName, string parameters, string CurrentDirectory)
        {
            try
            {
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.UseShellExecute = true;
                startInfo.WorkingDirectory = CurrentDirectory;
                startInfo.FileName = exeName;
                startInfo.Verb = "runas";
                //MLHIDE
                startInfo.Arguments = parameters;
                startInfo.ErrorDialog = true;
                var process = System.Diagnostics.Process.Start(startInfo);
                return 37;
            }
            catch
            {
                return -1;
            }
        }
    }
}
