<template>
  <Popup title="查看评论" isClose ref="popRef">
    <!-- 评论内容 -->
    <template #content>
      <view class="comment-container">
        <view class="comment-content">
          {{ commentDetail.content || $t("暂无评论内容") }}
        </view>

        <ImageGrid
          :images="commentDetail.images"
          v-if="commentDetail.images && commentDetail.images.length"
        />
      </view>
    </template>

    <!-- 底部按钮 -->
    <template #footer>
      <view class="btn-group">
        <view class="cancel-btn" @click="close">
          <trans _t="关闭" />
        </view>
      </view>
    </template>
  </Popup>
</template>

<script setup>
import { computed, ref, onMounted, watch } from "vue";
import Popup from "@/components/popup.vue";
import ImageGrid from "@/components/ImageGrid.vue";
import { t } from "@/locale";
import { SHOP_SHOW_COMMENTS } from "@/api";
import { urlStrToArr } from "@/utils";

// 组件props：接收评论ID
const props = defineProps({
  commentId: {
    type: [String, Number],
    required: true,
    default: "",
  },
});

const emit = defineEmits(["open", "close", "fetchSuccess", "fetchFail"]);

const popRef = ref(null);
// 评论数据
const commentDetail = ref({});

const fetchCommentDetail = async (id) => {
  try {
    const res = await SHOP_SHOW_COMMENTS(id);
    commentDetail.value = res.data;
    commentDetail.value.images = urlStrToArr(commentDetail.value.images);
    popRef.value && popRef.value.open();
    emit("fetchSuccess", res.data);
  } catch (err) {
    emit("fetchFail", { msg: errorMsg.value, error: err });
  }
};

// 监听commentId变化，重新请求数据
watch(
  () => props.commentId,
  (newId) => {
    if (newId && popRef.value?.isShow) {
      fetchCommentDetail(newId);
    }
  },
  { immediate: false }
);

// 打开弹框
const open = (id) => {
  fetchCommentDetail(id);
  emit("open");
};

// 关闭弹框
const close = () => {
  emit("close");
  if (popRef.value) {
    popRef.value.close();
    // 关闭后重置数据
    commentDetail.value = {};
  }
};

// 暴露方法给父组件
defineExpose({ open, close, fetchCommentDetail });
</script>

<style lang="less" scoped>
@import url("@/style.less");
.comment-container {
  width: 100%;
  /* 评论内容样式 */
  .comment-content {
    color: var(--text-01);
    .size(24rpx);
    line-height: 40rpx;
    margin-bottom: 30rpx;
    white-space: pre-wrap;
  }
}

.btn-group {
  display: flex;
  gap: 20rpx;
  width: 100%;
  .cancel-btn,
  .preview-original-btn {
    flex: 1;
    height: 38px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 16rpx;
    .size(24rpx);
  }
  .cancel-btn {
    background-color: var(--black);
    color: var(--light);
  }
  .preview-original-btn {
    background-color: #f5f5f5;
    color: var(--text-01);
    border: 2rpx solid #e5e5e5;
  }
}

/* 旋转动画 */
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
    