<template>
  <view class="container">
    <Header title="订单详情"></Header>
    <view class="content" v-if="orderDetail">
      <!-- 使用状态 -->
      <view class="status">
        <view class="status-box">
          <wd-icon
            name="check-outline"
            size="26px"
            color="#333"
            v-if="orderDetail.orderStore.status == 5 || orderDetail.orderStore.status == 7"
          ></wd-icon>
          <wd-icon
            name="close-outline"
            size="26px"
            color="#333"
            v-if="orderDetail.orderStore.status == 6"
          ></wd-icon>
          <view class="status-text">{{ statusList[orderDetail.orderStore.status] }}</view>
        </view>
        <view class="detail" v-if="orderDetail.orderStore.status == 3">
          请在{{ orderDetail.orderStore.receiverTime.slice(0, 4) }}年{{
            orderDetail.orderStore.receiverTime.slice(5, 7)
          }}月{{ orderDetail.orderStore.receiverTime.slice(8, 10) }}前到店消费
        </view>
      </view>

      <!-- 券码信息 -->
      <view class="info">
        <view class="box">
          <view class="left">
            <image mode="aspectFill" :src="fileDomain + orderDetail.orderItems[0].pic" />
            <view class="left-box">
              <text class="title">{{ orderDetail.orderItems[0].prodName }}</text>
              <!-- <text class="detail">周一至周日 到店吃</text>
              <text class="detail">随时退·过期自动退·免预约</text> -->
              <text class="detail">购买数量：{{ orderDetail.orderItems[0].prodCount }}</text>
              <view class="price-box">
                <text class="icon">￥</text>
                <text class="price">{{ orderDetail.orderItems[0].price }}</text>
              </view>
            </view>
          </view>
          <wd-icon name="chevron-right" size="22px" color="#333"></wd-icon>
        </view>

        <view class="rectangle-with-semicircles"></view>
        <view class="qrcode line">
          <!-- 二维码 -->
          <view class="qr-box" v-if="qrcode">
            <image :src="qrcode" class="qr"></image>
          </view>
          <view class="info-box">
            <view
              class="between"
              v-if="orderDetail.orderStore.status == 2 || orderDetail.orderStore.status == 3"
            >
              <view class="column">
                <text class="title">券码信息（1张可用）</text>
                <text class="text">{{ orderDetail.orderStore.receiverTime }} 到期</text>
              </view>
              <view class="btn" @tap="handleRefund(orderDetail.orderStore.orderNumber)">
                申请退款
              </view>
            </view>
            <view class="between">
              <view class="column">
                <text
                  class="title1"
                  v-if="orderDetail.orderStore.status != 2 || orderDetail.orderStore.status != 3"
                >
                  券码信息
                </text>
                <text
                  :class="
                    orderDetail.orderStore.status == 5 ||
                    orderDetail.orderStore.status == 6 ||
                    orderDetail.orderStore.status == 7
                      ? 'linethrough'
                      : 'phone'
                  "
                >
                  {{ orderDetail.orderStore.orderNumber.slice(6) }}
                </text>
              </view>

              <text class="text">{{ orderStatusList[orderDetail.orderStore.subStatus] }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 地址 -->
      <view class="info" v-if="shopDetail">
        <view class="info-box padding">
          <view class="between" style="margin-bottom: 0">
            <text class="name">{{ shopDetail.shopName }}</text>
            <view class="rowbox" @tap="callShopPhone(shopDetail.phone)">
              <image src="@/static/order/telephone.png" class="img"></image>
              <text class="text">联系商家</text>
            </view>
          </view>
          <view class="rowbox">
            <image src="@/static/order/time.png" class="img1"></image>
            <text class="address">
              营业时间 {{ shopDetail.transactionStart }}-{{ shopDetail.transactionEnd }}
            </text>
          </view>
          <view class="rowbox">
            <image src="@/static/order/address.png" class="img1"></image>
            <text class="address">{{ shopDetail.shopAddress }} 距您{{ shopDetail.distance }}</text>
          </view>
        </view>
      </view>

      <!-- 套餐信息 -->
      <view class="info" v-if="prodDetail">
        <view class="menu padding">
          <text class="title">到店吃套餐</text>
          <view class="menu-box" v-for="(item, index) in prodDetail.prodAdditionals" :key="index">
            <view class="header">
              <view class="circle"></view>
              <text class="h-name">{{ item.categorizeName }}</text>
            </view>
            <view class="list-box">
              <text class="name">{{ item.prodName }}</text>
              <view class="right-box">
                <text class="num">({{ item.count }}份)</text>
                <view class="price-box">
                  <text class="icon">￥</text>
                  <text class="num">{{ item.price }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 温馨提示 -->
      <view class="info" v-if="prodDetail">
        <view class="tips padding">
          <text class="title">温馨提示</text>
          <view class="tips-box">
            <view class="row">
              <text class="name">使用时间</text>
              <text class="colon">：</text>
              <text class="text">
                {{ prodDetail.groupPurchasePackageRule.startTime.slice(0, 16) }}-{{
                  prodDetail.groupPurchasePackageRule.endTime.slice(0, 16)
                }}
              </text>
            </view>
            <view class="row">
              <text class="name">使用规则</text>
              <text class="colon">：</text>
              <text class="textarea">{{ prodDetail.groupPurchasePackageRule.rule }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 订单详情 -->
      <view class="info">
        <view class="tips padding">
          <text class="title">实付金额：￥{{ orderDetail.orderStore.actualTotal }}</text>
          <view class="tips-box">
            <view class="row">
              <text class="name">订单号</text>
              <text class="colon">：</text>
              <view class="copybox">
                <text class="text">{{ orderDetail.orderStore.orderNumber.slice(6) }}</text>
                <view
                  class="copy"
                  @tap="copyTextToClipboard(orderDetail.orderStore.orderNumber.slice(6))"
                >
                  复制
                </view>
              </view>
            </view>
            <view class="row">
              <text class="name">手机号</text>
              <text class="colon">：</text>
              <text class="text">{{ maskPhoneNumber(orderDetail.orderStore.receiverMobile) }}</text>
            </view>
            <view class="row" v-if="orderDetail.orderStore.payTime">
              <text class="name">付款时间</text>
              <text class="colon">：</text>
              <text class="text">{{ orderDetail.orderStore.payTime }}</text>
            </view>
            <view class="row">
              <text class="name">下单时间</text>
              <text class="colon">：</text>
              <text class="text">{{ orderDetail.orderStore.createTime }}</text>
            </view>
            <view class="row">
              <text class="name">数量</text>
              <text class="colon">：</text>
              <text class="text">{{ orderDetail.orderItems[0].prodCount }}</text>
            </view>
            <view class="row">
              <text class="name">总价</text>
              <text class="colon">：</text>
              <text class="text">￥{{ orderDetail.orderStore.total }}</text>
            </view>
            <view class="row">
              <text class="name">优惠明细</text>
              <text class="colon">：</text>
              <text class="text">-￥{{ orderDetail.orderStore.reduceAmount }}</text>
            </view>
            <view class="row">
              <text class="name">实付</text>
              <text class="colon">：</text>
              <text class="text">￥{{ orderDetail.orderStore.actualTotal }}</text>
            </view>
          </view>
        </view>
      </view>

      <view style="height: 340rpx"></view>
    </view>

    <view class="footer">
      <view class="btn" @tap="anotherOrder">再来一单</view>
    </view>
  </view>
</template>

<script setup>
import Header from './components/Header/index.vue';
import QRCode from 'qrcode';
import { getOrderDetail, getShopDetail, getProdDetail } from '@/api/order';
import { getDistance } from '@/utils/common';

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

// 当前位置的经纬度
const currentLatitudeAndLongitude = ref({ latitude: 0, longitude: 0 });
const fileDomain = import.meta.env.VITE_APP_IMG_URL;
const statusList = ref({
  1: '待付款',
  2: '待到店使用',
  3: '待到店使用',
  4: '待评价',
  5: '已完成',
  6: '已取消',
  7: '已退款',
});

const orderStatusList = ref({
  1: '待付款',
  2: '待使用',
  3: '待使用',
  4: '待评价',
  5: '已完成',
  6: '已取消',
  7: '已退款',
});

const orderNumber = ref('');
onLoad((options) => {
  orderNumber.value = options.orderNumber;
  getDetail();
});

/**
 * 获取订单详情
 */
const orderDetail = ref();
const getDetail = async () => {
  const res = await getOrderDetail({ orderNumber: orderNumber.value });
  orderDetail.value = res.data;
  if (orderDetail.value.orderStore.status === '2' || orderDetail.value.orderStore.status === '3') {
    codeDetail(orderDetail.value.orderStore.orderNumber);
  }
  getProductDetail(orderDetail.value.orderItems[0].prodId);
  getShopMailDetail(orderDetail.value.baseOrder.shopId);
};

/**
 * 生成二维码
 */
const qrcode = ref('');
const codeDetail = (item) => {
  const data = {
    type: 'write-off',
    no: item,
  };
  QRCode.toDataURL(JSON.stringify(data)).then((img) => {
    console.log(img);
    qrcode.value = img;
  });
};

/**
 * 获取商品详情
 */
const prodDetail = ref();
const getProductDetail = async (id) => {
  const res = await getProdDetail({ prodId: id });
  prodDetail.value = res.data.data;
};

/**
 * 获取商铺信息
 */
const shopDetail = ref();
const getShopMailDetail = async (id) => {
  const res = await getShopDetail({ shopId: id });
  shopDetail.value = res.data.shop;
  // 获取位置并计算距离
  calculateDistance();
};

const maskPhoneNumber = (phone) => {
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};

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);
  }
}

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

/**
 * 复制到剪切板
 * @param {*} text
 */
function copyTextToClipboard(text) {
  xma.setClipboardData({
    data: text,
    success: function () {
      // 可以添加用户友好的提示，例如使用uni.showToast提示复制成功
      xma.showToast({
        title: '复制成功',
        icon: 'success',
        duration: 2000,
      });
    },
  });
}

const handleRefund = (item) => {
  xma.navigateTo({
    url: `/pages/order/refund?orderNumber=${item.orderNumber}`,
  });
};

const anotherOrder = () => {
  xma.navigateTo({
    url: `/pages/shop/confirmOrder?prodId=${orderDetail.value.orderItems[0].prodId}&skuId=${orderDetail.value.orderItems[0].skuId}`,
  });
};
</script>

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

.container {
  width: 375 * 2rpx;
  margin: 0 auto;

  .content {
    padding-top: 44px;
    display: flex;
    flex-direction: column;
    gap: 20rpx;
  }

  .status {
    display: flex;
    flex-direction: column;
    padding: 32rpx 20rpx 12rpx;
    gap: 6rpx;

    .status-box {
      display: flex;
      align-items: center;
      gap: 6rpx;

      .status-text {
        font-size: 48rpx;
        font-weight: bold;
        color: #333;
        font-family: PingFang SC;
      }
    }

    .detail {
      font-size: 28rpx;
      color: #999;
      font-family: PingFang SC;
    }
  }

  .info {
    background-color: #fff;
    border-radius: 16rpx;
    margin: 0 20rpx;

    // 二维码头部
    .box {
      padding: 20rpx;
      display: flex;
      justify-content: space-between;

      .left {
        display: flex;
        gap: 20rpx;

        image {
          height: 128rpx;
          width: 128rpx;
          border-radius: 8rpx;
        }

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

          text {
            font-family: PingFang SC;
            color: #333;
            font-size: 24rpx;
          }

          .title {
            font-size: 28rpx;
            font-weight: bold;
          }

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

            .icon {
              font-weight: bold;
            }

            .price {
              font-size: 32rpx;
              font-weight: bold;
            }
          }
        }
      }
    }

    .line {
      border-top: 1px dashed #999;
    }

    .rectangle-with-semicircles {
      width: 100%;
      position: relative;
      z-index: 10;
      height: 20rpx;
    }

    .rectangle-with-semicircles::after {
      position: absolute;
      content: '';
      height: 32rpx;
      width: 32rpx;
      border-radius: 50%;
      background-color: #f5f5f5;
      left: 0;
      top: 50%;
      transform: translate(-50%);
    }

    .rectangle-with-semicircles::before {
      position: absolute;
      content: '';
      height: 32rpx;
      width: 32rpx;
      border-radius: 50%;
      background-color: #f5f5f5;
      right: 0;
      top: 50%;
      transform: translate(50%);
    }

    // 二维码
    .qrcode {
      padding: 30rpx 20rpx 20rpx;
      display: flex;
      flex-direction: column;
      gap: 20rpx;

      .qr-box {
        display: flex;
        justify-content: center;
        align-items: center;

        .qr {
          width: 400rpx;
          height: 400rpx;
        }
      }
    }

    .padding {
      padding: 20rpx;
    }

    // 券码&地址信息
    .info-box {
      display: flex;
      flex-direction: column;
      gap: 10rpx;

      .between {
        display: flex;
        justify-content: space-between;
        margin-bottom: 28rpx;
      }

      .column {
        display: flex;
        flex-direction: column;
        gap: 18rpx;
      }

      text {
        font-family: PingFang SC Heavy;
        letter-spacing: 0em;
        color: #333;
      }

      .title {
        font-size: 32rpx;
        line-height: 32rpx;
        font-weight: bold;
      }

      .title1 {
        font-size: 32rpx;
        line-height: 32rpx;
      }

      .text {
        font-size: 24rpx;
        line-height: 24rpx;
      }

      .linethrough {
        text-decoration: line-through;
        font-size: 28rpx;
        line-height: 28rpx;
        color: #999;
      }

      .phone {
        font-size: 28rpx;
        line-height: 28rpx;
        font-weight: bold;
      }

      .name {
        font-size: 32rpx;
        line-height: 56rpx;
        font-weight: bold;
      }

      .btn {
        width: 142rpx;
        height: 58rpx;
        border-radius: 30rpx;
        border: 1rpx solid #999999;
        color: #333;
        font-size: 24rpx;
        font-family: PingFang SC;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .rowbox {
        display: flex;
        align-items: center;
        gap: 4rpx;

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

        .img1 {
          width: 28rpx;
          height: 28rpx;
        }

        .address {
          color: #666;
          font-family: PingFang SC Regular;
          font-size: 24rpx;
          font-weight: normal;
          line-height: 24rpx;
          letter-spacing: 0em;
        }
      }
    }

    // 套餐信息
    .menu {
      display: flex;
      flex-direction: column;
      gap: 14rpx;

      .title {
        color: #333;
        font-family: PingFang SC Bold;
        font-weight: bold;
        font-size: 36rpx;
        line-height: 36rpx;
        letter-spacing: 0rem;
      }

      .menu-box {
        display: flex;
        flex-direction: column;
        gap: 24rpx;
        margin-bottom: 16rpx;

        .header {
          display: flex;
          align-items: center;
          gap: 6rpx;

          .circle {
            width: 8rpx;
            height: 8rpx;
            border-radius: 50%;
            background-color: #333;
          }

          .h-name {
            font-family:
              PingFang SC,
              PingFang SC;
            font-weight: bold;
            font-size: 28rpx;
            color: #333333;
            text-align: left;
            font-style: normal;
            text-transform: none;
          }
        }

        .list-box {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-left: 14rpx;

          .name {
            font-family: PingFang SC Bold;
            font-size: 28rpx;
            font-weight: normal;
            line-height: 28rpx;
            letter-spacing: 0rem;
            color: #333333;
          }

          .right-box {
            display: flex;
            align-items: center;
            gap: 20rpx;

            .num {
              font-family: PingFang SC Regular;
              font-size: 26rpx;
              font-weight: normal;
              line-height: 26rpx;
              letter-spacing: 0rem;
              color: #999999;
            }

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

              text {
                font-family: PingFang SC Bold;
                font-size: 32rpx;
                font-weight: bold;
                letter-spacing: 0rem;
                color: #333;
              }

              .icon {
                font-size: 26rpx;
              }
            }
          }
        }
      }
    }

    // 提示&订单信息
    .tips {
      display: flex;
      flex-direction: column;
      gap: 28rpx;

      .title {
        color: #333;
        font-family: PingFang SC Bold;
        font-weight: bold;
        font-size: 36rpx;
        line-height: 36rpx;
        letter-spacing: 0rem;
      }

      .tips-box {
        display: flex;
        flex-direction: column;
        gap: 24rpx;
        margin-bottom: 10rpx;

        .row {
          display: flex;
          gap: 8rpx;

          .name {
            width: 120rpx;
            font-family: PingFang SC Regular;
            font-size: 28rpx;
            font-weight: normal;
            line-height: 28rpx;
            letter-spacing: 0rem;
            color: #999999;
            text-align-last: justify;
          }

          .colon {
            font-family: PingFang SC Regular;
            font-size: 28rpx;
            font-weight: normal;
            line-height: 28rpx;
            color: #999999;
          }

          .text {
            font-family: PingFang SC Regular;
            font-size: 28rpx;
            font-weight: normal;
            line-height: 28rpx;
            letter-spacing: 0rem;
            color: #333333;
          }

          .textarea {
            width: 510rpx;
            text-align: justify;
            font-family: PingFang SC Regular;
            font-size: 28rpx;
            font-weight: normal;
            line-height: 42rpx;
            letter-spacing: 0rem;
            color: #333333;
          }

          .copybox {
            display: flex;
            align-items: center;
            gap: 8rpx;
          }

          .copy {
            width: 60rpx;
            height: 34rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #707070;
            font-size: 24rpx;
            border-radius: 6rpx;
            border: 1rpx solid #707070;
          }
        }
      }
    }
  }

  .footer {
    position: fixed;
    bottom: 0;
    background-color: #fff;
    height: 188rpx;
    width: 100%;
    z-index: 10;
    display: flex;
    justify-content: flex-end;
    padding: 20rpx 38rpx 0;
    box-sizing: border-box;

    .btn {
      width: 188rpx;
      height: 76rpx;
      background: linear-gradient(90deg, #f73f3f 0%, #ec1a1a 100%);
      border-radius: 40rpx;
      color: #fff;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
