<template>
  <view class="container">
    <Header :title="shopDetail.shopName"></Header>

    <view class="content">
      <view class="shop">
        <image :src="fileDomain + shopDetail.shopLogo" class="logo" mode="aspectFill"></image>
        <view class="info">
          <view class="top">
            <view class="left">
              <text class="title">{{ shopDetail.shopName }}</text>
              <view class="ratebox">
                <wd-rate
                  custom-class="icon-statr"
                  v-model="shopDetail.grade"
                  size="26rpx"
                  space="2rpx"
                  readonly
                  active-color="#f12929"
                />
                <text class="rate">{{ shopDetail.grade }}</text>
              </view>
              <view class="ratebox">
                <text>营业时间：</text>
                <text class="time">
                  {{ shopDetail.transactionStart }}-{{ shopDetail.transactionEnd }}
                </text>
              </view>
            </view>

            <view class="btn" @tap="toShop">
              <image src="@/static/ticket/shopmail.png"></image>
              <text>进店</text>
            </view>
          </view>
          <view class="bottom">
            <image class="address" src="@/static/ticket/address.png"></image>
            <view class="infobox">
              <text class="addr">{{ shopDetail.shopAddress }}</text>
              <text>距您{{ shopDetail.distance }}</text>
            </view>
            <view class="iconbox" @tap="openMapApp()">
              <image class="img" src="@/static/ticket/map.png"></image>
              <text>导航到店</text>
            </view>
            <view class="iconbox" @tap="callShopPhone(shopDetail.phone)">
              <image class="img" src="@/static/ticket/phone.png"></image>
              <text>电话</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 优惠券列表 -->
      <view class="ticket-list" v-if="couponData.length">
        <view class="ticket-item" v-for="(item, index) in couponData" :key="index">
          <view class="ticket-box">
            <view class="normal ticket-left">
              <view class="ticket-box">
                <view class="ticket-price">
                  <text class="price">￥</text>
                  <text class="num">{{ item.discountValue }}</text>
                </view>
                <view class="ticket-desc">
                  <text class="desc">满{{ item.thresholdAmount }}元可用</text>
                  <text class="desc">数量：{{ item.maxNum }}</text>
                </view>
              </view>
            </view>

            <view class="ticket-right">
              <view class="head">
                <text class="title">{{ item.activityName }}</text>
                <view class="headbox">
                  <text class="time">
                    使用时间：{{ item.startTime.slice(0, 10) }}-{{ item.endTime.slice(0, 10) }}
                  </text>
                  <view class="btn" v-if="item.numState === 0" @click="getCoupon(item)">
                    立即领取
                  </view>
                  <view class="btn" v-else @tap="toShop">使用</view>
                </view>
              </view>
              <view class="foot">
                <view class="line"></view>
                <view class="footbox" @click="handleChangeDetail(index)">
                  <text class="desc">详细信息</text>
                  <wd-icon
                    :name="item.showDetail ? 'chevron-down' : 'chevron-right'"
                    size="15px"
                    color="#9d9d9d"
                  ></wd-icon>
                </view>
              </view>
            </view>
          </view>

          <view class="detail" v-if="item.showDetail">
            <view class="line"></view>
            <view class="detail-box">
              <view class="rowbox">
                <text>使用时间</text>
                <text class="desc">
                  {{ item.startTime.slice(0, 10) }}-{{ item.endTime.slice(0, 10) }}
                </text>
              </view>
              <view class="rowbox">
                <text>使用条件</text>
                <text class="desc">满{{ item.thresholdAmount }}元可用</text>
              </view>
              <view class="rowbox">
                <text>使用说明</text>
                <text class="desc">
                  {{ item.activityNotes }}
                </text>
              </view>
            </view>
          </view>
        </view>
        <view class="coupon-tips" v-if="couponInfo">
          <view class="tips">使用须知</view>
          <view class="desc">{{ couponInfo.contentRdd }}</view>
        </view>
      </view>
      <wd-status-tip image="content" tip="暂无优惠券" v-else />
    </view>

    <view class="footer">
      <view class="btn" @tap="getCouponAll">一键领取</view>
    </view>
  </view>
</template>

<script setup>
import { shopCouponList, receiveCoupon, couponUsageNotice } from '@/api/ticket';
import { getShopDetail } from '@/api/order';
import { getDistance } from '@/utils/common';
import Header from '@/pages/order/components/Header/index.vue';

const fileDomain = import.meta.env.VITE_APP_IMG_URL;

onShow(() => {
  // 获取位置并计算距离
  calculateDistance();
});

const shopId = ref();
onLoad((options) => {
  shopId.value = options.shopId;
  getShopMailDetail();
  getList();
  getCouponInfo();
});

/**
 * 获取优惠券列表
 */
const couponData = ref([]);
const getList = async () => {
  const res = await shopCouponList(shopId.value);
  if (res.code === 0) {
    res.data.forEach((item) => {
      item.showDetail = false;
    });
    couponData.value = res.data;
  }
};

/**
 * 修改优惠券详情显示状态
 */
const handleChangeDetail = (idx) => {
  couponData.value[idx].showDetail = !couponData.value[idx].showDetail;
};

/**
 * 领取优惠券
 * @param {*} item
 */
const getCoupon = async (item) => {
  const res = await receiveCoupon([item.couponYzfId]);
  item.numState = 1;
  xma.showToast({
    title: '领取成功',
    icon: 'success',
    duration: 2000,
  });
};

/**
 * 一键领取优惠券
 */
const getCouponAll = async () => {
  const ids = [];
  couponData.value.forEach((item) => {
    if (item.numState === 0) {
      ids.push(item.couponYzfId);
    }
  });
  if (ids.length === 0) {
    xma.showToast({
      title: '暂无可领取优惠券',
      icon: 'none',
      duration: 2000,
    });
    return;
  }
  const res = await receiveCoupon(ids);
  couponData.value.forEach((item) => {
    item.numState = 1;
  });
  xma.showToast({
    title: '领取成功',
    icon: 'success',
    duration: 2000,
  });
};

/**
 * 获取商铺信息
 */
const shopDetail = ref({
  shopName: '店铺详情',
});
const getShopMailDetail = async () => {
  const res = await getShopDetail({ shopId: shopId.value });
  if (res.code === 0) {
    shopDetail.value = res.data.shop;
    // 获取位置并计算距离
    calculateDistance();
  }
};

/**
 * 获取优惠券信息
 */
const couponInfo = ref();
const getCouponInfo = async () => {
  const res = await couponUsageNotice();
  if (res.code === 0) {
    couponInfo.value = JSON.parse(res.data.paramValue);
  }
};

/**
 * 拨打商家电话
 * @param {*} phoneNumber
 */
function callShopPhone(phoneNumber) {
  xma.makePhoneCall({
    phoneNumber, // 仅为示例
  });
}

// 获取定位
function getLocationFn() {
  return new Promise((resolve, reject) => {
    xma.getLocation({
      type: 'wgs84',
      isHighAccuracy: true,
      success: function (res) {
        // 经纬度
        console.log('res.latitude, res.longitude', res.latitude, res.longitude);
        resolve({ lat: res.latitude, lon: res.longitude });
      },
      fail: function (err) {
        return err;
      },
    });
  });
}

// 计算距离的函数封装
async function calculateDistance() {
  try {
    const res = await getLocationFn();
    const distance = getDistance(
      res.lat,
      res.lon,
      shopDetail.value.shopLat,
      shopDetail.value.shopLng,
      1,
    );
    shopDetail.value.distance = distance;
    console.log('distance', distance, shopDetail.value.shopLat, shopDetail.value.shopLng);
  } catch (error) {
    console.error('Error calculating distance:', error);
  }
}

/**
 * 跳转地图
 */

function openMapApp() {
  uni.showActionSheet({
    itemList: ['高德地图', '百度地图'],
    success: (res) => {
      const item = {
        shopAddress: shopDetail.value.shopAddress,
        latitude: shopDetail.value.location.lat,
        longitude: shopDetail.value.location.lon,
        name: shopDetail.value.shopAddress,
      };

      switch (res.tapIndex) {
        case 0:
          // 打开高德地图
          item.name = '高德地图';
          navigationSelect(item);
          break;
        case 1:
          item.name = '百度地图';
          // 打开百度地图
          navigationSelect(item);
          break;
        default:
          break;
      }
    },
    fail: (err) => {
      console.log('取消选择', err);
    },
  });
}

const toShop = () => {
  xma.navigateTo({
    url: `/pages/shop/shop?shopId=${shopId.value}`,
  });
};
</script>

<style scoped lang="scss">
page {
  background: #f3f3f3;
}

.container {
  width: 375 * 2rpx;
  margin: 0 auto;
  .content {
    display: flex;
    flex-direction: column;
    padding: 100rpx 26rpx 26rpx;
    gap: 26rpx;

    .shop {
      display: flex;
      gap: 20rpx;
      background-color: #fff;
      border-radius: 16rpx;
      padding: 24rpx 22rpx 30rpx;

      .logo {
        height: 116rpx;
        width: 116rpx;
        border-radius: 16rpx;
      }

      .info {
        display: flex;
        flex-direction: column;
        gap: 34rpx;

        .top {
          display: flex;
          justify-content: space-between;
          width: 514rpx;

          .left {
            display: flex;
            flex-direction: column;
            gap: 10rpx;

            .title {
              font-family: PingFang SC Bold;
              font-size: 32rpx;
              color: #333333;
              line-height: 32rpx;
            }

            .ratebox {
              display: flex;
              align-items: center;
              gap: 8rpx;
              .icon-statr {
                :deep(.wd-icon-star-on) {
                  display: block !important;
                }
              }
              text {
                font-family: PingFang SC Regular;
                font-size: 24rpx;
                color: #666;
              }

              .rate {
                font-size: 22rpx;
                color: #f12a2a;
              }

              .time {
                color: #333;
              }
            }
          }

          .btn {
            width: 127rpx;
            height: 53rpx;
            border-radius: 27rpx;
            border: 2rpx solid #f12a2a;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: PingFang SC Regular;
            font-size: 24rpx;
            color: #f12a2a;
            gap: 6rpx;

            image {
              width: 30rpx;
              height: 30rpx;
            }
          }
        }

        .bottom {
          display: flex;
          justify-content: space-around;

          .address {
            width: 30rpx;
            height: 30rpx;
          }

          .infobox {
            display: flex;
            flex-direction: column;
            gap: 6rpx;

            text {
              font-family: PingFang SC Regular;
              font-size: 22rpx;
              color: #999999;
            }

            .addr {
              width: 324rpx;
              font-size: 24rpx;
              color: #333;
              text-overflow: ellipsis;
              white-space: nowrap;
              overflow: hidden;
            }
          }

          .iconbox {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 8rpx;
            font-family: PingFang SC Regular;
            font-size: 20rpx;
            color: #666666;

            .img {
              width: 42rpx;
              height: 42rpx;
            }
          }
        }
      }
    }

    .ticket-list {
      display: flex;
      flex-direction: column;
      gap: 36rpx;

      .ticket-item {
        width: 100%;
        background-color: #fff;
        border-radius: 16rpx;
        display: flex;
        flex-direction: column;

        .ticket-box {
          display: flex;

          .normal {
            background: url('../../static/ticket/ticket-normal.png') no-repeat;
            background-size: 100% 100%;
          }

          .past {
            background: url('../../static/ticket/ticket-past.png') no-repeat;
            background-size: 100% 100%;
          }

          .ticket-left {
            width: 200rpx;
            height: 200rpx;

            .ticket-box {
              width: 94%;
              height: 100%;
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              gap: 30rpx;

              .ticket-price {
                display: flex;
                align-items: last baseline;

                text {
                  font-size: 24rpx;
                  line-height: 24rpx;
                  font-family: PingFang SC;
                  color: #fff;
                }

                .num {
                  font-size: 52rpx;
                }
              }

              .ticket-desc {
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 24rpx;

                .desc {
                  font-size: 24rpx;
                  line-height: 24rpx;
                  font-family: PingFang SC;
                  color: #fff;
                }
              }
            }
          }

          .ticket-right {
            display: flex;
            flex-direction: column;
            width: 504rpx;
            position: relative;

            .img {
              width: 126rpx;
              height: 94rpx;
              position: absolute;
              right: 28rpx;
              top: 26rpx;
            }

            .head {
              display: flex;
              flex-direction: column;
              padding: 30rpx 22rpx 26rpx 32rpx;
              gap: 4rpx;

              .title {
                font-family: PingFang SC Heavy-Regular;
                font-size: 32rpx;
                color: #333333;
                line-height: 32rpx;
              }

              .headbox {
                display: flex;
                justify-content: space-between;
                align-items: end;
                height: 50rpx;

                .time {
                  font-family: PingFang SC Heavy-Regular;
                  font-size: 20rpx;
                  color: #999999;
                  line-height: 20rpx;
                }

                .btn {
                  width: 110rpx;
                  height: 50rpx;
                  box-sizing: border-box;
                  border-radius: 26rpx;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  background: linear-gradient(90deg, #ff7051 0%, #ff382e 100%);
                  color: #fff;
                  font-size: 24rpx;
                  line-height: 24rpx;
                }
              }
            }

            .foot {
              display: flex;
              flex-direction: column;
              padding: 0 22rpx 14rpx 32rpx;
              gap: 14rpx;

              .line {
                border-top: 2rpx solid #f2f2f2;
              }

              .footbox {
                display: flex;
                align-items: center;
                justify-content: space-between;

                .desc {
                  font-family: PingFang SC Heavy-Regular;
                  font-size: 20rpx;
                  color: #999999;
                  line-height: 20rpx;
                }
              }
            }
          }
        }

        .detail {
          display: flex;
          flex-direction: column;
          padding: 24rpx 0rpx 56rpx 0rpx;
          gap: 30rpx;

          .line {
            border-top: 2rpx solid #e7e7e7;
          }

          .detail-box {
            display: flex;
            flex-direction: column;
            gap: 40rpx;
            padding: 0 40rpx 0 22rpx;

            .rowbox {
              display: flex;
              flex-direction: row;
              gap: 48rpx;

              text {
                font-family: PingFang SC Regular;
                font-size: 28rpx;
                color: #666666;
                line-height: 28rpx;
              }

              .desc {
                width: 476rpx;
              }
            }
          }
        }
      }

      .coupon-tips {
        width: 100%;
        background-color: #fff;
        border-radius: 16rpx;
        display: flex;
        flex-direction: column;
        padding: 40rpx 46rpx 40rpx;
        // min-height: 436rpx;
        box-sizing: border-box;
        gap: 38rpx;

        .tips {
          font-family: PingFang SC Bold-Regular;
          font-size: 32rpx;
          color: #333333;
          line-height: 32rpx;
          text-align: center;
        }

        .desc {
          white-space: pre-line; /* 将空格和换行符保留在文本中 */
          font-family: PingFang SC Regular;
          font-size: 24rpx;
          color: #333333;
          line-height: 36rpx;
          text-align: left;
        }
      }
    }
  }

  .footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 20rpx 26rpx 60rpx;
    box-sizing: border-box;
    background-color: #f5f5f5;

    .btn {
      width: 100%;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-family: PingFang SC Bold-Regular;
      font-size: 32rpx;
      color: #ffffff;
      background: linear-gradient(180deg, #ff694d 0%, #ff3f33 100%);
      border-radius: 46rpx;
    }
  }
}
</style>
