<template>
  <view class="container">
    <view class="white_container">
      <image class="pic" :src="picUrl + info.album_images" />
      <!-- <swiper class="swiper" autoplay>
        <swiper-item v-for="(item, pageIndex) in info.bigImg" :key="pageIndex">
          <image class="pic" :src="picUrl + item" />
        </swiper-item>
      </swiper> -->

      <view class="main">
        <view class="title">{{ info.merchant_name }}</view>

        <!-- <u-icon name="star-fill" color="#FFB84D" /> -->
        <view class="startList">
          <image v-for="index in 5" :key="index"
            :src="index < info.rating ? 'https://static.hshuishang.com/property-img-file/local_start1.png' : 'https://static.hshuishang.com/property-img-file/local_start2.png'"
            mode="aspectFill"></image>
        </view>

        <!-- 优惠劵区域 -->
        <view class="coupon_container" v-if="coupons.length > 0">
          <view class="coupon" :class="{ 'coupon_used1': coupon.is_received }" v-for="(coupon, index) in coupons"
            :key="index">
            <view class="coupon_amount">¥{{ coupon.money }}</view>
            <view class="coupon_condition" v-if="coupon.full_amount != 0">满{{ coupon.full_amount }}元可用</view>
            <view class="coupon_condition" v-else>无门槛</view>
            <view class="coupon_status" @click="handleCouponClick(coupon)">{{ coupon.is_received ? '已领' : '领取' }}</view>
          </view>
          <view class="more_coupon" @click="showCouponDetail">
            <view class="more_text">更多优惠</view>
            <u-icon name="arrow-right" color="#FF370B" size="28" />
          </view>
        </view>

        <u-line margin="46rpx 0 30rpx 0" />
        <view class="table">
          <view class="label">联系电话</view>
          <view class="desc">{{ info.phone }}</view>
        </view>
        <view class="table">
          <view class="label">营业时间</view>
          <view class="desc">{{ info.business_hours }}</view>
        </view>
        <view class="table">
          <view class="label">营业地址</view>
          <view class="desc" v-if="info.ad">{{ info.ad.ad_name ? info.ad.ad_name.replace(/,/g, "") : "" }}{{
            info.address }}</view>
        </view>
        <view class="table mb32">
          <view class="label">特色服务</view>
          <view class="desc">{{ info.features }}</view>
        </view>

        <view class="particulars" @click="detail_msg">
          <view>查看详情</view>
          <u-icon name="arrow-right" size="30" />
        </view>

      </view>
    </view>

    <!-- 店铺活动商品 -->
    <view class="white_container shop-activity" v-if="shopActivityList.length > 0">
      <view class="shop-activity-title">店铺活动</view>
      <view class="shop-activity-list">
        <block v-for="(item, index) in shopActivityList" :key="index">
          <view class="sa-goods" v-for="(sku, sIdx) in item.group_buy_goods_list" :key="sIdx"
            @click="toShopActivityDetail(sku)">
            <image class="sa-pic" :src="sku.commodity_pic || item.commodity_pic" mode="aspectFill" />
            <view class="sa-info">
              <view class="sa-name">{{ sku.goods_name || item.commodity_name }}</view>
              <view class="sa-price-row">
                <view class="sa-price">￥{{ sku.group_buy_price }}<text class="sa-unit" v-if="sku.goods_unit">/{{ sku.goods_unit }}</text></view>
                <view class="sa-origin" v-if="sku.sales_price">单买价 ￥{{ sku.sales_price }}</view>
              </view>
            </view>
          </view>
        </block>
      </view>
    </view>

    <view class="white_container detail" v-for="(item, index) in commentList" :key="index">
      <view class="Msg">
        <view class="Msg_Tit">
          <view class="Msg_Tit_left">
            <image src="https://static.hshuishang.com/property-img-file/user_ava.png" v-if="!item.user.avatar"
              mode="aspectFill"></image>
            <image :src="picUrl + item.user.avatar" v-if="item.user.avatar" mode="aspectFill"></image>
            {{ item.user.nick_name }}
          </view>
          <view class="Msg_Tit_right">
            <image v-for="indez in 5" :key="indez"
              :src="indez < item.satisfaction ? 'https://static.hshuishang.com/property-img-file/local_start1.png' : 'https://static.hshuishang.com/property-img-file/local_start2.png'"
              mode="aspectFill"></image>
          </view>
        </view>

        <view class="Msg_con">
          {{ item.comment }}
          <view class="Msg_con_img" v-if="item.image_url">
            <image v-for="(img, index) in item.image_url.split(',')" :key="index" :src="picUrl + img" mode="aspectFill"
              @click="previewImage(item.image_url.split(','), index)">
            </image>
            <video class="Msg_con_video" v-if="item.video_url" :src="picUrl + item.video_url" controls></video>
          </view>
        </view>

        <view class="Msg_iconList">
          <view class="Msg_iconList_left">
            <view class="Msg_iconList_leftIcon">
              <image src="https://static.hshuishang.com/property-img-file/local_review.png" mode="widthFix"></image>
              {{ item.merchant_evaluation_reply_list ? item.merchant_evaluation_reply_list.length : 0 }}
            </view>

            <view class="Msg_iconList_leftIcon">
              <image v-if="item.is_like == 2" src="https://static.hshuishang.com/property-img-file/com_likeIcon.png"
                mode="widthFix" @click="like(item)"></image>
              <image v-if="item.is_like == 1" src="https://static.hshuishang.com/property-img-file/com_likeIcon2.png"
                mode="widthFix" @click="unlike(item)"></image>
              {{ item.merchant_evaluation_like_list ? item.merchant_evaluation_like_list.length : 0 }}
            </view>
          </view>
          <view class="Msg_iconList_right" @click="commentDesc(item)">
            详情 <view><u-icon name="arrow-right" colof="#999999"></u-icon></view>
          </view>
        </view>
      </view>
    </view>
    <view class="bottom">
      <view class="left">
        <view class="left_label" @click="handleOptionClick">
          <image src="https://static.hshuishang.com/Index_add.png" mode="" />
          <view>导航</view>
        </view>
        <view class="left_label" @click="handlePhoneClick" v-if="info.phone">
          <image src="https://static.hshuishang.com/property-img-file/localLife_detail_Frame.png" mode="" />
          <view>电话</view>
        </view>
        <view v-if="isShow" class="left_label" @click="handleDiscussClick">
          <image src="https://static.hshuishang.com/property-img-file/localLife_shopList_Group_1334.png" mode="" />
          <view>点评</view>
        </view>
        <view class="left_label" @click="handleKfClick">
          <image src="https://static.hshuishang.com/kefu0.png" mode="" />
          <view>客服</view>
        </view>
      </view>
      <button v-if="isShow && !isDisabled" class="btn" @click="handleQuickPayClick">快捷买单</button>
      <button v-if="isShow && isDisabled" class="btn_disabled" @click="handleQuickPayClick">快捷买单</button>
    </view>

    <!-- 优惠详情弹窗 -->
    <u-popup :show="showCouponPopup" width="650rpx" height="800rpx" round="20rpx">
      <view class="coupon_popup">
        <view class="popup_header">
          <view class="popup_title">优惠详情</view>
          <view class="popup_close" @click="closeCouponPopup">取消</view>
        </view>
        <view class="popup_content">
          <view class="coupon_item" v-for="(item, index) in couponDetails" :key="index">
            <view class="coupon_item_left">
              <view class="coupon_item_amount">¥{{ item.money }}</view>
              <view class="coupon_item_condition" v-if="item.full_amount != 0">满{{ item.full_amount }}元可用</view>
              <view class="coupon_item_condition" v-else>无门槛</view>
            </view>
            <view class="coupon_item_center">
              <view class="coupon_item_name">{{ item.red_package_name }}</view>
              <view class="coupon_item_expire">{{ item.end_time }}到期</view>
            </view>
            <view class="coupon_item_right">
              <view class="coupon_item_button" @click="handleCouponClick(item)">{{ item.is_received ? '已领' : '领取' }}
              </view>
            </view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import {
  request,
  picUrl,
  NavgateTo,
} from "../../../utils";

import { apiArr } from "../../../api/v2local";
import { apiArr as apiArr2 } from "../../../api/user";

export default {
  data() {
    return {
      picUrl,
      info: {},
      page_num: 1,
      page_size: 10,
      commentList: [],
      flag: false,
      isShow: false,
      isDisabled: false,
      coupons: [],
      couponDetails: [],
      showCouponPopup: false,
      shopActivityList: [] // 店铺活动商品（团购 activity_type=2）
    };
  },
  onLoad(options) {
	  let id;
	  if (options.scene) {
			  const scene = decodeURIComponent(options.scene);
			  function getQueryParam(str, name) {
			        const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
			        const match = str.match(reg);
			        return match ? decodeURIComponent(match[2]) : null;
			      }
			      const idStr = getQueryParam(scene, 'id');  // 得到 "22"
			      if (idStr) {
			        id = Number(idStr);  // 得到 22
			      }
	  }else{ 
			  id = Number(uni.getStorageSync("merchantInfo").id)
	  }
	  console.log('scene:',options.scene,id)
	const params = {
		id: id
	}
    request(apiArr.getMerchantInfo, "POST", params).then(res => {
      this.info = res
      uni.setStorageSync('merchantInfo', res)

      // 确保onLoad执行完后再执行这两个方法
      this.page_num = 1
      this.flag = false
      this.commentList = []
      this.getCommentList()
      this.getShopActivity()
    });
  },
  onShow() {
    if (this.info.id) {
      this.getCommentList()
    }
    this.getMerchantInfo()
    this.getCouponList()
  },
  onReachBottom() {
    if (this.flag) {
      this.getMechantList();
    }
  },

  methods: {
    // 店铺活动商品（团购 activity_type=2），小区来源与团购一致（绑定房产小区）
    getShopActivity() {
      const userId = uni.getStorageSync('userId')
      if (!userId) return
      const params = {
        user_id: userId,
        merchant_id: this.info.id,
        community_id: uni.getStorageSync('changeCommData') ? uni.getStorageSync('changeCommData').id : ''
      }
      request(apiArr.getShopActivityList, "POST", params, {}, false).then(res => {
        const list = (res.list || []).map(item => {
          const group_buy_goods_list = (item.group_buy_goods_list || []).map(sku => ({
            ...sku,
            commodity_pic: picUrl + sku.commodity_pic,
            quantity: 0
          }))
          return {
            ...item,
            commodity_pic: picUrl + item.commodity_pic,
            group_buy_goods_list
          }
        })
        this.shopActivityList = list
      }).catch(() => {
        this.shopActivityList = []
      })
    },
    // 点击店铺活动商品 -> 复用团购详情页
    toShopActivityDetail(itemObj) {
      let targetItem = itemObj
      if (!targetItem.group_buy_activity_info && targetItem.group_buy_goods_list && targetItem.group_buy_goods_list.length > 0) {
        targetItem = targetItem.group_buy_goods_list[0]
      }
      if (!targetItem.group_buy_activity_info) return
      const item = {
        ...targetItem,
        groupById: targetItem.group_buy_activity_info.id
      }
      NavgateTo(`/packages/shop/groupPurchaseDetail/index?item=${JSON.stringify(item)}`)
    },
    getCouponList() {
      const params = {
        mch_id: uni.getStorageSync("merchantInfo").id,
      }
      request(apiArr2.redPackageCenter, "POST", params, {}, false).then(res => {
        this.coupons = res.rows
        this.couponDetails = res.rows
      })
    },
    // 领取红包
    handleCouponClick(item) {
      if (item.is_received) {
        return
      }
      const params = {
        user_id: uni.getStorageSync('userId'),
        red_package_config_id: item.id,
        mch_id: item.belong_role == 1 ? item.merchant_id : ''
      }
      request(apiArr2.redPackageClaim, 'POST', params).then(res => {
        this.getCouponList()
      })
    },
    handleQuickPayClick() {
      if (this.isDisabled) {
        uni.showToast({
          title: '支付未开通，升级 VIP 或联系工作人员开通',
          icon: 'none',
          duration: 2000
        });

      } else {
        NavgateTo('../pay/index');
      }
    },
    //获取评论列表
    getCommentList() {
      if (uni.getStorageSync('userId')) {
        request(apiArr.getMerchantComment, "POST", {
          page_num: this.page_num,
          page_size: this.page_size,
          merchant_id: this.info.id,
        }).then(res => {
          this.page_num++
          if (res.rows.length == this.page_size) {
            this.flag = true;
          } else {
            this.flag = false;
          }
          const list = res.rows.filter((item) => {
            return item.status == 2;
          });

          list.forEach(item => {
            if (item.merchant_evaluation_reply_list) {
              item.merchant_evaluation_reply_list = item.merchant_evaluation_reply_list.filter((item) => {
                return item.status == 2;
              })
            }
          })

          this.commentList = this.commentList.concat(list);
        })
      }
    },

    getMerchantInfo() {
      request(apiArr.getMerchantInfo, "POST", {
        id: uni.getStorageSync("merchantInfo").id,
      }).then(res => {
        this.isShow = res.quick_purchase_enabled == 1
        this.isDisabled = res.level == 1
      })
    },

    //店铺详情
    detail_msg() {
      NavgateTo('../detail_msg/index')
    },
    // 导航
    handleOptionClick() {
      const { info } = this;
      let openParmas = {
        latitude: Number(info.latitude),
        longitude: Number(info.longitude),
        name: info.comAddress,
        address: info.comAddress,
      };
      uni.openLocation(openParmas);
    },

    //拨打电话触发事件
    handlePhoneClick() {
      uni.makePhoneCall({
        phoneNumber: this.info.phone || '',
        fail(err) {
          console.log('拨打电话失败', err)
        }
      })
    },

    // 点评
    handleDiscussClick() {
      NavgateTo('../comment/index');
    },

    // 客服
    handleKfClick() {
      NavgateTo('/packages/customerService/changeService/index');
    },

    like(e) {
      request(apiArr.merChantCommentLike, "POST", {
        evaluation_id: e.id,
      }).then(res => {
        console.log(e);
        if (e.merchant_evaluation_like_list) {
          e.merchant_evaluation_like_list.push({})
        } else {
          e.merchant_evaluation_like_list = []
          e.merchant_evaluation_like_list.push({})
        }
        e.is_like = 1
        uni.showToast({
          icon: "none",
          title: '点赞成功',
          duration: 2000
        });
      })
    },
    unlike(e) {
      request(apiArr.merChantCommentUnlike, "POST", {
        evaluation_id: e.id,
      }).then(res => {
        e.is_like = 2
        e.merchant_evaluation_like_list.pop()
        uni.showToast({
          title: '取消成功',
          icon: "none",
          duration: 2000
        });
      })
    },

    commentDesc(e) {
      NavgateTo(`../UserComment/index?id=${e.id}`)
    },

    // 预览图片
    previewImage(imageList, currentIndex) {
      // 将相对路径转换为完整URL
      const urls = imageList.map(img => this.picUrl + img);
      uni.previewImage({
        urls: urls,
        current: urls[currentIndex],
        success: function (res) {
          console.log('预览成功', res);
        },
        fail: function (err) {
          console.log('预览失败', err);
        }
      });
    },

    // 显示优惠详情弹窗
    showCouponDetail() {
      this.showCouponPopup = true;
    },

    // 关闭优惠详情弹窗
    closeCouponPopup() {
      this.showCouponPopup = false;
    },

    // 领取优惠劵
    receiveCoupon() {
      uni.showToast({
        title: '领取成功',
        icon: 'success'
      });
    },

  },
};
</script>

<style>
@import url("./index.css");
</style>
