/** * V.AI STUDIO — Order Button v4 * * v4: Expose showOrderPicker ra window._showOrderPicker * để cards SP trong chat AI cũng có nút "+ Đơn" hoạt động */ (function(){ 'use strict'; var STORE_KEY='vai_orders'; function waitReady(cb){ var t=setInterval(function(){ if(typeof D!=='undefined'&&D.length>100){clearInterval(t);cb();} },2000); setTimeout(function(){clearInterval(t);cb();},20000); } function fmt(n){if(!n||isNaN(n))return'0đ';return Number(n).toLocaleString('vi-VN')+'đ';} function getOrdersSafe(){ if(window.VAI_ORDERS&&typeof window.VAI_ORDERS.getAll==='function'){ var orders=window.VAI_ORDERS.getAll(); if(orders&&orders.length)return orders; } try{ var raw=localStorage.getItem(STORE_KEY); if(raw){var parsed=JSON.parse(raw);if(Array.isArray(parsed)&&parsed.length)return parsed;} }catch(e){} return []; } function addOrderSafe(order){ if(window.VAI_ORDERS&&typeof window.VAI_ORDERS.add==='function'){ window.VAI_ORDERS.add(order); }else{ try{ var orders=getOrdersSafe(); var idx=orders.findIndex(function(o){return o.code===order.code;}); if(idx>=0)orders[idx]=order;else orders.unshift(order); localStorage.setItem(STORE_KEY,JSON.stringify(orders)); }catch(e){} } } function showOrderPicker(product,onDone){ var old=document.getElementById('vai-order-picker');if(old)old.remove(); var orders=getOrdersSafe(); var overlay=document.createElement('div'); overlay.id='vai-order-picker'; overlay.style.cssText='position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;backdrop-filter:blur(2px)'; overlay.addEventListener('click',function(e){if(e.target===overlay)overlay.remove();}); var name=product.name||product.n||''; var sku=product.sku||product.model||product.mod||''; var price=product.priceNum||product.pn||0; if(!price)price=parseInt((product.price||product.p||'').toString().replace(/[^\d]/g,''))||0; var h='
'; h+='
🛒 Thêm vào đơn
'+name.substring(0,45)+'
'; if(sku)h+='
Mã: '+sku+' • Giá: '+fmt(price)+'
'; h+='
'; if(!orders.length){ h+='
📋
Chưa có đơn hàng nào
Vui lòng tạo báo giá trước, sau đó lưu đơn.
'; }else{ h+='
Chọn đơn hàng ('+orders.length+' đơn):
'; orders.forEach(function(o,idx){ var isC=o.status==='confirmed';var itemCount=(o.items&&o.items.length)||0; h+='
'; h+='
'+o.code+''+itemCount+' SP
'; h+='
'+(o.customer||'Chưa có KH')+(o.grandTotal?' • '+fmt(o.grandTotal)+'':'')+'
'; }); } h+='
'; overlay.innerHTML=h;document.body.appendChild(overlay); document.getElementById('vai-op-close').onclick=function(){overlay.remove();}; overlay.querySelectorAll('.vai-op-item').forEach(function(item){ item.addEventListener('click',function(){ var idx=parseInt(this.getAttribute('data-idx')); var order=JSON.parse(JSON.stringify(orders[idx])); if(!order)return;order.items=order.items||[]; if(sku){for(var i=0;i30){clearInterval(t);return;} if(typeof D==='undefined'||!D.length)return; if(document.getElementById('vai-page-add-btn'))return; var product=null;for(var i=0;i