<template>
  <div class="app-container">
    <!-- 检索区 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
        <el-form-item label="会员名称" prop="memberNickName">
          <el-input v-model="queryParams.memberNickName" placeholder="会员名称" clearable style="width: 140px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="queryParams.goodsName" placeholder="评价对象名称" clearable style="width: 140px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="评分" prop="score">
          <el-select v-model="queryParams.score" placeholder="全部" clearable style="width: 100px">
            <el-option v-for="item in 5" :key="item" :label="item + ' 星'" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="评价时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br/>

    <!-- 列表区 -->
    <el-card shadow="never" class="table-card">
      <el-tabs v-model="replyTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部" name="all" />
        <el-tab-pane label="未回复" name="UNREPLIED" />
        <el-tab-pane label="已回复" name="REPLIED" />
      </el-tabs>

      <el-row :gutter="10" class="mb8">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="reviewList" :empty-text="emptyTableText">
        <el-table-column label="会员名称" align="center" prop="memberNickName" width="110" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.memberNickName || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="评价对象" align="left" min-width="220">
          <template slot-scope="scope">
            <div class="goods-target">
              <image-preview v-if="scope.row.goodsMainPic" :src="scope.row.goodsMainPic" :width="44" :height="44" />
              <div class="goods-text">
                <div>{{ scope.row.goodsName || '—' }}</div>
                <div class="sub-text">{{ scope.row.goodsSpec || '默认' }}</div>
                <div class="item-tip">一行一评 · 单商品行快照</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="评价内容" align="left" min-width="180" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ contentSummary(scope.row.content) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="晒图" align="center" width="90">
          <template slot-scope="scope">
            <div v-if="scope.row.reviewPics && scope.row.reviewPics.length" class="pic-cell">
              <image-preview :src="scope.row.reviewPics[0]" :width="40" :height="40" />
              <span v-if="scope.row.reviewPics.length > 1" class="pic-count">+{{ scope.row.reviewPics.length - 1 }}</span>
            </div>
            <span v-else>—</span>
          </template>
        </el-table-column>
        <el-table-column label="评分" align="center" width="130">
          <template slot-scope="scope">
            <el-rate :value="scope.row.score != null ? Number(scope.row.score) : 0" disabled />
          </template>
        </el-table-column>
        <el-table-column label="评价时间" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="回复状态" align="center" width="90">
          <template slot-scope="scope">
            <el-tag size="small" :type="replyStatusTag(scope.row.replyStatus)">
              {{ replyStatusLabel(scope.row.replyStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)" v-hasPermi="['agri:seller:review:query']">查看</el-button>
            <el-button size="mini" type="text" icon="el-icon-chat-line-round" @click="handleReply(scope.row)" v-hasPermi="['agri:seller:review:reply']">回复</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['agri:seller:review:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 评价详情抽屉 -->
    <seller-review-detail
      ref="reviewDetail"
      :visible.sync="detailOpen"
      :review-id="currentReviewId"
      @reply="handleReplyFromDetail"
      @view-order="handleViewOrder"
      @success="handleSuccess"
    />

    <!-- 关联订单详情抽屉（只读） -->
    <seller-order-detail
      :visible.sync="orderDetailOpen"
      :order-id="currentOrderId"
      :show-actions="false"
    />

    <!-- 回复弹窗 -->
    <el-dialog :title="replyDialogTitle" :visible.sync="replyOpen" width="560px" append-to-body @close="cancelReply">
      <el-form ref="replyFormRef" :model="replyForm" :rules="replyRules" label-width="90px">
        <el-form-item label="回复内容" prop="replyContent">
          <el-input
            v-model="replyForm.replyContent"
            type="textarea"
            :rows="5"
            placeholder="请输入回复内容，保存后 C 端可见"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReply">确 定</el-button>
        <el-button @click="cancelReply">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSellerReview,
  replySellerReview,
  delSellerReview
} from "@/api/agri/seller/review"
import { getSellerContext } from "@/api/agri/seller/context"
import { setSellerShopContext } from "@/utils/sellerShop"
import SellerReviewDetail from "./detail"
import SellerOrderDetail from "../order/detail"

export default {
  name: "AgriSellerReview",
  components: { SellerReviewDetail, SellerOrderDetail },
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      reviewList: [],
      detailOpen: false,
      currentReviewId: null,
      orderDetailOpen: false,
      currentOrderId: null,
      replyOpen: false,
      replyDialogTitle: "回复评价",
      currentReplyReviewId: null,
      replyTab: "all",
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        replyStatus: undefined,
        score: undefined,
        goodsName: undefined,
        memberNickName: undefined,
        beginTime: undefined,
        endTime: undefined
      },
      replyForm: {
        replyContent: ""
      },
      replyRules: {
        replyContent: [{ required: true, message: "请填写回复内容", trigger: "blur" }]
      }
    }
  },
  computed: {
    /** 是否有检索条件（用于区分空列表文案，对齐需求 §6.3） */
    hasSearchFilter() {
      const q = this.queryParams
      return !!(
        q.memberNickName ||
        q.goodsName ||
        q.score ||
        (this.dateRange && this.dateRange.length === 2) ||
        this.replyTab !== "all"
      )
    },
    emptyTableText() {
      return this.hasSearchFilter ? "未找到符合条件的评价" : "暂无买家评价"
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    initPage() {
      this.loadShopContext().then(() => {
        this.getList()
      }).catch(() => {
        this.getList()
      })
    },
    loadShopContext() {
      return getSellerContext().then(response => {
        const data = response.data || {}
        if (data.shopId != null) {
          setSellerShopContext(data.shopId, data.shopName)
        }
      })
    },
    getList() {
      this.loading = true
      const params = { ...this.queryParams }
      if (this.dateRange && this.dateRange.length === 2) {
        params.beginTime = this.dateRange[0]
        params.endTime = this.dateRange[1]
      } else {
        params.beginTime = undefined
        params.endTime = undefined
      }
      listSellerReview(params).then(response => {
        this.reviewList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    replyStatusLabel(status) {
      const map = { UNREPLIED: "未回复", REPLIED: "已回复" }
      return map[status] || "—"
    },
    replyStatusTag(status) {
      const map = { UNREPLIED: "warning", REPLIED: "success" }
      return map[status] || "info"
    },
    contentSummary(content) {
      if (!content) {
        return "—"
      }
      const text = String(content).trim()
      return text.length > 60 ? text.slice(0, 60) + "…" : text
    },
    handleTabClick() {
      this.queryParams.replyStatus = this.replyTab === "all" ? undefined : this.replyTab
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.replyTab = "all"
      this.resetForm("queryForm")
      this.queryParams.replyStatus = undefined
      this.handleQuery()
    },
    handleDetail(row) {
      this.currentReviewId = row.reviewId
      this.detailOpen = true
    },
    handleReply(row) {
      this.currentReplyReviewId = row.reviewId
      this.replyDialogTitle = row.replyStatus === "REPLIED" ? "修改回复" : "回复评价"
      this.replyForm.replyContent = row.replyContent || ""
      this.replyOpen = true
    },
    handleReplyFromDetail(detail) {
      this.handleReply(detail)
    },
    handleViewOrder(detail) {
      if (!detail.orderId) {
        return
      }
      this.currentOrderId = detail.orderId
      this.orderDetailOpen = true
    },
    cancelReply() {
      this.replyOpen = false
      this.currentReplyReviewId = null
      this.replyForm.replyContent = ""
      this.resetForm("replyFormRef")
    },
    submitReply() {
      this.$refs.replyFormRef.validate(valid => {
        if (!valid) {
          return
        }
        const content = (this.replyForm.replyContent || "").trim()
        replySellerReview(this.currentReplyReviewId, { replyContent: content }).then(() => {
          this.$modal.msgSuccess("回复成功")
          this.replyOpen = false
          this.handleSuccess()
          if (this.detailOpen && this.currentReviewId === this.currentReplyReviewId && this.$refs.reviewDetail) {
            this.$refs.reviewDetail.loadDetail()
          }
        })
      })
    },
    handleDelete(row) {
      this.$modal.confirm("删除后 C 端将不再展示该评价，且买家无法再次评价该商品行（一行一评），是否继续？").then(() => {
        return delSellerReview(row.reviewId)
      }).then(() => {
        this.$modal.msgSuccess("删除成功")
        this.handleSuccess()
      }).catch(() => {})
    },
    handleSuccess() {
      this.getList()
    }
  }
}
</script>

<style scoped>
.goods-target {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}
.goods-text {
  flex: 1;
  min-width: 0;
}
.sub-text {
  margin-top: 2px;
  font-size: 12px;
  color: #909399;
}
.item-tip {
  margin-top: 2px;
  font-size: 11px;
  color: #c0c4cc;
}
.pic-cell {
  position: relative;
  display: inline-block;
}
.pic-count {
  position: absolute;
  right: 0;
  bottom: 0;
  padding: 0 4px;
  font-size: 11px;
  line-height: 16px;
  color: #fff;
  background: rgba(0, 0, 0, 0.55);
  border-radius: 2px 0 0 0;
}
</style>
