using LYFZ.Model;
using NetDimension.NanUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace LYFZ.Software.MainBusiness.MicroApplet
{
public class frmMicroAppletAdmin : LYFZ.Software.MicroApplet.frmMicroAppletAdmin
{
frmAdminPage frmPage = null;
string gotoUrl = "";
public frmMicroAppletAdmin(string parameter = "/panel/setting/store")
{
if (Environment.OSVersion.Version.Major >= 6)
{
try
{
frmPage = new frmAdminPage();
gotoUrl = parameter;
this.UcNavigationTool.LabTitle = "微信小程序后台管理";
this.Load += frmMicroAppletAdmin_Load;
this.btnRefresh.Click += btnRefresh_Click;
this.btnSetAccount.Click += BtnSetAccount_Click;
this.frmPage.ContextMenuHandler.RunContextMenu += ContextMenuHandler_RunContextMenu;
this.Shown += FrmMicroAppletAdmin_Shown;
this.frmPage.LoadHandler.OnLoadEnd += LoadHandler_OnLoadEnd;
this.frmPage.LoadHandler.OnLoadStart += LoadHandler_OnLoadStart;
this.comAccountList.SelectedIndexChanged += ComAccountList_SelectedIndexChanged;
}
catch
{
MessageBoxCustom.Show("您的系统不支持微信小程序功能,请使用 Win7 或以上系统。");
this.Enabled = false;
}
}
else {
MessageBoxCustom.Show("您的系统不支持微信小程序功能,请使用 Win7 或以上系统。");
this.Enabled = false;
}
}
///
/// 是否初始化完成
///
bool isInitialization = false;
private void ComAccountList_SelectedIndexChanged(object sender, EventArgs e)
{
if (isInitialization)
{
if (this.comAccountList.SelectedItem != null)
{
MicroAppToken = "";
BLL.MicroApplet.MicroAppletAccount mAccount = (BLL.MicroApplet.MicroAppletAccount)((ItemValue)this.comAccountList.SelectedItem).Value;
CurrentMicroAppletShopID = mAccount.ShopID;
LoadMicroAppletPage(mAccount);
}
}
}
private void BtnSetAccount_Click(object sender, EventArgs e)
{
frmMicroAppletAccountManager frmaccountManager = new frmMicroAppletAccountManager();
frmaccountManager.ShowDialog();
if (frmaccountManager.isUpdate)
{
if (LoadMicroConfigure())
{
if (String.IsNullOrEmpty(CurrentMicroAppletShopID))
{
CurrentMicroAppletShopID = LYFZ.Software.MainBusiness.CommonLogical.SuccessfulLogin.CurrentCompanyInfoID;
}
isInitialization = false;
if (_MicroAppletAccountList.Count > 0)
{
BindMicroAppletAccountList(this.comAccountList, CurrentMicroAppletShopID);
}
LoadMicroAppletPage(GetMicroAppletAccount(CurrentMicroAppletShopID));
}
else
{
MessageBoxCustom.Show("获取小程序帐号信息失败,请确认是否正确配置相关信息");
}
}
}
static string userInfo = "";
//bool isSetLocalStorage = false;
private void LoadHandler_OnLoadStart(object sender, Chromium.Event.CfxOnLoadStartEventArgs e)
{
//http://ivision.lyfz.net/login
// if (!isSetLocalStorage)
{
SetSetLocalStorage();
}
}
private void LoadHandler_OnLoadEnd(object sender, Chromium.Event.CfxOnLoadEndEventArgs e)
{
SetSetLocalStorage();
}
void SetSetLocalStorage()
{
//添加登录后的用户信息
this.frmPage.Chromium.ExecuteJavascript("localStorage.setItem('isClient',true);");
this.frmPage.Chromium.ExecuteJavascript(String.Format("localStorage.setItem('userInfo',JSON.stringify({0}));", userInfo));
// isSetLocalStorage = true;
}
public static string CurrentMicroAppletShopID = "";
private void FrmMicroAppletAdmin_Shown(object sender, EventArgs e)
{
if (LoadMicroConfigure())
{
if (String.IsNullOrEmpty(CurrentMicroAppletShopID))
{
CurrentMicroAppletShopID = LYFZ.Software.MainBusiness.CommonLogical.SuccessfulLogin.CurrentCompanyInfoID;
}
if (_MicroAppletAccountList.Count > 0)
{
BindMicroAppletAccountList(this.comAccountList, CurrentMicroAppletShopID);
}
LoadMicroAppletPage(GetMicroAppletAccount(CurrentMicroAppletShopID));
}
else {
MessageBoxCustom.Show("获取小程序帐号信息失败,请确认是否正确配置相关信息");
}
}
void LoadMicroAppletPage(BLL.MicroApplet.MicroAppletAccount mAccount)
{
isInitialization = true;
LYFZ.ComponentLibrary.FrmLoadHandling.LoadDoWorkMethod(delegate (object obj, BackgroundWorker backgroundWorker)
{
try
{
backgroundWorker.ReportProgress(0, "正在验证授权...");
if (!String.IsNullOrEmpty(mAccount.Account) && !String.IsNullOrEmpty(mAccount.Password))
{
// if (String.IsNullOrEmpty(MicroAppToken))
{
MicroAppLoginReturn loginModel = CompanyLoginReturnToken(mAccount.Account, mAccount.Password);
if (loginModel.Code != 200)
{
MicroAppToken = "";
MessageBoxCustom.Show("获取授权失败:" + loginModel.Message, backgroundWorker: backgroundWorker);
}
}
}
else
{
MicroAppToken = "";
MessageBoxCustom.Show(String.Format("您还没有开通“利亚方舟影楼版微信小程序”"), backgroundWorker: backgroundWorker);
}
}
catch (Exception ex)
{
MessageBoxCustom.Show(String.Format("获取授权时错误:{0}", ex.Message), backgroundWorker: backgroundWorker);
}
});
if (this.plExMainContainer.Controls.Count <= 0)
{
this.frmPage.SetEmbeddedWindows(this.plExMainContainer);
}
if (!String.IsNullOrEmpty(MicroAppToken))
{
frmPage.LoadUrl(this.GetMicroAppletUrl(String.Format("{0}{1}", microAppDomainName, gotoUrl), mAccount));
// frmPage.LoadUrl("http://lyfz.app.local/H5UI/index.html");
// frmPage.LoadUrl("http://res.app.local/H5UI/index.html");
// frmPage.LoadUrl("https://html5test.com/");
// frmPage.LoadUrl("http://www.baidu.com/");
//frmPage.LoadUrl("http://benediktmeurer.de/ARES-6/");
//frmPage.LoadUrl("https://react-md.mlaursen.com/components/pickers/date");
}
else
{
frmPage.LoadUrl("http://www.lyfz.net/index/miniapp_desc");
}
}
void frmMicroAppletAdmin_Load(object sender, EventArgs e)
{
this.comAccountList.Enabled = LYFZ.BLL.BLL_ErpUser.GetRights(LYFZ.BLL.BLL_ErpUser.CurrentUserRights.MicroAppletManage, CustomAttributes.OperatingAuthority.MicroAppletAccountSwicth);
this.btnSetAccount.Enabled = LYFZ.BLL.BLL_ErpUser.GetRights(LYFZ.BLL.BLL_ErpUser.CurrentUserRights.MicroAppletManage, CustomAttributes.OperatingAuthority.MicroAppletAccountSet);
}
LYFZ.Model.Model_ErpSystemConfigure Config = new Model.Model_ErpSystemConfigure();
LYFZ.BLL.BLL_ErpSystemConfigure bllConfig = new BLL.BLL_ErpSystemConfigure();
public static string MicroAppToken = "";
public static string MicroAppBindingCode = "";
public static string microAppInterfaceDomainName = "http://wxyx.lyfz.net";
public static string microAppDomainName = "http://ivision.lyfz.net";
static string AuthCompanyLogin = String.Format("{0}/api.php/Auth/companyLogin", microAppInterfaceDomainName);
string GetaccountAndPwdString(BLL.MicroApplet.MicroAppletAccount mAccount)
{
string pwdMd5 = "";
if (!String.IsNullOrEmpty(mAccount.Password))
{
pwdMd5 = LYFZ.WinAPI.SDKSecurity.MD5Encrypt(mAccount.Password).ToLower();
}
return String.Format("account_number={0}&password={1}", mAccount.Account, pwdMd5);
}
string GetMicroAppletUrl(string url, BLL.MicroApplet.MicroAppletAccount mAccount)
{
if (url.Contains("?"))
{
return String.Format("{0}&{1}", url, GetaccountAndPwdString(mAccount));
}
else
{
return String.Format("{0}?{1}", url, GetaccountAndPwdString(mAccount));
}
}
public static MicroAppLoginReturn CompanyLoginReturnToken(string account, string pwd)
{
MicroAppLoginReturn retModel = new MicroAppLoginReturn();
try
{
string postData = String.Format("&phone_no={0}&password={1}&openid=&verification_code=", account, LYFZ.WinAPI.SDKSecurity.MD5Encrypt(pwd).ToLower());
string postReturnString = LYFZ.WinAPI.CustomPublicMethod.HttpWebRequestPOST(AuthCompanyLogin, postData, Encoding.UTF8);
if (postReturnString.IndexOf("{") == 0)
{
dynamic postReturnObj = Newtonsoft.Json.JsonConvert.DeserializeObject(postReturnString);
if (Convert.ToInt32(postReturnObj["meta"]["code"]) == 200)
{
MicroAppToken = postReturnObj["body"]["token"];
retModel.UserInfo = Newtonsoft.Json.JsonConvert.SerializeObject(postReturnObj["body"]);
retModel.AppToken = MicroAppToken;
userInfo = retModel.UserInfo;
string getReturnString = HttpWebRequestGET(String.Format("{0}/api.php/IvisionBackstage/getBindAccount", microAppInterfaceDomainName), MicroAppToken, Encoding.UTF8);
dynamic getReturnObj = Newtonsoft.Json.JsonConvert.DeserializeObject(getReturnString);
if (getReturnString.IndexOf("{") == 0 && Convert.ToInt32(getReturnObj["meta"]["code"]) == 200)
{
retModel.Code = 200;
retModel.Message = "OK";
retModel.Bind_code = getReturnObj["body"]["bind_code"];
}
}
else
{
MicroAppToken = "";
retModel.Message = postReturnObj["meta"]["message"];
}
}
else
{
MicroAppToken = "";
retModel.Message = postReturnString;
}
}
catch (Exception ex)
{
retModel.Message = ex.Message;
}
return retModel;
}
static List _CompayList = new List();
public static List _MicroAppletAccountList = new List();
public static bool LoadMicroConfigure()
{
bool retBl = false;
try
{
_MicroAppletAccountList = new BLL.BLL_ErpSystemConfigure().GetMicroAppletAccountList();
if (_CompayList.Count <= 0)
{
_CompayList = new LYFZ.BLL.BLL_ErpCompanyInfo().GetModelList("1=1");
}
retBl = true;
}
catch (Exception ex)
{
MessageBoxCustom.Show("加载微信小程序帐号信息时出错:" + ex.Message);
}
return retBl;
}
static LYFZ.Model.Model_ErpCompanyInfo GetCompanyInfo(string shopID)
{
if (_CompayList.Any(c => c.Company_DividedShop.ToLower() == shopID.ToLower()))
{
return _CompayList.Find(c => c.Company_DividedShop.ToLower() == shopID.ToLower());
}
else
{
return new Model.Model_ErpCompanyInfo();
}
}
public static void BindMicroAppletAccountList(ComponentLibrary.ComboBoxEx comBox, string dfShopID)
{
comBox.Items.Clear();
foreach (BLL.MicroApplet.MicroAppletAccount mAccount in _MicroAppletAccountList)
{
LYFZ.Model.Model_ErpCompanyInfo comp = GetCompanyInfo(mAccount.ShopID);
ItemValue item = new ItemValue(mAccount, String.Format("【{0}】{1}", comp.Company_Name,mAccount.Account));
comBox.Items.Add(item);
if (dfShopID.Trim().Length > 0 && mAccount.ShopID.ToLower() == dfShopID.ToLower())
{
comBox.SelectedItem = item;
}
else if (dfShopID.Trim().Length <= 0 && mAccount.ShopID.ToLower() == LYFZ.Software.MainBusiness.CommonLogical.SuccessfulLogin.CurrentCompanyInfoID.ToLower())
{
comBox.SelectedItem = item;
}
}
}
public static BLL.MicroApplet.MicroAppletAccount GetMicroAppletAccount(string shopID)
{
if (_MicroAppletAccountList.Any(m => m.ShopID.ToLower() == shopID.ToLower()))
{
return _MicroAppletAccountList.Find(m => m.ShopID.ToLower() == shopID.ToLower());
}
else {
return new BLL.MicroApplet.MicroAppletAccount();
}
}
private void ContextMenuHandler_RunContextMenu(object sender, Chromium.Event.CfxRunContextMenuEventArgs e)
{
e.SetReturnValue(true);
}
void btnRefresh_Click(object sender, EventArgs e)
{
// isSetLocalStorage = false;
myRefresh(this.cbDelHuanChun.Checked);
}
void myRefresh(bool isDelHuanChun)
{
if (isDelHuanChun)
{
CurrentMicroAppletShopID = "";
MicroAppToken = "";
this.frmPage.Browser.ReloadIgnoreCache();
if (this.comAccountList.SelectedItem != null)
{
BLL.MicroApplet.MicroAppletAccount mAccount = (BLL.MicroApplet.MicroAppletAccount)((ItemValue)this.comAccountList.SelectedItem).Value;
LoadMicroAppletPage(mAccount);
}
}
else
{
this.frmPage.Browser.Reload();
}
}
///
/// Web GET方式提交
///
///
/// 字符编码
///
public static string HttpWebRequestGET(string url, string token, Encoding _Encoding = null, bool isUrlDecode = true)
{
try
{
System.GC.Collect();
if (_Encoding == null)
{
_Encoding = System.Text.Encoding.Default;
}
if (System.Net.ServicePointManager.DefaultConnectionLimit < 512)
{
System.Net.ServicePointManager.DefaultConnectionLimit = 512;
}
LYFZ.WinAPI.CustomPublicMethod.SetServicePointManagerSecurityProtocol(url);
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
webRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/json,*/*";
webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; Zune 4.7; BOIE9;ZHCN)";
webRequest.Method = "GET";
webRequest.Timeout = 600000;
webRequest.KeepAlive = false;
webRequest.ProtocolVersion = System.Net.HttpVersion.Version10;
webRequest.Headers.Add("token", token);
// webRequest.Headers.Add(headers);
/* if (_ContentType != null)
{
webRequest.ContentType = _ContentType;
}
if (myCookieContainer != null)
{
webRequest.CookieContainer = myCookieContainer;
}*/
System.Threading.Thread.Sleep(5);
using (System.Net.WebResponse wr = webRequest.GetResponse())
{
System.IO.StreamReader str = new System.IO.StreamReader(wr.GetResponseStream(), _Encoding);
string strMsg = str.ReadToEnd();
str.Close();
str.Dispose();
str = null;
webRequest.Abort();
webRequest = null;
if (isUrlDecode)
{
strMsg = System.Web.HttpUtility.UrlDecode(strMsg);
}
return strMsg;
//在这里对接收到的页面内容进行处理
}
}
catch (Exception ex)
{
System.Net.ServicePointManager.Expect100Continue = false;
return "Request failed,Exception:" + ex.Message;
}
}
///
/// Web POST方式提交
///
///
///
/// 字符编码
/// Content-typeHTTP 标头的值
///
public static string HttpWebRequestPOST(string url, string postData, MicroAppLoginReturn appLogin, Encoding _Encoding = null, bool isUrlDecode = true)
{
try
{
//string postData = "CustomerID=LYFZTYUF"
// + "&ShareTitle=" + System.Web.HttpUtility.UrlEncode("OK!Test")
// + "&ShareDescription=" + System.Web.HttpUtility.UrlEncode("利亚方舟微相册分享体验微 信号:340508706@qq.com");
System.GC.Collect();
if (_Encoding == null)
{
_Encoding = Encoding.Default;
}
byte[] byteArray = _Encoding.GetBytes(postData);
if (System.Net.ServicePointManager.DefaultConnectionLimit < 512)
{
System.Net.ServicePointManager.DefaultConnectionLimit = 512;
}
//这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
// System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
LYFZ.WinAPI.CustomPublicMethod.SetServicePointManagerSecurityProtocol(url);
// string url = "http://localhost:8000/webService/POSTText?t=" + DateTime.Now.ToString("yyyyMMddhhmmss"); //POST到网站
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new Uri(url));
// System.Net.CookieContainer cookies = new System.Net.CookieContainer();
// webRequest.CookieContainer=cookies;
webRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; Zune 4.7; BOIE9;ZHCN)";
webRequest.KeepAlive = false;
webRequest.ProtocolVersion = System.Net.HttpVersion.Version10;
webRequest.Method = "POST";
webRequest.Headers.Add("token", appLogin.AppToken);
webRequest.Headers.Add("bindcode", appLogin.Bind_code);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
/* webRequest.Headers.Add(headers);
if (myCookieContainer != null)
{
webRequest.CookieContainer = myCookieContainer;
}*/
System.IO.Stream newStream = webRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
newStream = null;
//接收返回信息:
webRequest.Timeout = 600000;
System.Threading.Thread.Sleep(10);
using (System.Net.WebResponse wr = webRequest.GetResponse())
{
System.IO.StreamReader str = new System.IO.StreamReader(wr.GetResponseStream(), _Encoding);
string strMsg = str.ReadToEnd();
str.Close();
str.Dispose();
str = null;
webRequest.Abort();
webRequest = null;
if (isUrlDecode)
{
strMsg = System.Web.HttpUtility.UrlDecode(strMsg);
}
return strMsg;
//在这里对接收到的页面内容进行处理
}
}
catch (Exception ex)
{
System.Net.ServicePointManager.Expect100Continue = false;
return "Request failed,Exception:" + ex.Message;
}
}
}
}