
const{createApp,ref,reactive,computed,onMounted,watch}=Vue;
const api=axios.create({baseURL:'/api',timeout:15000});
api.interceptors.response.use(r=>r.data,e=>({code:500,message:e.message}));
const app=createApp({setup(){
  const cp=ref('home'),pgBack=ref('home'),token=ref(localStorage.getItem('token')||'');
  const kw=ref(''),searchRes=ref([]),showSearch=ref(false);
  const banners=ref([]),cats=ref([]),activeCat=ref(0),homeLoading=ref(true);
  const newProds=ref([]),hotProds=ref([]),bestProds=ref([]);
  const catIdx=ref(0),catProds=ref([]),subCats=ref([]);
  const cart=ref([]),usr=ref({}),prod=ref({}),prodImgs=ref([]),specSel=reactive({});
  const prodQty=ref(1),curPrice=ref(0),curOriginalPrice=ref(0),curStock=ref(0),curSkuId=ref(null);
  const reviews=ref([]);
  const prodLoading=ref(false),orderLoading=ref(false),loginSubmitting=ref(false),regSubmitting=ref(false),addCartLoading=ref(false),buyNowLoading=ref(false);
const showReviewDlg=ref(false),reviewOrder=ref(null),reviewRating=ref(5),reviewContent=ref('');
  const showCheckout=ref(false),checkoutItems=ref([]),checkoutAddr=ref(null),checkoutTotal=ref(0),checkoutRemark=ref(''),checkoutLoading=ref(false),showAddrPicker=ref(false);
  const showOrders=ref(false),orders=ref([]),orderTab=ref(''),showAddress=ref(false),addrList=ref([]);
  const addrForm=reactive({show:false,name:'',phone:'',province:'',city:'',district:'',detail:''});
  async function loadAddr(){if(!token.value)return;try{const r=await api.get('/address/list',{headers:{Authorization:'Bearer '+token.value}});if(r.code===0)addrList.value=r.data||[]}catch(e){vant.showToast('网络错误')}}
  async function saveAddr(){if(!addrForm.name||!addrForm.phone)return vant.showToast('请填写完整信息');try{const r=await api.post('/address/save',{...addrForm},{headers:{Authorization:'Bearer '+token.value}});if(r.code===0){vant.showToast('保存成功');addrForm.show=false;loadAddr()}else vant.showToast(r.message)}catch(e){vant.showToast('网络错误')}}
  async function setDefaultAddr(a){try{const r=await api.post('/address/'+a.id+'/default',{},{headers:{Authorization:'Bearer '+token.value}});if(r.code===0){vant.showToast('已设为默认');loadAddr()}}catch(e){vant.showToast('网络错误')}}
  async function delAddr(id){try{const r=await api.delete('/address/'+id,{headers:{Authorization:'Bearer '+token.value}});if(r.code===0){vant.showToast('已删除');loadAddr()}}catch(e){vant.showToast('网络错误')}}
  const lgPhone=ref('13800001111'),lgPwd=ref('test123456'),rgPhone=ref(''),rgPwd=ref(''),rgName=ref('');
  const lgEmail=ref(''),lgSmsPhone=ref(''),lgSmsCode=ref(''),lgCaptcha=ref(''),captchaId=ref(''),captchaSvg=ref(''),smsCountdown=ref(0);
  const loginType=ref('phone');
  const loginTypes=[{key:'phone',label:'手机登录'},{key:'email',label:'邮箱登录'},{key:'sms',label:'短信登录'}];
  // 底部导航
  const curTab=ref(0);
  const tabbarList=[
    {icon:'🏠',label:'首页',page:'home'},
    {icon:'📂',label:'分类',page:'category'},
    {icon:'🛒',label:'购物车',page:'cart'},
    {icon:'👤',label:'我的',page:'user'}
  ];
  // 活动卡片
  const activities=[
    {title:'新人专享',desc:'首单立减10元'},
    {title:'限时特惠',desc:'全场满199减30'},
    {title:'积分兑换',desc:'好物0元兑'}
  ];
  // 功能入口
  const entries=[
    {icon:'⚡',label:'限时秒杀'},{icon:'🤝',label:'拼团'},{icon:'📄',label:'领券中心'},
    {icon:'⭐',label:'积分商城'},{icon:'✅',label:'每日签到'}
  ];
  // 资产数据
  const assets=computed(()=>[
    {label:'余额',val:'¥'+(+usr.value.balance||0).toFixed(0)},
    {label:'积分',val:'0'},{label:'优惠券',val:'0'},{label:'佣金',val:'¥0'}
  ]);
  const cartSelected=computed(()=>cart.value.filter(c=>c.selected));
  const cartTotal=computed(()=>cartSelected.value.reduce((s,c)=>s+(+c.price)*(c.quantity||1),0));
  const cartAll=ref(true);
  const msgCount=ref(0);

  function stText(s){return {pending_pay:'待付款',pending_ship:'待发货',shipped:'已发货',received:'待评价',completed:'已完成',closed:'已关闭',refunding:'退款中'}[s]||s}
  function calcCart(){cartAll.value=cart.value.every(c=>c.selected)}
  function toggleCartAll(){cart.value.forEach(c=>c.selected=cartAll.value)}
  function switchTab(p,i){curTab.value=i;cp.value=p;if(p==='cart'&&token.value)loadCart();if(p==='user'&&token.value){loadUser();loadOrdCnt()}}

  async function loadBanners(){try{const r=await api.get('/banner/list');if(r.code===0)banners.value=r.data||[]}catch(e){vant.showToast('网络错误')}}
  async function loadCats(){try{const r=await api.get('/category/list');if(r.code===0&&r.data.length){cats.value=r.data;activeCat.value=r.data[0].id}}catch(e){vant.showToast('网络错误')}}
  async function loadHomeData(){homeLoading.value=true;try{const[r1,r2,r3]=await Promise.all([api.get('/product/list',{params:{pageSize:6,sort:'new',order:'desc'}}),api.get('/product/list',{params:{pageSize:6,sort:'sales',order:'desc'}}),api.get('/product/list',{params:{pageSize:6,sort:'price',order:'desc'}})]);if(r1.code===0)newProds.value=r1.data.list||[];if(r2.code===0)hotProds.value=r2.data.list||[];if(r3.code===0)bestProds.value=r3.data.list||[]}catch(e){vant.showToast('网络错误')}homeLoading.value=false}
  async function loadHomeCat(id){try{const r=await api.get('/product/list',{params:{category_id:id,pageSize:6}});if(r.code===0)newProds.value=r.data.list||[]}catch(e){vant.showToast('网络错误')}}
  async function loadCatProds(id){if(!id&&cats.value.length)id=cats.value[0].id;catIdx.value=id;try{const r=await api.get('/product/list',{params:{category_id:id,pageSize:50}});if(r.code===0)catProds.value=r.data.list||[];const rc=await api.get('/category/list');if(rc.code===0)subCats.value=(rc.data||[]).filter(c=>c.pid===id)}catch(e){vant.showToast('网络错误')}}
  async function loadCart(){if(!token.value)return;try{const r=await api.get('/cart/list',{headers:{Authorization:'Bearer '+token.value}});if(r.code===0&&Array.isArray(r.data)){cart.value=r.data.map(c=>({...c,selected:true,image:c.product_image||c.sku_image||'',name:c.product_name||'',price:c.sku_price||c.price||0,sku_info:''}));calcCart()}}catch(e){vant.showToast('网络错误')}}
  async function delCartItem(item){try{const r=await api.delete('/cart/'+item.id,{headers:{Authorization:'Bearer '+token.value}});if(r.code===0){cart.value=cart.value.filter(c=>c.id!==item.id);calcCart()}}catch(e){vant.showToast('网络错误')}}
  async function batchDelCart(){const items=cartSelected.value;if(!items.length)return vant.showToast('请选择商品');try{vant.showDialog({message:'确定删除选中的'+items.length+'件商品？',showCancelButton:true}).then(async()=>{try{await Promise.all(items.map(i=>api.delete('/cart/'+i.id,{headers:{Authorization:'Bearer '+token.value}})));loadCart()}catch(e){vant.showToast('网络错误')}}).catch(()=>{})}catch(e){vant.showToast('网络错误')}}
  async function loadUser(){if(!token.value)return;try{const r=await api.get('/user/info',{headers:{Authorization:'Bearer '+token.value}});if(r.code===0)usr.value=r.data||{}}catch(e){vant.showToast('网络错误')}}
  async function loadOrdCnt(){if(!token.value)return;try{const r=await api.get('/order/list',{params:{pageSize:100},headers:{Authorization:'Bearer '+token.value}});if(r.code===0&&r.data.list)msgCount.value=r.data.list.filter(o=>o.status==='pending_ship'||o.status==='pending_pay').length}catch(e){}}
  async function loadOrds(st=''){if(!token.value)return;orderLoading.value=true;try{const r=await api.get('/order/list',{params:{status:st,pageSize:50},headers:{Authorization:'Bearer '+token.value}});if(r.code===0)orders.value=r.data.list||[]}catch(e){vant.showToast('网络错误')}orderLoading.value=false}
  function selectSpec(name,val){
    specSel[name]=val;
    // 检查所有规格是否已选
    const allSelected = prod.value.specs.every(s => specSel[s.name]);
    if (allSelected && prod.value.skus?.length) {
      const selectedSpecs = prod.value.specs.map(s => specSel[s.name]);
      const match = prod.value.skus.find(sk => {
        const skSpecs = JSON.parse(sk.specs || '[]');
        return skSpecs.length === selectedSpecs.length && skSpecs.every((v,i) => v === selectedSpecs[i]);
      });
      if (match) {
        curSkuId.value = match.id;
        curPrice.value = match.price;
        curOriginalPrice.value = match.original_price || prod.value.original_price;
        curStock.value = match.stock;
        prodQty.value = 1;
        return;
      }
    }
    // 无匹配SKU，显示商品默认价格
    curSkuId.value = null;
    curPrice.value = prod.value.price;
    curOriginalPrice.value = prod.value.original_price;
    curStock.value = prod.value.stock;
    prodQty.value = 1;
  }

  async function loadReviews(productId){
    try{const r=await api.get('/product/reviews/'+productId,{params:{pageSize:5}});
    if(r.code===0) reviews.value=r.data.list||[]}catch(e){vant.showToast('网络错误')}
  }

  async function showProduct(id){
    pgBack.value=cp.value;cp.value='product';prodLoading.value=true;prod.value={};reviews.value=[];
    try{const r=await api.get('/product/detail/'+id);
    if(r.code===0){
      prod.value=r.data;
      prodImgs.value=(r.data.images||[]).filter(Boolean).length?r.data.images:[r.data.image].filter(Boolean);
      Object.keys(specSel).forEach(k => delete specSel[k]);
      curPrice.value=r.data.price;
      curOriginalPrice.value=r.data.original_price;
      curStock.value=r.data.stock;
      curSkuId.value=null;
      prodQty.value=1;
      loadReviews(id);
    }}catch(e){vant.showToast('网络错误')}
    prodLoading.value=false;
  }

  function showReview(order){
    reviewOrder.value=order;
    reviewRating.value=5;
    reviewContent.value='';
    showReviewDlg.value=true;
  }

  async function submitReview(action,done){
    if(action==='confirm'){
      if(!reviewOrder.value) return done();
      const item=reviewOrder.value.items?.[0];
      if(!item) return done();
      try{const r=await api.post('/review/create',{
        product_id:item.product_id,
        order_id:reviewOrder.value.id,
        rating:reviewRating.value,
        content:reviewContent.value
      },{headers:{Authorization:'Bearer '+token.value}});
      if(r.code===0){
        vant.showToast('评价成功');
        reviewOrder.value=null;
        done();
      }else{
        vant.showToast(r.message);
        done(false);
      }}catch(e){vant.showToast('网络错误');done(false)}
    }else{
      done();
    }
  }

  async function goCheckout(){
    if(!cartSelected.value.length) return;
    const items=cartSelected.value.map(c=>({
      product_id:c.product_id,sku_id:c.sku_id||null,quantity:c.quantity||1,
      name:c.name,image:c.image,price:c.price,sku_info:c.sku_info||''
    }));
    checkoutItems.value=items;
    checkoutTotal.value=items.reduce((s,item)=>s+(+item.price)*(item.quantity),0);
    try{if(!addrList.value.length)await loadAddr()}catch(e){}
    const defAddr=addrList.value.find(a=>a.is_default)||addrList.value[0];
    checkoutAddr.value=defAddr||null;
    checkoutRemark.value='';checkoutLoading.value=false;
    showCheckout.value=true;
  }

  function selectCheckoutAddr({selectedOptions}){
    const addr=selectedOptions[0]?.value;
    if(addr){checkoutAddr.value=addr;showAddrPicker.value=false}
  }

  async function submitOrder(){
    if(!checkoutAddr.value) return vant.showToast('请选择收货地址');
    if(checkoutLoading.value) return;
    checkoutLoading.value=true;
    try{
      const items=checkoutItems.value.map(i=>({product_id:i.product_id,sku_id:i.sku_id||null,quantity:i.quantity,cart_id:i.id}));
      const r=await api.post('/order/create',{
        items,address_id:checkoutAddr.value.id,remark:checkoutRemark.value
      },{headers:{Authorization:'Bearer '+token.value}});
      if(r.code===0){
        const payR=await api.post('/order/'+r.data.orderNo+'/pay',{payment_method:'wechat'},{headers:{Authorization:'Bearer '+token.value}});
        if(payR.code===0){
          vant.showToast('支付成功');showCheckout.value=false;loadCart();loadOrdCnt();goOrders('pending_ship');
        }else{
          vant.showToast('下单成功，支付失败');showCheckout.value=false;loadCart();goOrders('pending_pay');
        }
      }else{vant.showToast(r.message||'下单失败')}
    }catch(e){vant.showToast('网络错误')}
    checkoutLoading.value=false;
  }
  async function addCart(){if(!token.value)return vant.showToast('请先登录');if(prod.value.specs?.length&&!curSkuId.value)return vant.showToast('请选择完整规格');if(addCartLoading.value)return;addCartLoading.value=true;try{const r=await api.post('/cart/add',{product_id:prod.value.id,sku_id:curSkuId.value,quantity:prodQty.value},{headers:{Authorization:'Bearer '+token.value}});if(r.code===0){vant.showToast('已加入购物车');loadCart()}else vant.showToast(r.message)}catch(e){vant.showToast('网络错误')}addCartLoading.value=false}
  async function buyNow(){if(!token.value)return vant.showToast('请先登录');if(prod.value.specs?.length&&!curSkuId.value)return vant.showToast('请选择完整规格');if(buyNowLoading.value)return;buyNowLoading.value=true;try{const r=await api.post('/order/create',{items:[{product_id:prod.value.id,sku_id:curSkuId.value,quantity:prodQty.value}]},{headers:{Authorization:'Bearer '+token.value}});if(r.code===0){vant.showToast('下单成功');loadCart();loadOrdCnt();goOrders('pending_pay')}else vant.showToast(r.message)}catch(e){vant.showToast('网络错误')}buyNowLoading.value=false}
  async function dupeGoCheckout(){if(!cartSelected.value.length)return;vant.showToast('结算开发中')}
  async function doCheckout(){if(!cartSelected.value.length)return;try{const items=cartSelected.value.map(c=>({product_id:c.product_id||c.id,sku_id:c.sku_id||null,quantity:c.quantity||1}));const r=await api.post('/order/create',{items},{headers:{Authorization:'Bearer '+token.value}});if(r.code===0){vant.showToast('下单成功');loadCart();loadOrdCnt();goOrders('pending_pay')}else vant.showToast(r.message)}catch(e){vant.showToast('网络错误')}}
  function goOrders(st){orderTab.value=st;loadOrds(st);showOrders.value=true}
  async function loadOrders(){await loadOrds(orderTab.value)}
  // 取消订单
  async function cancelOrder(on){try{const r=await api.post('/order/'+on+'/cancel',{close_reason:'用户取消'},{headers:{Authorization:'Bearer '+token.value}});if(r.code===0){vant.showToast('已取消');loadOrders()}else vant.showToast(r.message)}catch(e){vant.showToast('网络错误')}}
  // 确认收货
  async function confirmOrder(on){try{const r=await api.post('/order/'+on+'/confirm',{},{headers:{Authorization:'Bearer '+token.value}});if(r.code===0){vant.showToast('已确认收货');loadOrders()}else vant.showToast(r.message)}catch(e){vant.showToast('网络错误')}}
  // 去支付
  async function payOrder(on){try{const r=await api.post('/order/'+on+'/pay',{payment_method:'wechat'},{headers:{Authorization:'Bearer '+token.value}});if(r.code===0){vant.showToast('支付成功');loadOrders()}else vant.showToast(r.message)}catch(e){vant.showToast('网络错误')}}
  async function doSearch(){if(!kw.value)return;showSearch.value=false;cp.value='home';try{const r=await api.get('/product/list',{params:{keyword:kw.value}});if(r.code===0){newProds.value=r.data.list||[];homeLoading.value=false}}catch(e){vant.showToast('网络错误')}}
  async function loadCaptcha(){try{const r=await api.get('/captcha/image');if(r.code===0){captchaId.value=r.data.id;captchaSvg.value=r.data.svg}}catch(e){}}
  function sendSmsCode(){if(!lgSmsPhone.value||lgSmsPhone.value.length<11)return vant.showToast('请输入正确手机号');if(smsCountdown.value>0)return;smsCountdown.value=60;const t=setInterval(()=>{smsCountdown.value--;if(smsCountdown.value<=0){clearInterval(t);smsCountdown.value=0}},1000);api.post('/captcha/sms',{phone:lgSmsPhone.value}).then(r=>{if(r.code===0)vant.showToast(r.message.replace(':','验证码: '));else vant.showToast(r.message)}).catch(e=>{vant.showToast('网络错误')})}
  async function handleLogin(){
    if(loginSubmitting.value)return;
    loginSubmitting.value=true;
    try{if(lgCaptcha.value){const vr=await api.post('/captcha/verify',{id:captchaId.value,text:lgCaptcha.value});if(vr.code!==0){vant.showToast(vr.message);loadCaptcha();loginSubmitting.value=false;return}}
    let r;
    if(loginType.value==='phone'){r=await api.post('/user/login',{phone:lgPhone.value,password:lgPwd.value})}
    else if(loginType.value==='email'){r=await api.post('/user/login',{phone:lgEmail.value,password:lgPwd.value})}
    else if(loginType.value==='sms'){r=await api.post('/user/login',{phone:lgSmsPhone.value,password:'sms_'+lgSmsCode.value})}
    if(r&&r.code===0){token.value=r.data.token;localStorage.setItem('token',r.data.token);usr.value=r.data.user||{};cp.value='home';vant.showToast('登录成功');loadCart();loadOrdCnt();loadUser()}else if(r)vant.showToast(r.message)}catch(e){vant.showToast('网络错误')}
    loginSubmitting.value=false;
  }  async function handleRegister(){if(!rgPhone.value||!rgPwd.value)return vant.showToast('请填写完整');if(regSubmitting.value)return;regSubmitting.value=true;try{const r=await api.post('/user/register',{phone:rgPhone.value,password:rgPwd.value,nickname:rgName.value||''});if(r.code===0){vant.showToast('注册成功');cp.value='login'}else vant.showToast(r.message)}catch(e){vant.showToast('网络错误')}regSubmitting.value=false}
  function logout(){token.value='';localStorage.removeItem('token');usr.value={};cp.value='home';vant.showToast('已退出')}

  // ========== 支付相关变量和函数 ==========
  const showPayment=ref(false),payMethod=ref('wechat'),payInfo=ref(null),paying=ref(false);
  async function createPayment(orderNo,method='wechat'){try{const r=await api.post('/payment/create',{order_no:orderNo,method},{headers:{Authorization:'Bearer '+token.value}});if(r.code===0){payInfo.value=r.data;showPayment.value=true}else{vant.showToast(r.message||'创建支付失败');return false}return true}catch(e){vant.showToast('网络错误');return false}}
  function switchPayMethod(m){payMethod.value=m}
  async function doMockPay(){paying.value=true;try{const r=await api.post('/payment/mock-notify',{order_no:payInfo.value?.order_no,trade_no:'MOCK'+Date.now(),payment_method:payMethod.value});if(r.code===0){vant.showToast('支付成功');showPayment.value=false;loadCart();loadOrdCnt();goOrders('pending_ship')}else{vant.showToast(r.message||'支付失败')}}catch(e){vant.showToast('网络错误')}paying.value=false}
  async function doRealPay(){if(!payInfo.value?.pay_url)return vant.showToast('暂无可用的支付链接');paying.value=true;startPaymentPoll();window.open(payInfo.value.pay_url,'_blank');setTimeout(()=>{paying.value=false},3000)}
  function startPaymentPoll(){const t=setInterval(async()=>{try{const r=await api.get('/payment/status/'+payInfo.value?.order_no);if(r.code===0&&r.data?.paid){clearInterval(t);vant.showToast('支付成功');showPayment.value=false;loadCart();loadOrdCnt();goOrders('pending_ship')}}catch(e){}},2000);setTimeout(()=>{clearInterval(t);paying.value=false},120000)}
  function closePayment(){showPayment.value=false;payInfo.value=null}

  onMounted(()=>{try{loadBanners();loadCats();loadHomeData();loadCaptcha();if(token.value){loadUser();loadCart();loadOrdCnt();loadAddr()}}catch(e){vant.showToast('网络错误')}});
  return{cp,pgBack,token,kw,searchRes,showSearch,banners,cats,activeCat,homeLoading,newProds,hotProds,bestProds,catIdx,catProds,subCats,cart,cartAll,cartSelected,cartTotal,usr,prod,prodImgs,specSel,prodQty,curPrice,curOriginalPrice,curStock,curSkuId,reviews,showReviewDlg,reviewOrder,reviewRating,reviewContent,showCheckout,checkoutItems,checkoutAddr,checkoutTotal,checkoutRemark,checkoutLoading,showAddrPicker,showOrders,orders,orderTab,showAddress,addrList,addrForm,loadAddr,saveAddr,setDefaultAddr,delAddr,selectSpec,showReview,submitReview,goCheckout,selectCheckoutAddr,submitOrder,lgPhone,lgPwd,rgPhone,rgPwd,rgName,curTab,tabbarList,activities,entries,assets,msgCount,stText,calcCart,toggleCartAll,switchTab,loadHomeCat,loadCatProds,showProduct,addCart,buyNow,goOrders,loadOrders,doSearch,handleLogin,handleRegister,logout,batchDelCart,loadCaptcha,sendSmsCode,loginType,loginTypes,lgEmail,lgSmsPhone,lgSmsCode,lgCaptcha,captchaId,captchaSvg,smsCountdown,showPayment,payMethod,payInfo,paying,payOrder,createPayment,switchPayMethod,doMockPay,doRealPay,closePayment,startPaymentPoll,prodLoading,orderLoading,loginSubmitting,regSubmitting,addCartLoading,buyNowLoading}
}});
app.use(vant).mount('#app');
