old_flsystem/应用/TBRebate/Class1 - 复制.cs

2298 lines
156 KiB
C#
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Api.Framework;
using Api.Framework.Cps;
using Api.Framework.Enums;
using Api.Framework.Events;
using Api.Framework.Model;
using Api.Framework.SDK;
using Api.Framework.Timers;
using Api.Framework.Tools;
using Chat.Framework;
using Chat.Framework.WXSdk;
using Chat.Framework.WXSdk.Events;
using Chat.Framework.WXSdk.Implement;
using CsharpHttpHelper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using TBRebate.Entitys;
using TBRebate.Properties;
using static Api.Framework.Cps.AlimamaApi;
using static Api.Framework.Tools.TBHelper;
using static TBRebate.Enums;
using System.Text;
namespace TBRebate
{
public class Class1 : Plugin
{
public Class1()
{
this.Logo = Resources.;
this.Name = Resources.PluginName;
this.Note = Resources.PluginNote;
}
#region
public static Config Config;
private MainForm mainForm = null;
#endregion
public override void Start()
{
try
{
var session = ApiClient.GetSession();
#region
if (session.TableExist<fl_plugin_tbrebate_tbtgw>())
{
var tbtgws = session.Find<fl_plugin_tbrebate_tbtgw>("select * from fl_plugin_tbrebate_tbtgw").ToList();
if (tbtgws != null)
{
foreach (var item in tbtgws)
{
//插入主推广位数据
session.Insertable(new fl_adzone_info()
{
adzone_name = item.pid_chief_name, //推广位名称
adzone_pid = item.pid_chief, //推广位pid
adzone_pid_cps_name = item.pid_chief_cps_name, //推广位cps名称
alliance_id = (int)CpsType., //联盟id
robot_id = item.robot_id, //机器人id
group_id = string.Empty, //群id
is_download = false, //不下载
member_id = 0, //私人id
onoff = item.onoff, //不禁用
custom_type = Resources.SoftwareType, //自定义类型
extend = "chief"
}).ExecuteCommand();
//插入副推广位数据
session.Insertable(new fl_adzone_info()
{
adzone_name = item.pid_deputy_name, //推广位名称
adzone_pid = item.pid_deputy, //推广位pid
adzone_pid_cps_name = item.pid_deputy_cps_name, //推广位cps名称
alliance_id = (int)CpsType., //联盟id
robot_id = item.robot_id, //机器人id
group_id = string.Empty, //群id
is_download = false, //不下载
member_id = 0, //私人id
onoff = item.onoff, //不禁用
custom_type = Resources.SoftwareType, //自定义类型
extend = "deputy"
}).ExecuteCommand();
}
}
session.DropTable<fl_plugin_tbrebate_tbtgw>();
}
if (!session.TableExist<fl_plugin_tbrebate_ignoreids>())
{
session.CreateTable<fl_plugin_tbrebate_ignoreids>();
session.AddIndex<fl_plugin_tbrebate_ignoreids>("itemid");//增加索引.
session.AddIndex<fl_plugin_tbrebate_ignoreids>("losetime");//增加索引.
}
#endregion
//创建配置文件
Config = this.ReadConfig<Config>();
SDK.ReciveIMEvent += SDK_ReciveIMEvent;
SDK.OrderNoticeEvent += SDK_OrderNoticeEvent;
SDK.WebRequestEvent += SDK_WebRequestEvent;
InitIgnoreidsCache();
}
catch (Exception ex)
{
this.OnLog(ex.Message);
}
}
private void SDK_WebRequestEvent(object sender, WebRequestEvents e)
{
try
{
#region
if (e.Param.ContainsKey("method"))//方法名称
{
var method = e.Param["method"].ToLower();
switch (method)
{
case "tbitem":
{
var resultJson = string.Empty;
try
{
if (!e.Param.ContainsKey("ids")) throw new Exception("缺少参数ids");
var ids = e.Param["ids"].ToString();
if (!string.IsNullOrWhiteSpace(ids))
{
var idList = ids.Replace("", ",").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToList();
if (idList.Count != 0)
{
InitIgnoreidsCache(idList);
}
}
}
catch (Exception ex)
{
e.Send(ex.Message, 100);
return;
}
e.Send("请求成功", 200);
}
break;
}
}
#endregion
}
catch (Exception ex)
{
this.OnLog("淘宝返利web接收数据异常" + ex.Message);
}
}
public static List<fl_plugin_tbrebate_ignoreids> ignoreidsCache = new List<fl_plugin_tbrebate_ignoreids>();
private void InitIgnoreidsCache(List<string> idList = null)
{
var nowTime = HttpExtend.GetTimeStamp(DateTime.Now);
var session = ApiClient.GetSession();
var temps = new List<fl_plugin_tbrebate_ignoreids>();
var ignoreids = session.Find<fl_plugin_tbrebate_ignoreids>("select * from fl_plugin_tbrebate_ignoreids");
if (ignoreids != null && ignoreids.Count != 0)
{
temps = ignoreids.Where(f => f.losetime < nowTime).ToList();
if (temps != null && temps.Count != 0)
session.Deleteable(temps).ExecuteCommand();
temps = ignoreids.Where(f => f.losetime >= nowTime).ToList();
}
if (idList != null)
{
foreach (var itemid in idList)
{
var temp = temps.FirstOrDefault(f => f.itemid == itemid);
if (temp == null)
session.Insertable<fl_plugin_tbrebate_ignoreids>(new fl_plugin_tbrebate_ignoreids() { itemid = itemid, losetime = HttpExtend.GetTimeStamp(DateTime.Now.AddDays(2)) }).ExecuteCommand();
else
{
temp.losetime = HttpExtend.GetTimeStamp(DateTime.Now.AddDays(2));
session.Updateable(temp).ExecuteCommand();
}
}
}
ignoreidsCache = session.Find<fl_plugin_tbrebate_ignoreids>("select * from fl_plugin_tbrebate_ignoreids");
}
public override void ShowForm()
{
try
{
if (mainForm == null || mainForm.IsDisposed)
{
mainForm = new MainForm();
mainForm.Show();
}
mainForm.TopMost = true;
mainForm.TopMost = false;
}
catch (Exception ex)
{
this.OnLog(ex.Message);
}
}
public override void Stop()
{
try
{
SessionExt.Clear();
if (mainForm != null)
{
mainForm.CloseForm();
mainForm = null;
}
}
catch (Exception ex)
{
this.OnLog(ex.Message);
}
}
private void SDK_OrderNoticeEvent(object sender, OrderNoticeEvent e)
{
try
{
if (e.ChatType == CpsType.)
{
//this.OnLog("淘宝订单:" + HttpHelper.ObjectToJson(e));
var session = ApiClient.GetSession();
//订单信息
var order_tb = e.Order as fl_order_alimama;
if (order_tb == null) return;
if (e.Member != null)
{
#region
var robot_info = session.FindRobotInfo(e.Member.robot_name.Trim(), e.Member.robot_type);
if (robot_info != null)
{
var mess = string.Empty;
var point = HttpHelper.JsonToObject<ItemPoint>(order_tb.db_point) as ItemPoint;
#region ()
if (e.Customer == null)
{
var prevent_theft_cache = session.FindSingle<fl_prevent_theft_cache>("select * from fl_prevent_theft_cache where order_id = @order_id", new { order_id = order_tb.trade_id });//防止上级多次触发
if (prevent_theft_cache == null)
{
var isHint = false;
if (!string.IsNullOrWhiteSpace(order_tb.seller_id) && e.Member.status != MemberType.)
{
#region ()
if (Class1.Config.AShop_SameCommodity_Switch)
{
var frequency = session.Find<fl_order_alimama>("select * from fl_order_alimama where db_userid = @db_userid and num_iid = @num_iid", new { db_userid = order_tb.db_userid, num_iid = order_tb.num_iid }).Count;//获取同价店铺同一件商品购买的次数
if (Class1.Config.AShop_SameCommodity_Number <= frequency)
{
if (Class1.Config.AShop_SameCommodity_OperateType == OperateType.)
{
if (!session.TemporaryBypassedBlack(e.Member))
{
e.Member.status = MemberType.; //拉入黑名单
session.SaveOrUpdate(e.Member);
session.FindBlacklistMemberInfos(true);//刷新黑名单缓存
ApiClient.SendMessage(robot_info, e.Member.username, new VariateReplace().CommonReplace(Config.Blocked_RestrictTip, order_tb, e.Member, point), order_tb.msg_groupid);
ApiClient.SendNoticeMessage($@"嫌疑用户拉黑
————
事件类型:订单检测
微信账号:{robot_info.name}
微信昵称:{robot_info.nick}
客户账号:{e.Member.username}
客户昵称:{e.Member.usernick}
拉黑原因:用户购买同一商品{frequency}次", Config.notice_robotname);
e.Cancel = true;
{
prevent_theft_cache = new fl_prevent_theft_cache();
prevent_theft_cache.operate_type = Class1.Config.AShop_SameCommodity_OperateType;
prevent_theft_cache.member_id = e.Member.id;
prevent_theft_cache.item_id = order_tb.num_iid;
prevent_theft_cache.mall_id = order_tb.seller_id;
prevent_theft_cache.order_id = order_tb.trade_id;
prevent_theft_cache.cps_type = CpsType.;
session.Insertable(prevent_theft_cache).ExecuteCommand();
}
if (Config.AShop_SameCommodity_UserTop)
{
if (robot_info.type == ChatType.)
{
var wx = ChatClient.WXClient.Values.FirstOrDefault(f => f.WeixinHao == robot_info.name /*&& f.WeixinType == WeixinType.Grpc微信*/);
if (wx != null)
{
//var ipad = wx as WXClientImpl_IPAD;
//if (ipad != null)
// ipad.EditContacts(e.Member.username, EditContactsType.置顶, e.Member.usernick);
wx.EditContacts(e.Member.username, EditContactsType., e.Member.usernick);
}
}
}
return;
}
}
else if (Class1.Config.AShop_SameCommodity_OperateType == OperateType.)
{
ApiClient.SendNoticeMessage($@"嫌疑用户警告
————
事件类型:订单检测
微信账号:{robot_info.name}
微信昵称:{robot_info.nick}
客户账号:{e.Member.username}
客户昵称:{e.Member.usernick}
警告原因:用户购买同一商品{frequency}次", Config.notice_robotname);
isHint = true;
}
}
}
#endregion
#region ()
if (!isHint && Class1.Config.AShop_DifferentCommodity_Switch)
{
var frequency = session.Find<fl_order_alimama>("select * from fl_order_alimama where db_userid = @db_userid and seller_id = @seller_id", new { db_userid = order_tb.db_userid, seller_id = order_tb.seller_id }).Count;
if (Class1.Config.AShop_DifferentCommodity_Number <= frequency)
{
if (Class1.Config.AShop_DifferentCommodity_OperateType == OperateType.)
{
if (!session.TemporaryBypassedBlack(e.Member))
{
e.Member.status = MemberType.; //拉入黑名单
session.SaveOrUpdate(e.Member);
session.FindBlacklistMemberInfos(true);//刷新黑名单缓存
ApiClient.SendMessage(robot_info, e.Member.username, new VariateReplace().CommonReplace(Config.Blocked_RestrictTip, order_tb, e.Member, point), order_tb.msg_groupid);
ApiClient.SendNoticeMessage($@"嫌疑用户拉黑
————
事件类型:订单检测
微信账号:{robot_info.name}
微信昵称:{robot_info.nick}
客户账号:{e.Member.username}
客户昵称:{e.Member.usernick}
拉黑原因:用户在同家店铺购买{frequency}次", Config.notice_robotname);
e.Cancel = true;
{
prevent_theft_cache = new fl_prevent_theft_cache();
prevent_theft_cache.operate_type = Class1.Config.AShop_DifferentCommodity_OperateType;
prevent_theft_cache.member_id = e.Member.id;
prevent_theft_cache.item_id = order_tb.num_iid;
prevent_theft_cache.mall_id = order_tb.seller_id;
prevent_theft_cache.order_id = order_tb.trade_id;
prevent_theft_cache.cps_type = CpsType.;
session.Insertable(prevent_theft_cache).ExecuteCommand();
}
if (Config.AShop_DifferentCommodity_UserTop)
{
if (robot_info.type == ChatType.)
{
var wx = ChatClient.WXClient.Values.FirstOrDefault(f => f.WeixinHao == robot_info.name /*&& f.WeixinType == WeixinType.Grpc微信*/);
if (wx != null)
{
//var ipad = wx as WXClientImpl_IPAD;
//if (ipad != null)
// ipad.EditContacts(e.Member.username, EditContactsType.置顶, e.Member.usernick);
wx.EditContacts(e.Member.username, EditContactsType., e.Member.usernick);
}
}
}
return;
}
}
else if (Class1.Config.AShop_DifferentCommodity_OperateType == OperateType.)
{
ApiClient.SendNoticeMessage($@"嫌疑用户警告
————
事件类型:订单检测
微信账号:{robot_info.name}
微信昵称:{robot_info.nick}
客户账号:{e.Member.username}
客户昵称:{e.Member.usernick}
警告原因:用户在同家店铺购买{frequency}次", Config.notice_robotname);
isHint = true;
}
}
}
#endregion
}
#region
if (!isHint && Class1.Config.ReceivingTimeCheck_Switch && order_tb.tk_status == (int)AlimamaOrderStatus. && e.Member.status != MemberType.)
{
if (order_tb.earning_time != DateTime.MinValue)
{
var timeLag = (int)Math.Floor((order_tb.earning_time - order_tb.create_time).TotalHours);
if (timeLag <= Class1.Config.ReceivingTimeCheck_Hour)
{
if (Class1.Config.ReceivingTimeCheck_OperateType == OperateType.)
{
if (!session.TemporaryBypassedBlack(e.Member))
{
e.Member.status = MemberType.; //拉入黑名单
session.SaveOrUpdate(e.Member);
session.FindBlacklistMemberInfos(true);//刷新黑名单缓存
ApiClient.SendMessage(robot_info, e.Member.username, new VariateReplace().CommonReplace(Config.Blocked_RestrictTip, order_tb, e.Member, point), order_tb.msg_groupid);
ApiClient.SendNoticeMessage($@"嫌疑用户拉黑
————
事件类型:订单检测
微信账号:{robot_info.name}
微信昵称:{robot_info.nick}
客户账号:{e.Member.username}
客户昵称:{e.Member.usernick}
拉黑原因:订单收货时间间隔{timeLag}小时", Config.notice_robotname);
e.Cancel = true;
{
prevent_theft_cache = new fl_prevent_theft_cache();
prevent_theft_cache.operate_type = Class1.Config.ReceivingTimeCheck_OperateType;
prevent_theft_cache.member_id = e.Member.id;
prevent_theft_cache.item_id = order_tb.num_iid;
prevent_theft_cache.mall_id = order_tb.seller_id;
prevent_theft_cache.order_id = order_tb.trade_id;
prevent_theft_cache.cps_type = CpsType.;
session.Insertable(prevent_theft_cache).ExecuteCommand();
}
if (Config.ReceivingTimeCheck_UserTop)
{
if (robot_info.type == ChatType.)
{
var wx = ChatClient.WXClient.Values.FirstOrDefault(f => f.WeixinHao == robot_info.name /*&& f.WeixinType == WeixinType.Grpc微信*/);
if (wx != null)
{
//var ipad = wx as WXClientImpl_IPAD;
//if (ipad != null)
//ipad.EditContacts(e.Member.username, EditContactsType.置顶, e.Member.usernick);
wx.EditContacts(e.Member.username, EditContactsType., e.Member.usernick);
}
}
}
return;
}
}
else if (Class1.Config.ReceivingTimeCheck_OperateType == OperateType.)
{
ApiClient.SendNoticeMessage($@"嫌疑用户警告
————
事件类型:订单检测
微信账号:{robot_info.name}
微信昵称:{robot_info.nick}
客户账号:{e.Member.username}
客户昵称:{e.Member.usernick}
警告原因:订单收货时间间隔{timeLag}小时", Config.notice_robotname);
}
}
}
}
#endregion
}
}
#endregion
switch (e.OrderNoticeType)
{
case OrderNoticeType.:
{
if (Config.UserOrderChangeSwitch == SwitchType. && !ApiClient.Setting.SystemConfig.message_warning_switch)
{
#region /
var is_tlj = session.CheckIsTljOrder(order_tb.adzone_id);
#endregion
if (!is_tlj)
mess = _GetOrderStateMess(order_tb.db_status, SettleType., order_tb, e.Member, point);
else
{
if (order_tb.db_status == SystemOrderStatus.)
mess = Config.TljPaymentTip;
else if (order_tb.db_status == SystemOrderStatus.)
mess = Config.TljSettlementTip;
else//淘礼金其他订单状态不给用户提示
return;
mess = new VariateReplace().CommonReplace(mess, order_tb, e.Member, point);
}
if (!string.IsNullOrEmpty(e.Member.username) && !string.IsNullOrEmpty(mess))
ApiClient.SendMessage(robot_info, e.Member.username, mess, order_tb.msg_groupid);
}
}
return;
case OrderNoticeType.:
if (Config.AgentReceivedCommissionSwitch == SwitchType.)
{
if (e.Customer != null && point.AwardOne != 0)
{
if (order_tb.db_status == SystemOrderStatus.)
mess = Config.ClientOrderRefund_OneLevelTip;
else if (order_tb.db_status == SystemOrderStatus.)
mess = Config.OrderPaymentInform_OneLevelTip;
else if (order_tb.db_status == SystemOrderStatus.)
mess = Config.OrderCountermandInform_OneLevelTip;
else if (order_tb.db_status == SystemOrderStatus.)
mess = Config.OrderSettlement_OneLevelTip;
}
}
break;
case OrderNoticeType.:
if (Config.AgentReceivedCommissionSwitch == SwitchType.)
{
if (e.Customer != null)
{
if (order_tb.db_status == SystemOrderStatus.)
mess = Config.ClientOrderRefund_TwoLevelTip;
else if (order_tb.db_status == SystemOrderStatus.)
mess = Config.OrderPaymentInform_TwoLevelTip;
else if (order_tb.db_status == SystemOrderStatus.)
mess = Config.OrderCountermandInform_TwoLevelTip;
else if (order_tb.db_status == SystemOrderStatus.)
mess = Config.OrderSettlement_TwoLevelTip;
}
}
break;
case OrderNoticeType.:
if (Config.AgentReceivedCommissionSwitch == SwitchType.)
{
if (e.Customer != null)
{
if (order_tb.db_status == SystemOrderStatus.)
mess = Config.ClientOrderRefund_ThreeLevelTip;
else if (order_tb.db_status == SystemOrderStatus.)
mess = Config.OrderPaymentInform_ThreeLevelTip;
else if (order_tb.db_status == SystemOrderStatus.)
mess = Config.OrderCountermandInform_ThreeLevelTip;
else if (order_tb.db_status == SystemOrderStatus.)
mess = Config.OrderSettlement_ThreeLevelTip;
}
}
break;
case OrderNoticeType.:
if (Config.PrincipalReceivedCommissionSwitch == SwitchType.)
{
if (e.Customer != null)
{
if (order_tb.db_status == SystemOrderStatus.)
mess = Config.ClientOrderRefund_LeaderTip;
else if (order_tb.db_status == SystemOrderStatus.)
mess = Config.OrderPaymentInform_LeaderTip;
else if (order_tb.db_status == SystemOrderStatus.)
mess = Config.OrderCountermandInform_LeaderTip;
else if (order_tb.db_status == SystemOrderStatus.)
mess = Config.OrderSettlement_LeaderTip;
}
}
break;
default:
break;
}
if (!ApiClient.Setting.SystemConfig.message_warning_switch && !string.IsNullOrEmpty(e.Member.username) && !string.IsNullOrWhiteSpace(mess))
//ApiClient.SendMessage(robot_info, e.Member.username, new VariateReplace().CommonReplace(mess, order_tb, e.Member, point).Replace("[下级昵称]", string.IsNullOrEmpty(e.Customer.realnick) ? e.Customer.usernick : e.Customer.realnick));
ApiClient.SendMessage(robot_info, e.Member.username, new VariateReplace().CommonReplace(mess, order_tb, e.Member, point).Replace("[下级昵称]", e.Customer.realnick));
}
#endregion
}
else
{
#region
var querys = session.Find<queryhist_temp>("select robot_name,type,userid from fl_query_hist where itemid=@itemid and adzoneid = @adzoneid and userid > 0 and crt_time>@time group by userid,type,robot_name", new { itemid = order_tb.num_iid, adzoneid = order_tb.adzone_id, time = DateTime.Now.AddHours(-24).ToString("yyyy-MM-dd HH:mm:ss") });
if (querys.Count > 0)
{
for (int i = 0; i < querys.Count; i++)
{
try
{
if (querys[i].type != CpsType.) continue;
//未绑定的数量
var unbound_count = int.Parse(session.FindTable($"select count(id) as num from fl_order_alimama where trade_parent_id = @trade_parent_id and db_userid != 0", new { trade_parent_id = order_tb.trade_parent_id }).Rows[0]["num"].ToString());
if (unbound_count != 0) break;//已经被绑定直接停止
var queryhist_temp = querys[i];
var userid = queryhist_temp.userid;
var robot_name = queryhist_temp.robot_name;
var robot_info = session.Find<fl_robot_info>("select * from fl_robot_info where name = @name", new { name = robot_name }).FirstOrDefault();//机器人类型应该是没有的,直接通过机器人name查询机器人信息
if (robot_info != null)
{
Thread.Sleep(5000);
var wxbase = Chat.Framework.ChatClient.WXClient.Values.ToList().FirstOrDefault(f => f.WeixinHao == robot_name);
if (wxbase != null /*&& wxbase.WeixinType == WeixinType.Grpc微信*/ && wxbase.Status == WxStatus.线)
{
var member = session.FindMemberInfoById(userid);
if (member != null)
{
ApiClient.SendMessage(robot_info, member.username, Config.LotUserQueryBindTip.Replace("[商品标题]", order_tb.item_title));
session.ExcuteSQL("update fl_query_hist set userid = @newuserid where itemid = @itemid and adzoneid = @adzoneid and robot_name = @robotname and userid = @userid", new { newuserid = (i - querys.Count + 1), itemid = order_tb.num_iid, adzoneid = order_tb.adzone_id, robotname = robot_name, userid = member.id });
}
}
}
}
catch (Exception)
{ }
}
}
#endregion
}
}
}
catch (Exception ex)
{
this.OnLog(ex.Message);
}
}
private static List<string> Regex_Items = new List<string>() { @",\\""price\\"":{\\""priceText\\"":\\""(?<price>.+?)\\"",", @",\\""price\\"":\\""(?<price>.+?)\\""", @",\\""priceText\\"":\\""(?<price>.+?)\\""," };
/// <summary>
/// 判断网页链接的正则表达式
/// </summary>
private string Reg_CheckIsUrl = @"(?<链接>((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?)";
private void SDK_ReciveIMEvent(object sender, ReciveIMEvent e)
{
try
{
//过滤表情xml和卡片xml
if ((e.Message.Contains(@"<appmsg appid=") || e.Message.Contains(@"<msg><emoji")) && !e.Message.Contains(@"点击链接,再选择浏览器咑閞")) return;
if (!OrderHelper.IsCurrentCpsMess(e.Message, CpsType.)) return;
var session = ApiClient.GetSession();
var _member = e.GetMemberinfo();
#region
var messTmp = e.Message.Trim();
if (Regex.IsMatch(e.Message.Trim(), @"^(\d{4})\s(\d{4})\s(\d{4})\s(\d{4})\s(\d{3})$"))
messTmp = messTmp.Replace(" ", "");
if (Regex.IsMatch(messTmp, @"^\d{18,19}$"))
{
var orderid = e.Message.Trim();//用户发送的订单号
var orders_temp = session.Find<fl_order_alimama>("select * from fl_order_alimama where trade_parent_id = @trade_parent_id", new { trade_parent_id = orderid });
if (orders_temp != null && orders_temp.Count != 0)
{
var member = orders_temp.FirstOrDefault(f => f.db_userid != 0 && f.db_userid != _member.id);
if (member != null)
{
e.SendMessage(Config.OccupyOrderErrorTip.Replace("[订单号]", orderid));
return;
}
var notices = new List<OrderNoticeEvent>();
var downAlimamaTimer = new DownAlimamaTimer();
#region ,
var bindOrders = orders_temp.Where(f => f.db_userid != 0).ToList();
if (bindOrders != null && bindOrders.Count != 0)
{
foreach (var order in bindOrders)
{
var point = HttpHelper.JsonToObject<ItemPoint>(order.db_point) as ItemPoint;
_member = e.GetMemberinfo(true);
if (order.db_status == SystemOrderStatus.)
e.SendMessage(new VariateReplace().CommonReplace(Config.OrderRepetBindTip, order, _member, point));
else
e.SendMessage(_GetOrderStateMess(order.db_status, (order.db_status == SystemOrderStatus. ? SettleType. : SettleType.), order, _member, point));
Thread.Sleep(500);
}
//return;
}
#endregion
#region ( => )
var notBindOrders = orders_temp.Where(f => f.db_userid == 0).ToList();
if (notBindOrders != null && notBindOrders.Count != 0)
{
if (notBindOrders[0].create_time < ApiClient.Setting.SystemConfig.allow_bind_create_order_time)
{
e.SendMessage($"订单:{orderid},已经过了有效绑定时间!");
return;
}
foreach (var order in notBindOrders)
{
if (order.db_status == SystemOrderStatus.)
order.db_endtime = DateTime.Now.AddMinutes(-5);//重新结算的话,需要将订单的冻结时间重新赋值,让后台处理
//没有绑定用户的订单进行绑定
order.db_userid = _member.id;
order.db_robotname = e.RobotName;
order.db_robottype = e.RobotInfo.type;
order.msg_groupid = e.Groupid;
bool is_allrebatesactivity = false;
#region
var adzone = session.FindAdzoneInfos().FirstOrDefault(f => f.alliance_id == (int)CpsType. && f.custom_type == Resources.TbAllRebatesSoftwareType && f.adzone_pid.EndsWith("_" + order.adzone_id));
if (adzone != null)
{
var allrebatesactivity_infos = session.Find<fl_plugin_allrebatesactivity_info>("select * from fl_plugin_allrebatesactivity_info where goods_id = @goods_id", new { goods_id = order.num_iid });
if (allrebatesactivity_infos != null && allrebatesactivity_infos.Count != 0)
{
var allrebatesactivity_info = allrebatesactivity_infos.FirstOrDefault(f => f.time_begin <= order.create_time && order.create_time <= f.time_end && f.groups.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(z => Convert.ToInt64(z.Trim())).ToList().Contains(_member.group_id) && f.robots.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(z => z.Trim()).ToList().Contains(order.db_robotname));
if (allrebatesactivity_info != null)
{
//TODO这里还要判断已经成交的列表中是否存在订单数量
//var allrebatesactivity_orderlists = session.Queryable<fl_plugin_allrebatesactivity_orderlist>().Where(f => f.activity_id == allrebatesactivity_info.id && f.mid == _member.id).ToList();
var allrebatesactivity_orderlists = session.Find<fl_plugin_allrebatesactivity_orderlist>("select * from fl_plugin_allrebatesactivity_orderlist where activity_id = @activity_id and mid = @mid", new { activity_id = allrebatesactivity_info.id, mid = _member.id });
int purchased_quantity = 0;//已经购买的数量
if (allrebatesactivity_orderlists != null && allrebatesactivity_orderlists.Count != 0)
{
foreach (var item in allrebatesactivity_orderlists)
{
var order_alimama = session.FindSingle<fl_order_alimama>("select * from fl_order_alimama where id = @id", new { id = item.oid });
if (order_alimama != null)
{
if (order_alimama.db_status == SystemOrderStatus. || order_alimama.db_status == SystemOrderStatus.退 || order_alimama.db_status == SystemOrderStatus.退 || order_alimama.db_status == SystemOrderStatus. || order_alimama.db_status == SystemOrderStatus. || order_alimama.db_status == SystemOrderStatus.退 || order_alimama.db_status == SystemOrderStatus.)
{
purchased_quantity += order_alimama.item_num;
}
}
}
}
if (allrebatesactivity_info.limit_quantity_number >= (order.item_num + purchased_quantity))
{
is_allrebatesactivity = true;
var return_money = (double)((decimal)allrebatesactivity_info.return_money * (decimal)order.item_num);
var point = @"{""Type"":0,""Commission"":0,""SumPoint"":" + order.pub_share_pre_fee + @",""UserPoint"":" + return_money + @",""AwardOne"":0,""AwardTwo"":0,""AwardThree"":0,""AwardCreate"":0}";
order.db_point = point;
order.db_userpoint = return_money;
var robot = session.FindRobots().FirstOrDefault(f => f.name == order.db_robotname && order.db_robottype == f.type);
if (robot != null)
{
var allrebatesactivity_orderlist = new fl_plugin_allrebatesactivity_orderlist()
{
activity_id = allrebatesactivity_info.id,
mid = _member.id,
rid = robot.id,
oid = order.id
};
session.Saveable(allrebatesactivity_orderlist).ExecuteCommand();
}
}
}
}
}
#endregion
#region ,
if (!is_allrebatesactivity)
{
#region ,
var isTljOrder = session.CheckIsTljOrder(order.adzone_id);
#endregion
//计算的佣金 - 判断使用设置模式,符合将扣除用户自定义预扣佣金
var commission = session.GetTbComparisonFeeRate(order);
//var itempoint = session.FindItemPoint(_member, isTljOrder ? 0 : (order.commission == 0 ? order.pub_share_pre_fee : order.commission), order.item_num, CpsType.阿里妈妈);
var itempoint = session.FindItemPoint(_member, isTljOrder ? 0 : commission, order.item_num, CpsType.);
if (itempoint != null)
{
order.db_point = HttpHelper.ObjectToJson(itempoint);
order.db_userpoint = itempoint.UserPoint;
}
}
#endregion
if (_member != null)
{
_member.bind_order++;
_member = session.UpdateMemberGroup(_member);
}
#region
var record = session.FindStatisticsRecord(_member.id);
if (record == null)
{
record = new fl_statistics_record() { uid = _member.id, ex2 = 0, ex4 = CsharpHttpHelper.HttpExtend.GetTimeStamp(DateTime.Now) };
session.Saveable<fl_statistics_record>(record).ExecuteCommand();
}
else
{
if (record.ex2 == 0 && record.ex4 == 0)
{
record.ex4 = CsharpHttpHelper.HttpExtend.GetTimeStamp(DateTime.Now);
session.Saveable<fl_statistics_record>(record).ExecuteCommand();
}
}
#endregion
session.SaveOrUpdate(order);
#region
if (ApiClient.Setting.SystemConfig.order_alimama_last_auto_capture == SwitchType.)
{
//订单尾号和用户进行绑定
if (session.FindAlimamaOrderLastnums().FirstOrDefault(f => f.userid == _member.id) == null)
{
session.Insertable(new fl_alimama_order_lastnum() { userid = _member.id, lastnumber = order.trade_parent_id.Substring(order.trade_parent_id.Length - 6, 6) }).ExecuteCommand();
session.FindAlimamaOrderLastnums(true);
}
}
#endregion
downAlimamaTimer.UpdateOrder(order, notices, session, isFrontData: true);
}
}
#endregion
#region
if (!ApiClient.Setting.SystemConfig.message_warning_switch && notices.Count != 0)
{
var tasks = TimerTask.GetTimer<Update_NoticeQueue>() as Update_NoticeQueue;
foreach (var item in notices)
{
if (item.IsRewards)
tasks.Add(item);
else
SDK_OrderNoticeEvent(this, item);
}
}
#endregion
e.Cancel = true;
}
else
{
e.SendMessage(Config.NotFoundOrderErrorTip.Replace("[订单号]", orderid));
//加入缓存
var bind = session.FindBindCache(orderid);
if (bind == null)
{
session.Insertable(new fl_bind_cache() { crt_time = DateTime.Now, db_robotid = e.RobotInfo.id, orderid = orderid, groupid = e.Groupid, db_userid = _member.id }).ExecuteCommand();
session.FindBindCache(orderid, true);
}
e.Cancel = true;
}
return;
}
if (OrderHelper.IsOrderId(e.Message.Trim()))
return;
#endregion
#region
var tbinfoTemps = session.FindTbInfoTempGroups();
var tbInfoTemp = tbinfoTemps.FirstOrDefault(f => f.name == e.RobotInfo.name && f.onoff == false);
if (tbInfoTemp != null)
{
fl_cps_member tb_cps = null;
var pid = string.Empty;//使用的推广位
var isDefault = true;
if (!string.IsNullOrWhiteSpace(e.Groupid))//群pid
{
var groupAdzone = session.FindAdzoneInfos().FirstOrDefault(f => f.alliance_id == (int)CpsType. && f.custom_type == PrivateAdzoneCustomType.pid.ToString() && f.group_id == e.Groupid);
if (groupAdzone != null && !string.IsNullOrWhiteSpace(groupAdzone.adzone_pid))
{
pid = groupAdzone.adzone_pid;
var pids = pid.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
if (pids.Length > 1)
{
string username = pids[1];
tb_cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType. && f.username == username);
isDefault = false;
}
}
}
if (isDefault)//私人pid
{
var memberAdzone = session.FindAdzoneInfos().FirstOrDefault(f => f.alliance_id == (int)CpsType. && f.custom_type == PrivateAdzoneCustomType.pid.ToString() && f.member_id == _member.id);
if (memberAdzone != null && !string.IsNullOrWhiteSpace(memberAdzone.adzone_pid))//私人推广位
{
pid = memberAdzone.adzone_pid;
var pids = pid.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
if (pids.Length > 1)
{
string username = pids[1];
tb_cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType. && f.username == username);
isDefault = false;
}
}
}
if (isDefault)//默认推广位
{
var tgw = Tools.GetTuiguangwei(e.RobotInfo.name, _member, tbInfoTemp);
if (tgw == null || string.IsNullOrWhiteSpace(tgw.Pid)) throw new Exception("@阿里妈妈推广位异常.请检测后重试!!");
pid = tgw.Pid;
var pids = pid.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
if (pids.Length > 1)
{
string username = pids[1];
tb_cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType. && f.username == username);//通过判断用户的购物积分,来判断用户使用哪个推广位
}
}
if (tb_cps == null) throw new Exception("@阿里妈妈推广位异常,请检测后重试!");
else
{
string keyword = string.Empty;
bool IsTitle = false;//是否是标题
AlimamaApi api = CpsClient.CreateAlimamaRequest(tb_cps);
if (api == null) throw new Exception("@创建阿里妈妈API请求失败");
//var sss = api.SendTaobao("taobao.tbk.sc.invitecode.get", new { relation_app = "common", code_type = 3 });
//var sss = api.SendTaobao("taobao.tbk.sc.publisher.info.save", new { info_type = 1, inviter_code = "RGA87B" });
//Dictionary<string, object> sss = null;
//try
//{
// sss = api.SendTaobao("taobao.tbk.sc.publisher.info.get", new { info_type = 2, relation_app = "common" });
//}
//catch (Exception ex)
//{}
if (Config.SearchCustomSwitch == SwitchType.)
{
if (!string.IsNullOrWhiteSpace(Config.SearchPrefix))
{
//判断接收到的内容是都满足标题搜索或者关键词搜索
var reg = Regex.Match(e.Message.Trim(), Config.SearchPrefix);//获取到符合关键词搜索的正则
if (reg.Success)
{
keyword = reg.Groups["关键词"].Value.Trim();
if (Config.SearchTitleSwitch == SwitchType.)//开启淘宝标题搜索
{
var ileng = Tools.GetStringLength(keyword);//这里判断字符串的长度为 30个汉字,或者60个字节
if (ileng >= 40 && ileng <= 100 && !Regex.IsMatch(keyword, Tools.Reg_CheckIsUrl))//非链接并且字符串字节长度符合小于等于40,大等于60的条件,才去查询标题
IsTitle = true;
}
if (!IsTitle && !string.IsNullOrEmpty(keyword))
{
var searchUrl = api.ComposeTbCms(pid, keyword);//内置的搜索机制
e.SendMessage(Config.PreciseSearchSuccessTip.Replace("[关键词]", keyword).Replace("[购买地址]", ApiClient.ShortURL(searchUrl, Config.SearchDwzType).Result));
return;
}
}
}
}
if (string.IsNullOrEmpty(keyword) && Config.SearchTitleSwitch == SwitchType. && !Regex.IsMatch(e.Message, Tools.Reg_QRCode_Goods))//开启淘宝标题搜索
{
if (!Regex.IsMatch(e.Message, "[^A-Za-z0-9]?([A-Za-z0-9]{11})[^A-Za-z0-9]?") && !Regex.Match(e.Message, @"[!,<>!@#\$%\^&*()_+~>·@#¥%……&*()——+,。、!?\?]").Success)
{
var ipad = sender as WeixinBase;
var _event = e.Event as WXReiceveFriendMsg;
if (ipad != null && ((_event != null && !_event.IsRobot) || e.Event is WXReceiveGroupMsg))
{
var ileng = Tools.GetStringLength(e.Message.Trim());//这里判断字符串的长度为 30个汉字,或者60个字节
if (ileng >= 40 && ileng <= 100 && !Regex.IsMatch(e.Message.Trim(), Tools.Reg_CheckIsUrl))//非链接并且字符串字节长度符合小于等于40,大等于60的条件,才去查询标题
{
keyword = e.Message.Trim();
IsTitle = true;
}
}
}
}
string message = e.Message;
//宝贝二维码识别
string QRCodeUrl = string.Empty;
if (Config.QRCodeSearchSwitch == SwitchType.)
{
var reg_ = Regex.Match(e.Message, Tools.Reg_QRCode_Goods);
if (reg_.Success)
{
QRCodeUrl = Util.DecodeQRCode(reg_.Groups["二维码图片"].Value);//解析的二维码图片所得到的二维码内容
message = message.Replace(reg_.Groups["二维码图片"].Value, "");
}
}
var pid_split = pid.Split('_');
var tbAnalysis = new TBHelper.TbAnalysis();
var item_id = string.Empty;
try
{
item_id = tbAnalysis.FindItemIdByUrlAndTklAndMkl(string.IsNullOrEmpty(QRCodeUrl) ? message : QRCodeUrl, api, pid_split);
}
catch (Exception ex)
{
if (string.IsNullOrEmpty(keyword))
{
//if (ex.Message.Contains("淘口令解析结果无效") || ex.Message.Contains("淘口令转链处理异常"))
//{
e.SendMessage(Config.SearchNoCommissionTip.Replace("[关键词]", "").Replace("[商品标题]", ""));
//}
return;
}
}
Dictionary<string, object> objData = null;
if (!string.IsNullOrWhiteSpace(item_id))
{
var temp = ignoreidsCache.FirstOrDefault(f => f.itemid == item_id);
if (temp != null && temp.losetime >= HttpExtend.GetTimeStamp(DateTime.Now))
{
e.SendMessage(Config.SearchNoCommissionTip.Replace("[关键词]", "").Replace("[商品标题]", ""));
return;
}
}
//标题搜索和商品id搜索
if (!string.IsNullOrEmpty(keyword) || !string.IsNullOrEmpty(item_id))
{
#region ID
if (Class1.Config.ItemIDRestrictList.Contains(item_id))
{
e.SendMessage(Config.ItemIDRestrictTip.Replace("[商品ID]", item_id));
return;
}
#endregion
if (!ApiClient.Setting.SystemConfig.message_warning_switch)
e.SendMessage(Config.SearchingTip);//正在搜索提示
var title = string.Empty;//商品标题
bool titleSuccess = false;//判断是否是标题搜索
for (int ii = 0; ii < 2; ii++)
{
titleSuccess = false;
try
{
//是否检测优惠券金额等信息
bool isCheckCoupon = true;
Dictionary<string, object> privilege = null;
Tools.GroupAdzoneCount(_member, tbInfoTemp);
if (!string.IsNullOrEmpty(keyword) && IsTitle)//符合搜索标题查询宝贝
{
try
{
objData = api.SendTaobao("taobao.tbk.sc.material.optional", new { adzone_id = pid_split[3], site_id = pid_split[2], q = keyword });
titleSuccess = true;
}
catch (Exception _ex)
{
objData = null;
}
}
else if (!string.IsNullOrEmpty(item_id))//符合搜索宝贝id的条件
{
try
{
objData = api.SendTaobao("taobao.tbk.item.info.get", new { num_iids = item_id });
}
catch (Exception ex)
{
try
{
if (ex.Message.Contains("sub_msg\":\"无结果"))
{
#region
privilege = tbAnalysis.GetPrivilege(api, item_id, pid_split);
if (privilege != null)
{
var _title = string.Empty;
var _price = "0";
var _sellerNick = "天猫淘宝";
var _pic = "https://timgsa.baidu.com/timg?image&size=b999_1000&imgtype=0&src=http%3A%2F%2Fpic.58pic.com%2F58pic%2F16%2F56%2F08%2F01358PICSDM_1024.jpg";
var tbinfo = tbAnalysis.FindTbInfoByItemId(item_id);
if (tbinfo != null)
{
_price = tbinfo.Price;
_sellerNick = tbinfo.ShopName;
_pic = tbinfo.ItemImage;
_title = tbinfo.ItemTitle;
}
else
{
HttpHelper http = new HttpHelper();
var item = new HttpItem();
item.URL = @"https://acs.m.taobao.com/gw/mtop.taobao.detail.getdetail/6.0/?data={%22itemNumId%22%3A%22" + item_id + @"%22&qq-pf-to=pcqq.group";
var _html = http.GetHtml(item).Html;
if (_html.Contains("SUCCESS::调用成功"))
{
var reg = Regex.Match(_html, @"item"":{""itemId"":""\d+?"",""title"":""(?<title>.+?)"",""");
if (!reg.Success)
reg = Regex.Match(_html, @"""title"":""(?<title>.+?)"",""");
if (reg.Success)
_title = reg.Groups["title"].Value;
foreach (var reg_item in Regex_Items)
{
reg = Regex.Match(_html, reg_item);
if (reg.Success)
{
_price = reg.Groups["price"].Value;
if (_price.Contains("-"))
_price = _price.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries)[0];
break;
}
}
reg = Regex.Match(_html, @"""sellerNick"":""(?<sellerNick>.+?)""");
if (reg.Success)
_sellerNick = reg.Groups["sellerNick"].Value;
reg = Regex.Match(_html, @"""images"":\[""(?<pic>.+?)""");
if (reg.Success)
{
_pic = reg.Groups["pic"].Value;
if (!_pic.StartsWith("http"))
_pic = "https:" + _pic;
}
}
}
if (_price == "0" || string.IsNullOrWhiteSpace(_price))//自己拼装的json 无法获取
{
e.SendMessage(Config.SearchNoCommissionTip.Replace("[关键词]", keyword).Replace("[商品标题]", title));//未搜索到提示语
return;
}
var temp = "{\"tbk_item_info_get_response\":{\"results\":{\"n_tbk_item\":[{\"cat_leaf_name\":\"\",\"cat_name\":\"\",\"item_url\":\"https:\\/\\/detail.tmall.com\\/item.htm?id=" + item_id + "\",\"material_lib_type\":\"1,2\",\"nick\":\"" + _sellerNick + "\",\"num_iid\":" + item_id + ",\"pict_url\":\"" + _pic + "\",\"provcity\":\"\",\"reserve_price\":\"" + _pic + "\",\"seller_id\":0,\"small_images\":{\"string\":[\"\",\"\",\"\",\"\"]},\"title\":\"" + _title + "\",\"user_type\":1,\"volume\":18,\"zk_final_price\":\"" + _price + "\"}]},\"request_id\":\"\"}}";
var dic = HttpExtend.JsonToDictionary(temp);
if (dic != null)
{
var key = "tbk_item_info_get_response";
if (!dic.ContainsKey(key)) throw new Exception($"key = {key},html = {temp}");
dic = dic[key] as Dictionary<String, object>;
if (dic.ContainsKey("result")) objData = dic["result"] as Dictionary<string, object>;
if (dic.ContainsKey("results")) objData = dic["results"] as Dictionary<string, object>;
}
}
#endregion
}
}
catch (Exception _ex)
{
objData = null;
}
}
}
if (objData != null && objData.Count != 0)
{
object tbk_temp_info = null;
if (titleSuccess)
{
if (objData.ContainsKey("result_list"))
{
var result_list = objData["result_list"] as Dictionary<string, object>;
if (result_list != null && result_list.ContainsKey("map_data"))
{
var map_data = (result_list["map_data"]) as ArrayList;
if (map_data != null && map_data.Count != 0)
tbk_temp_info = map_data[0];
}
}
}
else
{
var n_tbk_item = (objData["n_tbk_item"]) as ArrayList;
if (n_tbk_item != null && n_tbk_item.Count != 0)
tbk_temp_info = n_tbk_item[0];
}
var tbk_item = tbk_temp_info as Dictionary<string, object>;
//店铺ID
var sellerId = string.Empty;
if (tbk_item.ContainsKey("pict_url"))
{
var reg = Regex.Match(tbk_item["pict_url"].ToString(), @"i\d+?/(?<店铺Id>\d+?)/");
if (reg.Success)
{
sellerId = reg.Groups["店铺Id"].Value;
if (Config.SellerIDRestrictlist.Contains(sellerId))
{
e.SendMessage(Config.SellerIDRestrictTip.Replace("[店铺ID]", sellerId));
return;
}
}
}
//商品链接
var item_url = tbk_item["item_url"].ToString();
//店铺名称
var nick = tbk_item["nick"].ToString();
//商品主图
var pict_url = tbk_item["pict_url"].ToString();
//商品id
item_id = tbk_item["num_iid"].ToString();
//商品标题//&lt; &gt;&amp;&quot;&copy; <>&",©;
title = tbk_item["title"].ToString().Replace("", "").Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&").Replace("&quot;", "\"").Replace(" &copy;", "©");//这里有个看不见的字符,要将其替换掉
//原价
var reserve_price = double.Parse(tbk_item["reserve_price"].ToString());
//商品折扣价格(当前售价)
var zk_final_price = double.Parse(tbk_item["zk_final_price"].ToString());
//30天销量
var volume = "0";
if (tbk_item.ContainsKey("volume"))
volume = tbk_item["volume"].ToString();
//券后价
var endPrice = -1d;
#region
var activityId = string.Empty;
activityId = tbAnalysis.activityId;
var regs = Regex.Matches(e.Message, Reg_CheckIsUrl);
if (regs != null && regs.Count != 0)
{
foreach (Match item in regs)
{
if (item.Groups["链接"].Value.Contains("uland.taobao"))
{
var reg = Regex.Match(item.Groups["链接"].Value, @"activityId=(?<活动ID>[A-Za-z0-9]+)");
if (reg.Success)
activityId = reg.Groups["活动ID"].Value;
#region ID并且检测是否为屏蔽的店铺
//https://uland.taobao.com/quan/detail?sellerId=2203061148088&activityId=91a71ae9a76445288724467712c0083d
reg = Regex.Match(item.Groups["链接"].Value, @"sellerId=(?<店铺ID>[^&]*)");
if (reg.Success)
{
sellerId = reg.Groups["店铺ID"].Value;
if (Config.SellerIDRestrictlist.Contains(sellerId))
{
e.SendMessage(Config.SellerIDRestrictTip.Replace("[店铺ID]", sellerId));
return;
}
}
#endregion
break;
}
}
}
#endregion
#region
//最高佣金率
var commission_rate = 0d;
if (Config.QueryComparisonSwitch == QueryComparisonType.使)
{
#region special_id
var special_id = string.Empty;
try
{
var _data = new { info_type = 2, relation_app = "common", external_id = $"u:{e.GetMemberinfo().username}" };
var result = api.SendTaobao("taobao.tbk.sc.publisher.info.get", _data);
if (result != null && result.ContainsKey("data"))
{
var data = result["data"] as Dictionary<string, object>;
if (data != null && data.ContainsKey("inviter_list"))
{
var inviter_list = data["inviter_list"] as Dictionary<string, object>;
if (inviter_list != null && inviter_list.ContainsKey("map_data"))
{
var map_data = inviter_list["map_data"] as ArrayList;
if (map_data != null && map_data.Count != 0)
{
foreach (Dictionary<string, object> item in map_data)
{
if (item.ContainsKey("special_id"))
special_id = item["special_id"].ToString();
}
}
}
}
}
}
catch (Exception ex)
{ }
#endregion
if (privilege == null || !privilege.ContainsKey("min_commission_rate"))
privilege = tbAnalysis.GetPrivilege(api, item_id, pid_split, $"u:{e.GetMemberinfo().username}", special_id);
}
else if (Config.QueryComparisonSwitch == QueryComparisonType.使)
{
if (privilege == null || !privilege.ContainsKey("max_commission_rate"))
privilege = tbAnalysis.GetPrivilege(api, item_id, pid_split);
}
else if (Config.QueryComparisonSwitch == QueryComparisonType.使)
{
if (privilege == null)
privilege = tbAnalysis.GetPrivilege(api, item_id, pid_split);
if (privilege != null && !privilege.ContainsKey("min_commission_rate"))
{
var privilege_temp = tbAnalysis.GetPrivilege(api, item_id, pid_split, $"u:{e.GetMemberinfo().username}");
if (privilege_temp != null)
{
var data_temp = privilege_temp["data"] as Dictionary<string, object>;
if (data_temp != null && data_temp.ContainsKey("min_commission_rate"))
commission_rate = double.Parse(data_temp["min_commission_rate"].ToString());
}
}
}
if (privilege == null) throw new Exception("申请高佣失败,原因未知");
#endregion
var privilege_data = privilege["data"] as Dictionary<string, object>;
#region
if (commission_rate == 0)
{
if (privilege_data.ContainsKey("max_commission_rate"))
commission_rate = double.Parse(privilege_data["max_commission_rate"].ToString());
else if (privilege_data.ContainsKey("min_commission_rate"))
commission_rate = double.Parse(privilege_data["min_commission_rate"].ToString());
}
//this.OnLog("min_commission_rate3 = " + commission_rate);
#endregion
//优惠券地址
var coupon_click_url = string.Empty;
var coupon_price = 0.00d;
//if (privilege_data.ContainsKey("coupon_info") && Config.NoCouponModeSwitch == SwitchType.关闭)//无券
//{
// var quan_reg = Regex.Match(privilege_data["coupon_info"].ToString(), @"满\d+元减(\d+)元");
// if (quan_reg.Success)
// coupon_price = double.Parse(quan_reg.Groups[1].Value);
//}
//else
// coupon_price = 0.00d;
#region 202011717:43:22 ()xxx
//if (Config.NoCouponModeSwitch == SwitchType.开启)//无券
// coupon_price = 0.00d;
//else if (privilege_data.ContainsKey("mm_coupon_info") && privilege_data.ContainsKey("coupon_info"))
//{
// //正常优惠券
// var coupon_price_temp = 0d;
// var condition_price_temp = 0d;
// var quan_reg = Regex.Match(privilege_data["coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元");
// if (quan_reg.Success)
// {
// coupon_price_temp = double.Parse(quan_reg.Groups["减"].Value);
// condition_price_temp = double.Parse(quan_reg.Groups["满"].Value);
// }
// //妈妈优惠券
// var mm_coupon_price_temp = 0d;
// var mm_condition_price_temp = 0d;
// var mm_quan_reg = Regex.Match(privilege_data["mm_coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元");
// if (mm_quan_reg.Success)
// {
// mm_coupon_price_temp = double.Parse(mm_quan_reg.Groups["减"].Value);
// mm_condition_price_temp = double.Parse(mm_quan_reg.Groups["满"].Value);
// }
// var condition_price = 0d;//满减条件
// if (mm_condition_price_temp <= zk_final_price && condition_price_temp <= zk_final_price)
// {
// if (mm_coupon_price_temp > coupon_price_temp)
// {
// coupon_price = mm_coupon_price_temp;
// condition_price = mm_condition_price_temp;
// coupon_click_url = privilege_data["mm_coupon_click_url"].ToString();
// }
// else
// {
// coupon_price = coupon_price_temp;
// condition_price = condition_price_temp;
// coupon_click_url = privilege_data["coupon_click_url"].ToString();
// }
// }
// //妈妈优惠券条件金额小于最小的售价并且妈妈优惠券金额比正常优惠券高
// else if (mm_condition_price_temp <= zk_final_price && mm_coupon_price_temp > coupon_price_temp)
// {
// coupon_price = mm_coupon_price_temp;
// condition_price = mm_condition_price_temp;
// coupon_click_url = privilege_data["mm_coupon_click_url"].ToString();
// }
// //正常优惠券条件金额小于最小的售价并且正常优惠券金额比妈妈优惠券高
// else if (condition_price_temp <= zk_final_price && mm_coupon_price_temp < coupon_price_temp)
// {
// coupon_price = coupon_price_temp;
// condition_price = condition_price_temp;
// coupon_click_url = privilege_data["coupon_click_url"].ToString();
// }
// else if (mm_condition_price_temp > zk_final_price && condition_price_temp > zk_final_price)
// {
// if (mm_coupon_price_temp < coupon_price_temp)
// {
// coupon_price = coupon_price_temp;
// condition_price = condition_price_temp;
// coupon_click_url = privilege_data["coupon_click_url"].ToString();
// }
// else
// {
// coupon_price = mm_coupon_price_temp;
// condition_price = mm_condition_price_temp;
// coupon_click_url = privilege_data["mm_coupon_click_url"].ToString();
// }
// }
// var multiple = Math.Ceiling(condition_price / zk_final_price);
// if (multiple != 0)
// zk_final_price = zk_final_price * multiple;
//}
//else if (privilege_data.ContainsKey("mm_coupon_info"))
//{
// var quan_reg = Regex.Match(privilege_data["mm_coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元");
// if (quan_reg.Success)
// {
// coupon_price = double.Parse(quan_reg.Groups["减"].Value);
// var condition_price = double.Parse(quan_reg.Groups["满"].Value);
// var multiple = Math.Ceiling(condition_price / zk_final_price);
// if (multiple != 0)
// zk_final_price = zk_final_price * multiple;
// coupon_click_url = privilege_data["mm_coupon_click_url"].ToString();
// }
//}
//else if (privilege_data.ContainsKey("coupon_info"))
//{
// var quan_reg = Regex.Match(privilege_data["coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元");
// if (quan_reg.Success)
// {
// coupon_price = double.Parse(quan_reg.Groups["减"].Value);
// var condition_price = double.Parse(quan_reg.Groups["满"].Value);
// var multiple = Math.Ceiling(condition_price / zk_final_price);
// if (multiple != 0)
// zk_final_price = zk_final_price * multiple;
// coupon_click_url = privilege_data["coupon_click_url"].ToString();
// }
//}
//else
//{
// //没有优惠券检测大淘客是否有优惠券
// if (string.IsNullOrWhiteSpace(activityId))
// {
// activityId = TBHelper.FindGoodsActivityIdAll(item_id, out sellerId, out oldPrice);
// if (oldPrice != -1)
// zk_final_price = oldPrice;
// }
//}
#endregion
//优惠券满减比较的价格
var coupon_comparison_price = (reserve_price > zk_final_price ? reserve_price : zk_final_price);
#region 202011717:44:08 (,)
if (Config.NoCouponModeSwitch == SwitchType.)//无券
coupon_price = 0.00d;
else
{
//检测大淘客是否有优惠券,和价格
//activityId = TBHelper.FindGoodsActivityIdAll(item_id, out sellerId, out payPrice);
TbExCoupon exCoupon = TBHelper.FindGoodsCouponInfo(item_id);
if (exCoupon != null)
{
activityId = exCoupon.activityId;
sellerId = exCoupon.sellerId;
coupon_price = exCoupon.couponAmount;
zk_final_price = exCoupon.salePrice;
endPrice = exCoupon.endPrice;
if (privilege_data.ContainsKey("coupon_click_url"))
coupon_click_url = privilege_data["coupon_click_url"].ToString();
else if (privilege_data.ContainsKey("mm_coupon_click_url"))
coupon_click_url = privilege_data["mm_coupon_click_url"].ToString();
else
coupon_click_url = privilege_data["item_url"].ToString();
isCheckCoupon = false;
}
else
{
if (privilege_data.ContainsKey("mm_coupon_info") && privilege_data.ContainsKey("coupon_info"))
{
//正常优惠券
var coupon_price_temp = 0d;
var condition_price_temp = 0d;
var quan_reg = Regex.Match(privilege_data["coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元");
if (quan_reg.Success)
{
coupon_price_temp = double.Parse(quan_reg.Groups["减"].Value);
condition_price_temp = double.Parse(quan_reg.Groups["满"].Value);
}
//妈妈优惠券
var mm_coupon_price_temp = 0d;
var mm_condition_price_temp = 0d;
var mm_quan_reg = Regex.Match(privilege_data["mm_coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元");
if (mm_quan_reg.Success)
{
mm_coupon_price_temp = double.Parse(mm_quan_reg.Groups["减"].Value);
mm_condition_price_temp = double.Parse(mm_quan_reg.Groups["满"].Value);
}
var condition_price = 0d;//满减条件
if (mm_condition_price_temp <= coupon_comparison_price && condition_price_temp <= coupon_comparison_price)
{
if (mm_coupon_price_temp > coupon_price_temp)
{
coupon_price = mm_coupon_price_temp;
condition_price = mm_condition_price_temp;
coupon_click_url = privilege_data["mm_coupon_click_url"].ToString();
}
else
{
coupon_price = coupon_price_temp;
condition_price = condition_price_temp;
coupon_click_url = privilege_data["coupon_click_url"].ToString();
}
}
//妈妈优惠券条件金额小于最小的售价并且妈妈优惠券金额比正常优惠券高
else if (mm_condition_price_temp <= coupon_comparison_price && mm_coupon_price_temp > coupon_price_temp)
{
coupon_price = mm_coupon_price_temp;
condition_price = mm_condition_price_temp;
coupon_click_url = privilege_data["mm_coupon_click_url"].ToString();
}
//正常优惠券条件金额小于最小的售价并且正常优惠券金额比妈妈优惠券高
else if (condition_price_temp <= coupon_comparison_price && mm_coupon_price_temp < coupon_price_temp)
{
coupon_price = coupon_price_temp;
condition_price = condition_price_temp;
coupon_click_url = privilege_data["coupon_click_url"].ToString();
}
else if (mm_condition_price_temp > coupon_comparison_price && condition_price_temp > coupon_comparison_price)
{
if (mm_coupon_price_temp < coupon_price_temp)
{
coupon_price = coupon_price_temp;
condition_price = condition_price_temp;
coupon_click_url = privilege_data["coupon_click_url"].ToString();
}
else
{
coupon_price = mm_coupon_price_temp;
condition_price = mm_condition_price_temp;
coupon_click_url = privilege_data["mm_coupon_click_url"].ToString();
}
}
var multiple = Math.Ceiling(condition_price / coupon_comparison_price);
if (multiple != 0)
zk_final_price = zk_final_price * multiple;
}
else if (privilege_data.ContainsKey("mm_coupon_info"))
{
var quan_reg = Regex.Match(privilege_data["mm_coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元");
if (quan_reg.Success)
{
coupon_price = double.Parse(quan_reg.Groups["减"].Value);
var condition_price = double.Parse(quan_reg.Groups["满"].Value);
var multiple = Math.Ceiling(condition_price / coupon_comparison_price);
if (multiple != 0)
zk_final_price = zk_final_price * multiple;
coupon_click_url = privilege_data["mm_coupon_click_url"].ToString();
}
}
else if (privilege_data.ContainsKey("coupon_info"))
{
var quan_reg = Regex.Match(privilege_data["coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元");
if (quan_reg.Success)
{
coupon_price = double.Parse(quan_reg.Groups["减"].Value);
var condition_price = double.Parse(quan_reg.Groups["满"].Value);
var multiple = Math.Ceiling(condition_price / coupon_comparison_price);
if (multiple != 0)
zk_final_price = zk_final_price * multiple;
coupon_click_url = privilege_data["coupon_click_url"].ToString();
}
}
else
{
////没有优惠券检测大淘客是否有优惠券
//if (string.IsNullOrWhiteSpace(activityId))
//{
// activityId = TBHelper.FindGoodsActivityIdAll(item_id, out sellerId, out oldPrice);
// if (oldPrice != -1)
// zk_final_price = oldPrice;
//}
}
}
}
#endregion
if (Config.NoCouponModeSwitch == SwitchType.)
{
if (string.IsNullOrWhiteSpace(coupon_click_url))
coupon_click_url = privilege_data.ContainsKey("mm_coupon_click_url") ? privilege_data["mm_coupon_click_url"].ToString() : privilege_data["coupon_click_url"].ToString();
#region
if (isCheckCoupon && !string.IsNullOrWhiteSpace(activityId) && !string.IsNullOrWhiteSpace(sellerId))
{
#region
var hsf_coupon = AlimamaApi.mtop_alimama_union_hsf_coupon_get(sellerId, activityId);
if (hsf_coupon != null)
{
if (hsf_coupon.ContainsKey("result"))
{
var result = hsf_coupon["result"] as Dictionary<string, object>;
var isValid = true;
//var isValid = false;
//if (result.ContainsKey("effectiveStartTime"))
//{
// var effectiveStartTime = result["effectiveStartTime"].ToString();
// try
// {
// isValid = DateTime.Now >= DateTime.Parse(effectiveStartTime);
// }
// catch (Exception ex)
// { }
//}
if (isValid)
{
if (result.ContainsKey("amount"))
coupon_price = double.Parse(result["amount"].ToString());
if (result.ContainsKey("startFee"))
{
//zk_final_price = double.Parse(result["startFee"].ToString());
var startFee = double.Parse(result["startFee"].ToString());
var multiple = Math.Ceiling(startFee / coupon_comparison_price);
if (multiple != 0)
zk_final_price = zk_final_price * multiple;
}
}
}
}
#endregion
}
else
{
if (privilege_data.ContainsKey("coupon_start_time"))
{
var coupon_start_time = DateTime.Parse(privilege_data["coupon_start_time"].ToString()) <= DateTime.Now.Date;
isCheckCoupon = false;
}
if (isCheckCoupon)
{
var coupon = api.CheckCoupon(coupon_click_url);//检查优惠券有效性
//优惠券过期
if (coupon != null && coupon.retStatus != 0 && string.IsNullOrWhiteSpace(activityId))
{
coupon_click_url = privilege_data["item_url"].ToString();
coupon_price = 0.00d;
zk_final_price = double.Parse(tbk_item["zk_final_price"].ToString());
}
}
}
#endregion
}
else
{
coupon_click_url = privilege_data["item_url"].ToString();
coupon_price = 0.00d;
}
if (endPrice == -1)
endPrice = (double)((decimal)zk_final_price - (decimal)coupon_price);
//券后 总佣金
//var useCoupon_totalCommFee = Math.Round((endPrice != -1 ? endPrice : (zk_final_price - coupon_price)) * (commission_rate / 100.00), 2);
var useCoupon_totalCommFee = Math.Round(endPrice * (commission_rate / 100.00), 2);
//用券后 给用户的佣金
var useCoupon_commFee = session.FindItemPoint(_member, useCoupon_totalCommFee, 1, CpsType.);
//不用券 佣金
var unuseCoupon_totalCommFee = Math.Round(zk_final_price * (commission_rate / 100.00), 2);
//不用券 给用户的佣金
var unuseCoupon_commFee = session.FindItemPoint(_member, unuseCoupon_totalCommFee, 1, CpsType.);
#region
//生成淘礼金链接,如果返回空,这不能生成.
var tljUrl = TljMethod(e.GetMemberinfo(true), ref api, item_id, useCoupon_commFee.UserPoint);
if (!string.IsNullOrWhiteSpace(tljUrl))
{
var _tlj = session.FindTljInfos().FirstOrDefault(f => f.username == api.Member.username);
if (_tlj != null)
pid_split = _tlj.adzone_pid.Split('_');
}
#endregion
//判断是否有淘礼金,有淘礼金用淘礼金
var couponUrl = string.IsNullOrWhiteSpace(tljUrl) ? coupon_click_url : tljUrl;
if (!string.IsNullOrWhiteSpace(activityId))
couponUrl = couponUrl + "&activityId=" + activityId;
#region tkl
var tkl = string.Empty;
try
{
string _pict_url = pict_url;
string _title = title;
if (Config.TKLCustomSwitch == SwitchType.)
{
if (!string.IsNullOrWhiteSpace(Config.TKLImageUrl))
_pict_url = Config.TKLImageUrl;
if (!string.IsNullOrWhiteSpace(Config.TKLTitle))
_title = Config.TKLTitle;
}
tkl = tbAnalysis.FindTKL(couponUrl, _title, _pict_url, api);
if (string.IsNullOrEmpty(tkl))
{
tkl = tbAnalysis.FindTKL(couponUrl, _title, _pict_url, api);
if (!string.IsNullOrEmpty(tkl)) break;
}
if (string.IsNullOrEmpty(tkl))
{
//e.SendMessage(ApiClient.Setting.SystemConfig.msg_error);
e.SendMessage(Config.SearchNoCommissionTip.Replace("[关键词]", keyword).Replace("[商品标题]", title));//未搜索到提示语
return;
}
}
catch (Exception ex)
{
throw new Exception($"@获取淘口令异常:{ex.Message} - {ex.StackTrace}");
}
#endregion
//淘口令的前/后符号有没有设置.有设置将替换掉
tkl = tbAnalysis.ReplaceTklModifier(tkl);
#region
couponUrl = tbAnalysis.FindShortUrlBySrcUrl(couponUrl, api);
#endregion
var composeUrl = api.ComposeTbClick(item_id, pict_url, tkl, couponUrl, true);//中间页地址
//this.OnLog($"中间页地址:({item_id}){composeUrl},原始连接:{couponUrl}");
#region
if (!string.IsNullOrWhiteSpace(tljUrl))
{
var mess = Config.TljSearchSuccess;
e.SendMessage(mess
.Replace("[商品标题]", mess.Contains("<appmsg") ? title.Replace("<", "").Replace(">", "") : title)
.Replace("[商品原价]", zk_final_price.ToString())
.Replace("[商品主图]", $"[图片={pict_url}]")
.Replace("[图片地址]", pict_url)
.Replace("[月销量]", volume)
.Replace("[店铺名称]", nick)
//.Replace("[券后返利]", useCoupon_commFee.UserPoint.ToString())
//.Replace("[劵后返利]", useCoupon_commFee.UserPoint.ToString())
//.Replace("[弃券返利]", unuseCoupon_commFee.UserPoint.ToString())
//.Replace("[券后价]", ((decimal)zk_final_price - (decimal)coupon_price).ToString())
//.Replace("[劵后价]", ((decimal)zk_final_price - (decimal)coupon_price).ToString())
.Replace("[优惠券金额]", (coupon_price != 0 ? coupon_price.ToString() : "0"))
.Replace("[淘礼金金额]", useCoupon_commFee.UserPoint.ToString())
.Replace("[购买地址]", couponUrl)
.Replace("[购买中间页地址]", composeUrl)
.Replace("[购买淘口令]", tkl)
.Replace("[共节省]", ((decimal)coupon_price + (decimal)useCoupon_commFee.UserPoint).ToString())
.Replace("[商品图片]", mess.Contains("[商品图片]") ? "[图片=" + ApiClient.GetQRImage(title, zk_final_price.ToString(), coupon_price.ToString(), ((decimal)zk_final_price - (decimal)coupon_price).ToString(), pict_url, composeUrl, ApiClient.QrImageType.B, CpsType.) + "]" : string.Empty)
);
}
#endregion
#region
else
{
//有券的情况
if (coupon_price != 0)
{
var mess = string.Empty;
if (e.ChatType == ChatType. || e.ChatType == ChatType. || (e.ChatType == ChatType.QQ && string.IsNullOrWhiteSpace(Config.QQSearchSuccessWithCouponTip)))
mess = Config.SearchSuccessWithCouponTip;
else
mess = Config.QQSearchSuccessWithCouponTip;
e.SendMessage(mess
.Replace("[商品标题]", mess.Contains("<appmsg") ? title.Replace("<", "").Replace(">", "") : title)
.Replace("[商品原价]", zk_final_price.ToString())
.Replace("[商品主图]", $"[图片={pict_url}]")
.Replace("[图片地址]", pict_url)
.Replace("[月销量]", volume)
.Replace("[店铺名称]", nick)
.Replace("[券后返利]", useCoupon_commFee.UserPoint.ToString())
.Replace("[劵后返利]", useCoupon_commFee.UserPoint.ToString())
.Replace("[弃券返利]", unuseCoupon_commFee.UserPoint.ToString())
.Replace("[劵后价]", "[券后价]")
.Replace("[券后价]", endPrice.ToString())
.Replace("[优惠券金额]", coupon_price.ToString())
.Replace("[购买地址]", couponUrl)
.Replace("[购买中间页地址]", composeUrl)
.Replace("[购买淘口令]", tkl)
.Replace("[共节省]", ((decimal)coupon_price + (decimal)useCoupon_commFee.UserPoint).ToString())
//.Replace("[商品图片]", mess.Contains("[商品图片]") ? "[图片=" + ApiClient.GetQRImage(title, zk_final_price.ToString(), coupon_price.ToString(), ((decimal)zk_final_price - (decimal)coupon_price).ToString(), pict_url, composeUrl, ApiClient.QrImageType.模板B, CpsType.阿里妈妈) + "]" : string.Empty)
.Replace("[商品图片]", mess.Contains("[商品图片]") ? "[图片=" + ApiClient.GetQRImage(title, zk_final_price.ToString(), coupon_price.ToString(), endPrice.ToString(), pict_url, composeUrl, ApiClient.QrImageType.B, CpsType.) + "]" : string.Empty)
);
}
else//没有券的情况
{
var mess = string.Empty;
if (e.ChatType == ChatType. || e.ChatType == ChatType. || (e.ChatType == ChatType.QQ && string.IsNullOrWhiteSpace(Config.QQSearchSuccessWithoutCouponTip)))
mess = Config.SearchSuccessWithoutCouponTip;
else
mess = Config.QQSearchSuccessWithoutCouponTip;
e.SendMessage(mess
.Replace("[商品标题]", mess.Contains("<appmsg") ? title.Replace("<", "").Replace(">", "") : title)
.Replace("[商品原价]", zk_final_price.ToString())
.Replace("[商品主图]", $"[图片={pict_url}]")
.Replace("[图片地址]", pict_url)
.Replace("[月销量]", volume)
.Replace("[店铺名称]", nick)
.Replace("[返利积分]", unuseCoupon_commFee.UserPoint.ToString())
.Replace("[购买地址]", couponUrl)
.Replace("[购买中间页地址]", composeUrl)
.Replace("[购买淘口令]", tkl)
.Replace("[共节省]", (useCoupon_commFee.UserPoint).ToString())
.Replace("[商品图片]", mess.Contains("[商品图片]") ? "[图片=" + ApiClient.GetQRImage(title, zk_final_price.ToString(), "0", zk_final_price.ToString(), pict_url, composeUrl, ApiClient.QrImageType.B, CpsType.) + "]" : string.Empty)
);
}
}
#endregion
#region ,,,
session.Insertable(new fl_query_hist()
{
crt_time = DateTime.Now,
type = CpsType.,
itemid = item_id,
groupid = e.Groupid,
robot_name = e.RobotName,
robot_type = e.ChatType,
userid = _member.id,
title = title,
adzoneid = pid_split[3],
mallid = sellerId,
}).ExecuteCommand();
session.UpdateRecord(_member.id);
var shared = new Dictionary<string, object>();
shared["msg_type"] = "查询宝贝";
shared["msg_username"] = _member.username;
var sharedEvent = new SharedEvents(shared);
EventClient.OnEvent(sender, sharedEvent);
#endregion
return;
}
else
{
var flag_tianmao = api.IsTianmao(item_id);
#region
if (string.IsNullOrWhiteSpace(keyword) && string.IsNullOrWhiteSpace(title) && (flag_tianmao || Config.SearchTitleSwitch_NoCommission == SwitchType. || Config.SearchNoCommissionTip.Contains("[商品标题]")))
{
var reg = Regex.Match(e.Message, @"【(?<标题>.+)】");
if (reg.Success)
title = reg.Groups["标题"].Value;
if (string.IsNullOrEmpty(title))
{
#region
HttpHelper http = new HttpHelper();
var item = new HttpItem();
item.URL = @"https://acs.m.taobao.com/gw/mtop.taobao.detail.getdetail/6.0/?data={%22itemNumId%22%3A%22" + item_id + @"%22&qq-pf-to=pcqq.group";
var _html = http.GetHtml(item).Html;
if (_html.Contains("SUCCESS::调用成功"))
{
reg = Regex.Match(_html, @"""title"":""(?<title>[^""]{10,})"",""");
if (reg.Success)
title = reg.Groups["title"].Value;
}
else
{
var html = string.Empty;
for (int i = 0; i < 4; i++)
{
HttpItem httpItem = new HttpItem()
{
URL = @"https://item.taobao.com/item.htm?id=" + item_id,//宝贝的链接
Method = "GET",
Timeout = 100000,
ReadWriteTimeout = 30000,
IsToLower = false,
UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",
Accept = "text/html, application/xhtml+xml, */*",
ContentType = "application/x-www-form-urlencoded",
Allowautoredirect = true,
AutoRedirectCookie = true
};
http = new HttpHelper();
var result = http.GetHtml(httpItem);
if (!(result != null && (result.Html.Contains("操作超时")) || result.Html.Contains("基础连接已经关闭")))
{
html = result.Html;
break;
}
Thread.Sleep(200);
}
reg = Regex.Match(html, @"<meta name=""keywords"" content=""(?<标题>.+?)""/>");
if (reg.Success)
{
title = reg.Groups["标题"].Value.Replace("淘宝,掏宝,网上购物,店铺, ", "");
if (title.Last() == '.')
title = title.Substring(0, title.Length - 1);
}
else
{
}
}
#endregion
}
}
#endregion
if (flag_tianmao)
{
var adzone = session.FindAdzoneInfos().FirstOrDefault(f => f.custom_type == Resources.TbActivitySoftwareType && f.robot_id == e.RobotInfo.id);
if (adzone != null)
{
var group = session.FindAdzoneGroups(CpsType.).FirstOrDefault(f => f.id == adzone.adzone_group);
if (group != null)
{
var activity = Tools.GetActivityTuiguangwei(e.RobotInfo.name, tbInfoTemp);
if (activity == null) return;
var pids = activity.Pid.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
if (pids.Length > 1)
{
string username = pids[1];
tb_cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType. && f.username == username);//通过判断用户的购物积分,来判断用户使用哪个推广位
}
if (tb_cps == null) throw new Exception("@阿里妈妈推广位异常,请检测后重试 !");
api = CpsClient.CreateAlimamaRequest(tb_cps);
if (api == null) throw new Exception("@创建阿里妈妈API请求失败");
#region
var tkl = tbAnalysis.FindTKL(activity.ShortUrl, "复制宝贝标题,再天猫精选中搜索", "https://img.alicdn.com/tfs/TB1MaLKRXXXXXaWXFXXXXXXXXXX-480-260.png", api);
if (!string.IsNullOrWhiteSpace(tkl))
{
if (!string.IsNullOrEmpty(title))
{
title = title.Replace("这个#聚划算团购#宝贝不错:", "").Replace("(分享自@手机淘宝android客户端)", "");
var temp_url = api.ComposeTbClick(item_id, "https://img.alicdn.com/tfs/TB1MaLKRXXXXXaWXFXXXXXXXXXX-480-260.png", tkl, activity.ShortUrl, true, -1, Config.CoercePageUrl.Trim());//中间页地址
e.SendMessage(Config.CoerceSearchSuccessTip
.Replace("[商品标题]", title)
.Replace("[商品原价]", "未知")
.Replace("[商品主图]", "")//$"[图片 ={tbInfo.ItemImage}]")
.Replace("[月销量]", "未知")
.Replace("[店铺名称]", "未知")
.Replace("[购买中间页地址]", temp_url)
.Replace("[购买淘口令]", tkl)
.Replace("[图片地址]", "")
);
#region ,,,
session.Insertable(new fl_query_hist()
{
crt_time = DateTime.Now,
type = CpsType.,
itemid = item_id,
groupid = e.Groupid,
robot_name = e.RobotName,
robot_type = e.ChatType,
userid = _member.id,
title = title,
adzoneid = activity.Pid.Split('_')[3],
mallid = string.Empty
}).ExecuteCommand();
session.UpdateRecord(_member.id);
var _shared = new Dictionary<string, object>();
_shared["msg_type"] = "查询宝贝";
_shared["msg_username"] = _member.username;
EventClient.OnEvent(sender, new SharedEvents(_shared));
#endregion
return;
}
}
#endregion
}
}
}
session.UpdateRecord(_member.id);
var shared = new Dictionary<string, object>();
shared["msg_type"] = "查询宝贝";
shared["msg_username"] = _member.username;
var sharedEvent = new SharedEvents(shared);
EventClient.OnEvent(sender, sharedEvent);
if (string.IsNullOrWhiteSpace(keyword) && ii == 0 && !string.IsNullOrWhiteSpace(title) && Config.SearchTitleSwitch_NoCommission == SwitchType.)
{
keyword = title;
IsTitle = true;
var searchUrl = api.ComposeTbCms(pid, keyword);//内置的搜索机制
e.SendMessage(Config.SearchTitle_NoCommissionTip.Replace("[商品标题]", title).Replace("[购买地址]", ApiClient.ShortURL(searchUrl).Result));
//continue;
return;
}
else
{
e.SendMessage(Config.SearchNoCommissionTip.Replace("[关键词]", keyword).Replace("[商品标题]", title));//未搜索到提示语
//session.UpdateRecord(_member.id);
//var shared = new Dictionary<string, object>();
//shared["msg_type"] = "查询宝贝";
//shared["msg_username"] = _member.username;
//var sharedEvent = new SharedEvents(shared);
//EventClient.OnEvent(sender, sharedEvent);
return;
}
}
}
catch (Exception ex)
{
if (Regex.IsMatch(ex.Message, @"sub_msg\"":\""无结果"))
{
if (string.IsNullOrWhiteSpace(keyword) && ii == 0 && !string.IsNullOrWhiteSpace(title) && Config.SearchTitleSwitch_NoCommission == SwitchType.)
{
keyword = title;
IsTitle = true;
var searchUrl = api.ComposeTbCms(pid, keyword);//内置的搜索机制
e.SendMessage(Config.SearchTitle_NoCommissionTip.Replace("[商品标题]", title).Replace("[购买地址]", ApiClient.ShortURL(searchUrl).Result));
//continue;
return;
}
else
{
e.SendMessage(Config.SearchNoCommissionTip.Replace("[关键词]", keyword).Replace("[商品标题]", title));
session.UpdateRecord(_member.id);
var shared = new Dictionary<string, object>();
shared["msg_type"] = "查询宝贝";
shared["msg_username"] = _member.username;
var sharedEvent = new SharedEvents(shared);
EventClient.OnEvent(sender, sharedEvent);
return;
}
}
else //if (ex.Message.Contains("该item_id对应宝贝已下架或非淘客宝贝"))
{
e.SendMessage(Config.SearchNoCommissionTip.Replace("[关键词]", keyword).Replace("[商品标题]", title));//未搜索到提示语
throw ex;
}
//else
//{
// throw ex;
//}
}
}
}
}
}
#endregion
}
catch (Exception ex)
{
if (ex.Message.StartsWith("@"))
this.OnLog($"E ({e.RobotInfo.nick}【{e.RobotInfo.name}】){ex.Message.Replace("@", "")}");
else
this.OnLog($"E({e.RobotInfo.nick}【{e.RobotInfo.name}】){ex.Message} - {ex.StackTrace}");
this.OnLog(ApiClient.Setting.SystemConfig.msg_error);
}
}
/// <summary>
/// 订单状态 提示语替换
/// </summary>
/// <param name="order"></param>
/// <param name="objs"></param>
/// <returns></returns>
public static string _GetOrderStateMess(SystemOrderStatus order, SettleType settle, params object[] objs)
{
var mess = string.Empty;
switch (order)
{
case SystemOrderStatus.:
mess = new VariateReplace().CommonReplace(Config.OrderPaymentTip, objs);
break;
case SystemOrderStatus.:
mess = new VariateReplace().CommonReplace(Config.OrderFailureTip, objs);
break;
case SystemOrderStatus.:
mess = new VariateReplace().CommonReplace(Config.OrderRefundTip, objs);
break;
case SystemOrderStatus.:
mess = new VariateReplace().CommonReplace(settle == SettleType. ? Config.OrderSettlementTip : Config.OrderAlreadySettlementTip, objs);
break;
case SystemOrderStatus.:
mess = new VariateReplace().CommonReplace(Config.OrderFreezeTip, objs);
break;
case SystemOrderStatus.退:
mess = new VariateReplace().CommonReplace(Config.OrderFrozen_AllTip, objs);
break;
case SystemOrderStatus.退:
mess = new VariateReplace().CommonReplace(Config.OrderFrozen_PartTip, objs);
break;
}
return mess;
}
/// <summary>
/// 淘礼金方法
/// </summary>
/// <param name="member"></param>
/// <returns></returns>
public string TljMethod(fl_member_info member, ref AlimamaApi api, string item_id, double perface)
{
try
{
if (!Class1.Config.TljOnOff) return string.Empty;
if (perface < 1) return string.Empty;
var session = ApiClient.GetSession();
var tljInfos = session.FindTljInfos();
var tljCreateRecords = session.Find<fl_alimama_tlj_create_record>("select * from fl_alimama_tlj_create_record");
if (tljInfos != null && tljInfos.Count != 0)
{
var cpsnames1 = tljInfos.Select(f => f.username).ToList();
var cpsnames2 = tljCreateRecords.Select(f => f.cpsname).ToList();
for (int i = 0; i < cpsnames1.Count; i++)
{
if (!cpsnames2.Contains(cpsnames1[i]))
{
var tljRecord = new fl_alimama_tlj_create_record() { cpsname = cpsnames1[i], date = DateTime.Now.ToString("yyyyMMdd"), number = 0 };
tljCreateRecords.Add(session.Saveable(tljRecord).ExecuteReturnEntity());
}
}
}
List<fl_alimama_tlj_create_record> tljs = null;
if (tljCreateRecords != null)
tljs = tljCreateRecords.Where(f => (f.date == DateTime.Now.ToString("yyyyMMdd") && f.number < 30) || f.date != DateTime.Now.ToString("yyyyMMdd")).ToList();
switch (Class1.Config.TljModel)
{
case TLJModel.使:
{
var incomeResult = session.FindSingle<fl_statistics_record>(@"select * from fl_statistics_record where uid = @userid", new { userid = member.id });
if (incomeResult == null)
return CreateTljUrl(ref api, tljs, item_id, perface);
}
break;
case TLJModel.使:
{
if (member.bind_order == 0)
return CreateTljUrl(ref api, tljs, item_id, perface);
}
break;
case TLJModel.:
{
var random = new Random(Guid.NewGuid().GetHashCode());
var num = random.Next(1, 5000);
if ((1000 < num && num < 1250) || 10 < num && num < 260)
return CreateTljUrl(ref api, tljs, item_id, perface);
}
break;
}
}
catch (Exception ex)
{
}
return string.Empty;
}
private readonly object lock_tlj = new object();
/// <summary>
/// 创建淘礼金
/// </summary>
/// <param name="api"></param>
/// <param name="item_id"></param>
/// <param name="image"></param>
/// <returns>返回淘礼金连接</returns>
private string CreateTljUrl(ref AlimamaApi api, List<fl_alimama_tlj_create_record> tljs, string item_id, double perface)
{
try
{
lock (lock_tlj)
{
var session = ApiClient.GetSession();
#region
var _tlj = session.FindTljByItemid(item_id);
if (_tlj != null)
{
var cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType. && f.username == _tlj.cpsname);
if (cps != null)
{
AlimamaApi _api = CpsClient.CreateAlimamaRequest(cps);
if (_api != null)
api = _api;
}
if (_tlj.number == 1)
session.Deleteable<fl_alimama_tlj_get_record>(_tlj).ExecuteCommand();
else
{
_tlj.number--;
session.SaveOrUpdate(_tlj);
}
return _tlj.url;
}
#endregion
if (!string.IsNullOrWhiteSpace(Class1.Config.TljItemIds))
{
var itemids = Class1.Config.TljItemIds.Replace("", ",").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
if (string.IsNullOrWhiteSpace(itemids.FirstOrDefault(f => f.Trim() == item_id)))
return string.Empty;
}
if (tljs != null)
{
foreach (var item in tljs)
{
var cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType. && f.username == item.cpsname);
if (cps != null)
{
AlimamaApi _api = CpsClient.CreateAlimamaRequest(cps);
if (_api != null)
{
var tlj = session.FindTljInfos().FirstOrDefault(f => f.username == _api.Member.username);
if (tlj != null)
{
if (string.IsNullOrWhiteSpace(tlj.appkey) || string.IsNullOrWhiteSpace(tlj.appsecret) || string.IsNullOrWhiteSpace(tlj.adzone_pid))
continue;
var reg = Regex.Match(tlj.adzone_pid, @"mm_(?<cpsname>\d+)_(?<pid1>\d+)_(?<pid2>\d+)");
if (!reg.Success)
continue; //throw new Exception($"淘宝推广位格式不正确");
var cpsname = reg.Groups["cpsname"].Value;
//var pid1 = reg.Groups["pid1"].Value;
var pid2 = reg.Groups["pid2"].Value;
var now = DateTime.Now;
var send_end_time = now.AddHours(Class1.Config.TljExpireDate);
var tljResult = _api.SendTaobao("taobao.tbk.dg.vegas.tlj.create", new { adzone_id = pid2, item_id = item_id, security_switch = "true", total_num = Class1.Config.TljCreateNum, name = Class1.Config.TljName, user_total_win_num_limit = Class1.Config.TljGetLimit, per_face = perface, send_start_time = now.ToString("yyyy-MM-dd HH:mm:ss"), send_end_time = send_end_time.ToString("yyyy-MM-dd HH:mm:ss") }, tlj.appkey, tlj.appsecret);
if (tljResult != null && tljResult.ContainsKey("success"))
{
if (tljResult["success"].ToString().ToLower() == "false")
{
if (tljResult.ContainsKey("msg_info"))
{
var msg = tljResult["msg_info"].ToString();
if (msg == "您创建的淘礼金商品数目已达上限")
session.ExcuteSQL("update fl_alimama_tlj_create_record set date = @date ,number = 30 where cpsname = @cpsname", new { date = now.ToString("yyyyMMdd"), cpsname = cpsname });
//throw new Exception("该淘宝账号ID今日创建淘礼金次数已耗尽");
}
//throw new Exception(tljResult.ContainsKey("msg_info") ? tljResult["msg_info"].ToString() : $"生成淘礼金失败,{HttpHelper.ObjectToJson(tljResult)}");
continue;
}
if (tljResult.ContainsKey("model"))
{
var model = tljResult["model"] as Dictionary<string, object>;
if (model.ContainsKey("send_url"))
{
var send_url = model["send_url"].ToString();
#region
session.AddTljCreateNum(cpsname);
#endregion
#region
if (Class1.Config.TljCreateNum > 1)
{
session.SaveOrUpdate(new fl_alimama_tlj_get_record() { adzoneid = pid2, expiredate = send_end_time, itemid = item_id, number = Class1.Config.TljCreateNum - 1, url = send_url, cpsname = cpsname });
}
#endregion
api = _api;
return send_url;
}
}
}
}
}
}
}
}
}
}
catch (Exception ex)
{ }
return string.Empty;
}
}
}