using ryCommon;
using ryCommonDb;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VSoft.Prams;

namespace VSoft
{
    public partial class FrmAddSoft : Form
    {
        public string SQLConnStr { get; set; } = Itrycn_Db.SQLConnStr;
        public FrmAddSoft()
        {
            InitializeComponent();
            LblCustomImg.Text = "自动获取";
        }
        public string tableName = "Softs";
        private string IconPath { get; set; } = "";
        public int IsAdd { get; set; } = 1;
        public int SelectId { get; set; } = -1;
        public int ColumnId { get; set; } = -1;
        public FrmAddSoft(string path)
        {
            InitializeComponent();
            if (System.IO.Path.GetExtension(path).ToLower() == ".lnk")
            {
                var shortcut = API.ReadShortcut(path);
                TxtPath.Text = shortcut.TargetPath;
                TxtRunPram.Text = shortcut.Arguments;
                TxtStartPath.Text = shortcut.WorkDir;
                //ShellLink cc = new ShellLink(path);
                //PicImg.Image = cc.LargeIcon.ToBitmap();
            }
            else
            {
                TxtPath.Text =RyFiles.GetRelativePath(path);
            }
            TxtName.Text = System.IO.Path.GetFileNameWithoutExtension(path);
        }
        private string orgion_IconPath = "";
        public void GetInfo(int id)
        {
            SelectId = id;
            Text = "修改软件";
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(SQLConnStr) == 1)
            {
                DataSet ds = db.ReadData(tableName, id.ToString());
                if (mydb.HaveData(ds))
                {
                    DataRow reader = ds.Tables[0].Rows[0];
                    #region 读取信息     
                    TxtName.Text = reader["Name"].ToString();
                    TxtCmdId.Text = reader["CmdId"].ToString();
                    TxtDes.Text = reader["Des"].ToString();
                    TxtPath.Text = reader["Path"].ToString();
                    TxtRunPram.Text = reader["RunPram"].ToString();
                    TxtStartPath.Text = reader["StartPath"].ToString();
                    Json json = new Json(reader["SetJson"].ToString());
                    ChkRunAsAdmin.Checked = json.GetJsonValue("RunAsAdmin", false);
                    var _IconPath = reader["IconPath"].ToString();
                    orgion_IconPath = _IconPath;
                    IconPath = _IconPath;
                    if (_IconPath.Length==0)
                    {
                        _IconPath = reader["Path"].ToString();
                    }
                    else
                    {
                        LblCustomImg.Text = "自定义";
                    }
                    PicImg.Image = API.GetImg(RyFiles.GetRealPath(_IconPath));
                    #endregion
                }
            }
            db.Free();
        }

        private void BtnOK_Click(object sender, EventArgs e)
        {
            if (TxtName.Text.Length == 0)
            {
                MessageBox.Show("名称不能为空。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (TxtCmdId.Text.Length> 0 && !TxtCmdId.Text.Replace("_","").IsEngOrNum())
            {
                MessageBox.Show("命令ID只支持英文和数字字符。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (IconPath.Length>0 && IconPath.IndexOfEx("<app>")!=0 && IconPath!=TxtPath.Text)
            {
                var _IconPath=RyFiles.AddFileToFolder(RyFiles.GetRealPath(IconPath), Config.Soft_Info.UserDataFolder + "\\SoftLogos", true, out var result);
                if(result)
                {
                    IconPath = RyFiles.GetRelativePath(_IconPath);
                }
            }
            if (IconPath != orgion_IconPath)
            {
                if (orgion_IconPath.Length > 0 && orgion_IconPath.StartsWith("<app>\\UserDb\\SoftLogos", StringComparison.OrdinalIgnoreCase))
                {
                    RyFiles.DeleteFile(RyFiles.GetRealPath(orgion_IconPath));
                }
            }
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(SQLConnStr) == 1)
            {
                if (TxtCmdId.Text.Length > 0)
                {
                    var ds = db.ReadData("select * from " + tableName + " where CmdId='" + TxtCmdId.Text + "' and id<>" + SelectId + " limit 1");
                    if (mydb.HaveData(ds))
                    {
                        MessageBox.Show("当前命令ID已经存在,请更换命令ID。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ds.Dispose(); return;
                    }
                    ds.Dispose();
                }
                RyQuickSQL mySQL = new RyQuickSQL(tableName);
                mySQL.AddField("Name", TxtName.Text);
                mySQL.AddField("CmdId", TxtCmdId.Text);
                mySQL.AddField("Path", TxtPath.Text);
                mySQL.AddField("RunPram", TxtRunPram.Text);
                mySQL.AddField("StartPath", TxtStartPath.Text);//起始路径
                mySQL.AddField("IconPath", IconPath);//图标路径
                Json json = new Json("");
                json.Add("RunAsAdmin", ChkRunAsAdmin.Checked);
                mySQL.AddField("SetJson", json.Text);//设置
                mySQL.AddField("Des", TxtDes.Text);//备注
                mySQL.AddField("Pinyin", ryCommon.PinYin.Convert(TxtName.Text) + "\r\n" + ryCommon.PinYin.ConvertFirstPY(TxtName.Text));
                mySQL.AddField("editTime", DateTime.Now);
                if (IsAdd >= 1)
                {
                    mySQL.AddField("SoftType", 0);//0表示运行文件,1表示执行快速命令,2表示执行脚本
                    mySQL.AddField("ClickCount", 0);//点击量
                    mySQL.AddField("ColumnId",ColumnId);
                    mySQL.AddField("sortindex",Itrycn_Db.GetSoftCount(db, ColumnId) + 1);
                    mySQL.AddField("addTime", DateTime.Now);
                    db.ExecuteNonQuery(mySQL.GetInsertSQL(), mySQL);
                }
                else
                {
                    db.ExecuteNonQuery(mySQL.GetUpdateSQL() + " where id=" + SelectId, mySQL);
                }
            }
            db.Free();
            DialogResult = DialogResult.OK;
        }

        private void TxtPath_TextChanged2(object sender, EventArgs e)
        {
            if (IconPath.Length > 0)
            { return; }
            var path =RyFiles.GetRealPath(TxtPath.Text);
            if(System.IO.File.Exists(path))
            {
                PicImg.Image = API.GetImg(path,128);
            }
            else if (System.IO.Directory.Exists(path))
            {
                PicImg.Image = API.GetImg(path,64);
            }
            else
            {
                PicImg.Image = null;
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        private void PicImg_Click(object sender, EventArgs e)
        {
            选择图标ToolStripMenuItem.PerformClick();
        }

        private void FrmAddSoft_Load(object sender, EventArgs e)
        {

        }

        private void BtnBrowser_Click(object sender, EventArgs e)
        {
            if (of_File.ShowDialog() == DialogResult.OK)
            {
                TxtPath.Text = of_File.FileName;
            }
        }

        private void 选择图标ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                IconPath =RyFiles.GetRelativePath(openFileDialog1.FileName);
                PicImg.Image = API.GetImg(openFileDialog1.FileName);
                LblCustomImg.Text = "自定义";
            }
        }

        private void 使用应用图标ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IconPath = "";
            PicImg.Image = API.GetImg(RyFiles.GetRealPath(TxtPath.Text));
            LblCustomImg.Text = "自动获取";
        }
    }
}
