外卖吃多了,你都听到过这中声音,有好奇过是怎么实现的吗?
其实很简单,就是前端不断的请求后台接口,根据情况自动播放前端的mp3之类的早就准备好的音频。
前端核心代码:
<div class="btn-group float-left message">
<a href="javascript:" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown"
style="position: relative">
<span>消息提醒</span>
<div class="text-center ml-2 totalNum"
hidden
style="width: 18px;height: 18px;line-height: 18px;border-radius:999px;display: inline-block;background-color: #ff4544;color:#fff;">
5
</div>
</a>
<div class="dropdown-menu dropdown-menu-right message-list" hidden>
</div>
</div>
<script>
var checkUrl = "<?=Yii::$app->urlManager->createUrl(['mch/get-data/order'])?>";
var checkUrlNew = "<?=Yii::$app->urlManager->createUrl(['mch/get-data/order-pharmacist'])?>";
var pharmacist="<?=$pharmacist?>";
var sound='';
if(pharmacist){
sound = "<?=Yii::$app->request->baseUrl . '/statics/'?>Baidu-TTS.mp3";
}else {
sound = "<?=Yii::$app->request->baseUrl . '/statics/'?>/5611.wav";
}
function playSound(id) {
var borswer = window.navigator.userAgent.toLowerCase();
if (borswer.indexOf("ie") >= 0) {
//IE内核浏览器
var strEmbed = '<embed name="embedPlay" src="' + sound + '" autostart="true" hidden="true" loop="false"></embed>';
if ($("body").find("embed").length <= 0)
$("body").append(strEmbed);
var embed = document.embedPlay;
//浏览器不支持 audion,则使用 embed 播放
embed.volume = 100;
} else {
//非IE内核浏览器
var strAudio = "<audio id='audioPlay' src='" + sound + "' hidden='true'>";
if ($("body").find("audio").length <= 0)
$("body").append(strAudio);
var audio = document.getElementById("audioPlay");
//浏览器支持 audion
audio.play();
}
}
function is_index(indexOf, list) {
for (var i = 0; i < list.length; i++) {
if (indexOf == list[i]) {
return true;
}
}
return false;
}
// 订单消息
function checkmessage() {
$.ajax({
url: checkUrl,
type: 'get',
dataType: 'json',
success: function (res) {
var sound_list = JSON.parse(localStorage.getItem('sound_list'));
if (!sound_list) {
sound_list = [];
}
if (res.code == 0) {
var count = res.data.length;
if (count == 0) {
return;
}
$('.message-list').empty();
for (var i = 0; i < count; i++) {
$('.message-list').prop('hidden', false);
$('.totalNum').prop('hidden', false).html(count);
var type = res.data[i].type;
var order_type = res.data[i].order_type;
if (order_type == 4) {
var html = "<a target='_blank' class='dropdown-item' data-index='" + res.data[i].id + "' href='" + res.data[i].url + "'>" + res.data[i].name + "申请商品上架</a>";
} else {
if (type == 0) {
var html = "<a target='_blank' class='dropdown-item' data-index='" + res.data[i].id + "' href='" + res.data[i].url + "'>" + res.data[i].name + "下了一个订单</a>";
} else {
var html = "<a target='_blank' class='dropdown-item' data-index='" + res.data[i].id + "' href='" + res.data[i].url + "'>" + res.data[i].name + "一个售后订单</a>";
}
}
$('.message-list').append(html);
if (res.data[i].is_sound == 0 && !is_index(res.data[i].id, sound_list)) {
sound_list.push(res.data[i].id);
playSound(res.data[i].id);
}
}
localStorage.setItem('sound_list', JSON.stringify(sound_list));
$('.message-list').append("<a class='dropdown-item' style='text-align:center' href='<?=Yii::$app->urlManager->createUrl(['mch/store/order-message', 'status' => 1])?>'>全部消息</a>");
}
}
});
}
//药师订单消息
function checkmessage_ph() {
$.ajax({
url:checkUrlNew,
type: 'get',
dataType: 'json',
success: function (res) {
var sound_list_new = JSON.parse(localStorage.getItem('sound_list_new'));
if (!sound_list_new) {
sound_list_new = [];
}
if (res.code == 0) {
var count = res.data.length;
if (count == 0) {
return;
}
$('.message-list').empty();
console.log(res.data);
for (var i = 0; i < count; i++) {
$('.message-list').prop('hidden', false);
$('.totalNum').prop('hidden', false).html(count);
var type = res.data[i].type;
var order_type = res.data[i].order_type;
var rx_exist=res.data[i].rx_exist;
if (order_type == 4) {
var html = "<a target='_blank' class='dropdown-item' data-index='" + res.data[i].id + "' href='" + res.data[i].url + "'>" + res.data[i].name + "申请商品上架</a>";
} else {
if (type == 0) {
if(rx_exist==1){
var html = "<a target='_blank' class='dropdown-item' data-index='" + res.data[i].id + "' href='" + res.data[i].url + "'>" + res.data[i].name + "下了一个处方药订单</a>";
}
if(rx_exist==0){
var html = "<a target='_blank' class='dropdown-item' data-index='" + res.data[i].id + "' href='" + res.data[i].url + "'>" + res.data[i].name + "下了一个订单</a>";
}
} else {
var html = "<a target='_blank' class='dropdown-item' data-index='" + res.data[i].id + "' href='" + res.data[i].url + "'>" + res.data[i].name + "一个售后订单</a>";
}
}
$('.message-list').append(html);
if (!is_index(res.data[i].id, sound_list_new)) {
sound_list_new.push(res.data[i].id);
if(res.data[i].rx_exist==1){
playSound(res.data[i].id);
}
}
}
localStorage.setItem('sound_list_new', JSON.stringify(sound_list_new));
$('.message-list').append("<a class='dropdown-item' style='text-align:center' href='<?=Yii::$app->urlManager->createUrl(['mch/store/order-message', 'status' => 1])?>'>全部消息</a>");
}
}
});
}
$(document).ready(function () {
$('.message').hover(function () {
$('.message-list').show();
}, function () {
$('.message-list').hide();
});
$('.message-list').on('click', 'a', function () {
var num = $('.totalNum');
num.text(num.text() - 1);
if (num.text() == 0) {
num.prop('hidden', true);
$('.message-list').prop('hidden', true)
}
$.ajax({
url: '<?=Yii::$app->urlManager->createUrl(['mch/get-data/message-del'])?>',
type: 'get',
dataType: 'json',
data: {
'id': $(this).data('index')
},
success: function (res) {
if (res.code == 0) {
window.location.href = $(this).data('url');
}
}
});
$(this).remove();
});
setInterval(function () {
<?php if($pharmacist){?>
checkmessage_ph();
<?php }else{?>
checkmessage();
<?php }?>
}, 30000);
});
</script>
public function search()
{
if (!$this->validate()) {
return $this->errorResponse;
}
$query = OrderMessage::find()->alias('om')->where([
'om.store_id' => $this->store_id,
'om.shop_id' => 0,
'om.is_delete' => 0,
'om.order_type' => [0, 1, 2, 3, 4]
]);
if ($this->is_read) {
$query->andWhere(['or',['om.is_read' => 0],['om.is_sound'=>0]]);
}
$count = $query->count();
$pagination = new Pagination(['totalCount' => $count, 'pageSize' => $this->limit]);
$list = $query->orderBy(['om.addtime' => SORT_DESC])
->limit($pagination->limit)
->offset($pagination->offset)
->asArray()
->all();
$urlManager = \Yii::$app->urlManager;
// 此处考虑在 cache 或 setting 内做缓存,存储 order_message 表的更新时间,以及查询结果
// 插入 order_message 时,在 beforeInsert 内清空缓存
// -- wi1dcard
foreach ($list as $index => &$value) {
switch ($value['order_type']) {
case 3:
$yy_order = YyOrder::findOne(['id' => $value['order_id'], 'store_id' => $this->store_id]);
if ($value['type'] == 0) {
$value['url'] = $urlManager->createUrl(['mch/book/order/index', 'status' => 1]);
} else {
$value['url'] = $urlManager->createUrl(['mch/book/order/index', 'status' => 3]);
}
$user = User::findOne(['id' => $yy_order->user_id]);
$order['order_no'] = $yy_order->order_no;
$order['name'] = $user->nickname;
break;
case 4:
$mch_goods = Goods::findOne(['id' => $value['order_id']]);
$mch = Mch::findOne(['id' => $mch_goods->mch_id]);
$value['url'] = $urlManager->createUrl(['mch/mch/goods/goods', 'keyword' => $mch_goods->name]);
$order['order_no'] = $mch_goods->name;
$order['name'] = $mch->name;
break;
default:
if ($value['type'] == 0) {
$value['url'] = $urlManager->createUrl(['mch/order/index', 'status' => 1]);
} else {
$value['url'] = $urlManager->createUrl(['mch/order/refund']);
}
switch ($value['order_type']) {
case 0:
$class = "app\models\Order";
break;
case 1:
$class = "app\models\MsOrder";
$value['url'] = $urlManager->createUrl(['mch/miaosha/order/index', 'status' => 1]);
break;
case 2:
$class = "app\models\PtOrder";
$value['url'] = $urlManager->createUrl(['mch/group/order/index', 'status' => 1]);
break;
default:
break;
}
$order = $class ? $class::findOne(['id' => $value['order_id'], 'store_id' => $this->store_id]) : [];
//砍价订单
if($value['order_type']==0 && $order->type==2){
$value['url'] = $urlManager->createUrl(['mch/bargain/order/index']);
$value['is_bargain'] = 1;
}
}
$value['order_no'] = $order['order_no'];
$value['name'] = $order['name'];
$value['platform'] = User::find()->where(['id' => $order['user_id']])->select('platform')->scalar();
$time = time() - $value['addtime'];
if ($time < 60) {
$value['time'] = $time . '秒前';
} elseif ($time < 3600) {
$value['time'] = ceil($time / 60) . '分钟前';
} elseif ($time < 86400) {
$value['time'] = ceil($time / 3600) . '小时前';
} else {
$value['time'] = ceil($time / 86400) . '天前';
}
}
return [
'list' => $list,
'pagination' => $pagination
];
}