using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using EKETEAM.FrameWork;
using EKETEAM.Data;
using LitJson;

public partial class Plugins_signMobile : System.Web.UI.Page
{
    public string mode = eParameters.QueryString("mode");
    public string signid = eParameters.QueryString("signid");
    public string signtokenid = eParameters.QueryString("signtokenid");
    public string act = "";
    public string area = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        act = eParameters.QueryString("act");
        area = eParameters.QueryString("area");
        if (act == "finish")
        {
            litMsg.Text = eBase.getTipMsg(new eTipMsg() { Body = "签名完成!", Icon = "success" });
            return;
        }
        eUser user;
        #region 默认签名
        if (act == "getdefaultsign")
        {            
            if (area.Length == 0) eResult.Error("参数错误!");
            user = new eUser(area);
            if (!user.Logined) eResult.Error("用户未登录!");

            string signFile = eRunTime.signPath + user.ID + ".png";
            if (!System.IO.File.Exists(signFile)) eResult.Error("签名无效!");

            JsonData json = new JsonData();
            json["success"] = true;
            json["errcode"] = "0";
            string _edata = "";
            using (System.IO.FileStream fs = new System.IO.FileStream(signFile, System.IO.FileMode.Open))
            {
                fs.Seek(0, System.IO.SeekOrigin.Begin);
                byte[] bs = new byte[fs.Length];
                int log = Convert.ToInt32(fs.Length);
                fs.Read(bs, 0, log);
                _edata = Convert.ToBase64String(bs);//
            }
            json["base64"] = _edata;//base64数据
            eResult.WriteJson(json);
        }
        #endregion
        #region 获取签名ID
        if (act == "getsigntoken")
        {
            if (area.Length == 0) eResult.Error("参数错误!");
            user = new eUser(area);
            if (!user.Logined) eResult.Error("用户未登录!");

            eBase.DataBase.Execute("delete from a_eke_sysUserCustoms where UserID='" + user.ID + "' and parName like 'sign%'");

            #region Token
            eTable etb = new eTable("a_eke_sysUserCustoms", user);
            etb.Fields.Add("UserID", user.ID);
            etb.Fields.Add("parName", "signToken");
            etb.Fields.Add("MC", "签名token");
            etb.Fields.Add("parValue", "0");//打开状态
            etb.Add();
            signtokenid = etb.ID;
            etb = new eTable("a_eke_sysUserCustoms", user);
            etb.Fields.Add("UserID", user.ID);
            etb.Fields.Add("parName", "signPath");
            etb.Fields.Add("MC", "签名文件");
            etb.Add();
            signid = etb.ID; 
            #endregion

            JsonData json = new JsonData();
            json["success"] = true;
            json["errcode"] = "0";
            json["baseurl"] = eBase.getBaseURL();
            json["signid"] = signid;
            json["signtokenid"] = signtokenid;
            eResult.WriteJson(json);
        }
        #endregion
        
        dynamic signToken = eBase.DataBase.getValues("select UserID, parName, parValue, addTime, addUser from a_eke_sysUserCustoms where UserCustomID='" + signtokenid + "'");
        dynamic signPath = eBase.DataBase.getValues("select UserID, parName,  parValue, addTime, addUser from a_eke_sysUserCustoms where UserCustomID='" + signid + "'");
        #region 删除临时文件
        if (act == "removesigntemp")
        {
            string path = signPath.parValue.ToString();
            if (System.IO.File.Exists(path))
            {
                try { System.IO.File.Delete(path); }
                catch { }
            }
            eBase.DataBase.Execute("delete from a_eke_sysUserCustoms where UserCustomID='" + signtokenid + "'");
            eBase.DataBase.Execute("delete from a_eke_sysUserCustoms where UserCustomID='" + signid + "'");
            eResult.Success("完成!");
        }
        #endregion
        #region 获取签名状态
        if (act == "getsignstate")
        {
            if (!signToken.Success || !signPath.Success) eResult.Error("参数错误!");
            if (signToken.userid != signPath.userid) eResult.Error("参数错误!");

            JsonData json = new JsonData();
            json["success"] = true;
            json["errcode"] = "0";
            json["signid"] = signid;
            json["state"] = signToken.parValue;//打开状态
            string path = signPath.parValue.ToString();
            string _edata = "";
            if (path.Length > 0)
            {
                if (System.IO.File.Exists(path))
                {
                    using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open))
                    {
                        fs.Seek(0, System.IO.SeekOrigin.Begin);
                        byte[] bs = new byte[fs.Length];
                        int log = Convert.ToInt32(fs.Length);
                        fs.Read(bs, 0, log);
                        _edata = Convert.ToBase64String(bs);//
                    }
                }
            }

            json["base64"] = _edata;//base64数据
            eResult.WriteJson(json);
        }
        #endregion
        if (signToken.Success && signPath.Success)
        {
            DateTime stime = Convert.ToDateTime(signToken.addTime);
            TimeSpan ts = DateTime.Now - stime;
            int minutes = Convert.ToInt32(ts.TotalMinutes);
            if (minutes > 10)
            {
                eBase.Writeln("超时!");
                eBase.End();
            }
        }

        string useragent = HttpContext.Current.Request.UserAgent == null ? "" : HttpContext.Current.Request.UserAgent;
        //if (!useragent.ToLower().Contains("micromessenger")) return;
        #region 保存签名
        if (act == "save")
        {
            save();
            return;
        }
        #endregion
        eBase.DataBase.Execute("update a_eke_sysUserCustoms set parValue='1' where UserCustomID='" + signtokenid + "' and parValue='0'");
       
    }
    private void save()
    {
        string tempPath = eRunTime.tempPath;
        if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
        string filename = tempPath + eBase.GetFileName() + ".png";
        string imageData = eParameters.Form("imageData");
        //string Pic_Path = HttpContext.Current.Server.MapPath("MyPicture2.png");
        using (FileStream fs = new FileStream(filename, FileMode.Create))
        {
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                byte[] data = Convert.FromBase64String(imageData);
                bw.Write(data);
                bw.Close();
            }
        }
        string savesign = eParameters.Form("savesign");
        if (savesign == "1")
        {
            string signPath = eRunTime.signPath;
            if (!Directory.Exists(signPath)) Directory.CreateDirectory(signPath);
            string userid=  eBase.DataBase.getValue("select UserID from a_eke_sysUserCustoms where UserCustomID='" + signid + "'");
            string signfile = signPath + userid + ".png";

            System.IO.File.Copy(filename,signfile,true);

        }
        eBase.DataBase.Execute("update a_eke_sysUserCustoms set parValue='" + filename + "' where UserCustomID='" + signid + "'");
        //ePicture.ToWidth(Pic_Path, 200);
        //ePicture.ToHeight
        eResult.Success("完成!");
    }
}