<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <!-- 京东评论标签页 -->
      <el-tab-pane label="京东评论" name="jd">
        <div class="comment-container">
          <!-- 搜索区域 -->
          <mobile-search-form
            :model="jdQueryParams"
            @search="handleJdQuery"
            @reset="resetJdQuery"
          >
            <template #form="{ expanded }">
              <el-form 
                :inline="true" 
                :model="jdQueryParams" 
                class="demo-form-inline" 
                size="small"
                label-width="68px"
              >
                <el-form-item label="商品ID">
                  <el-input v-model="jdQueryParams.productId" placeholder="商品ID" clearable @keyup.enter.native="handleJdQuery" />
                </el-form-item>
                <el-form-item label="产品类型">
                  <el-select v-model="jdQueryParams.productType" placeholder="请选择" clearable filterable style="width: 200px;">
                    <el-option
                      v-for="(value, key) in jdProductTypeMap"
                      :key="key"
                      :label="key"
                      :value="key">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="用户名">
                  <el-input v-model="jdQueryParams.userName" placeholder="用户名" clearable @keyup.enter.native="handleJdQuery" />
                </el-form-item>
                <el-form-item label="使用状态">
                  <el-select v-model="jdQueryParams.isUse" placeholder="全部" clearable style="width: 120px;">
                    <el-option label="未使用" :value="0" />
                    <el-option label="已使用" :value="1" />
                  </el-select>
                </el-form-item>
                <el-form-item label="创建时间">
                  <el-date-picker
                    v-model="jdDateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    @change="handleJdDateRangeChange"
                  />
                </el-form-item>
                <!-- 桌面端搜索按钮 -->
                <el-form-item v-if="!expanded">
                  <el-button type="primary" icon="el-icon-search" size="small" @click="handleJdQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" size="small" @click="resetJdQuery">重置</el-button>
                  <el-button type="warning" icon="el-icon-upload2" size="small" :loading="jdFetchLoading" @click="handleJdFetchComments">获取评论</el-button>
                  <el-button type="success" icon="el-icon-download" size="small" @click="handleJdExport">导出</el-button>
                </el-form-item>
              </el-form>
            </template>
          </mobile-search-form>
          
          <!-- 操作按钮区域（移动端单独显示） -->
          <div class="action-buttons-section mobile-only">
            <mobile-button-group
              :buttons="jdActionButtons"
              :primary-count="2"
            />
          </div>
          
          <!-- 桌面端按钮组 -->
          <div class="desktop-action-buttons desktop-only">
            <el-button type="warning" icon="el-icon-upload2" size="small" :loading="jdFetchLoading" @click="handleJdFetchComments">获取评论</el-button>
            <el-button type="success" icon="el-icon-download" size="small" @click="handleJdExport">导出</el-button>
          </div>

          <!-- 表格区域 -->
          <el-table v-loading="jdLoading" :data="jdList" border>
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="ID" prop="id" width="80" />
            <el-table-column label="产品类型" prop="productType" width="150" />
            <el-table-column label="商品ID" prop="productId" width="200" />
            <el-table-column label="用户名" prop="userName" width="120" />
            <el-table-column label="评论内容" prop="commentText" min-width="300" show-overflow-tooltip />
            <el-table-column label="评论ID" prop="commentId" width="150" />
            <el-table-column label="图片" width="100" align="center">
              <template slot-scope="scope">
                <el-button v-if="scope.row.pictureUrls" type="text" @click="viewImages(scope.row.pictureUrls)">查看图片</el-button>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="使用状态" prop="isUse" width="100" align="center">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isUse === 0 ? 'success' : 'info'" size="small">
                  {{ scope.row.isUse === 0 ? '未使用' : '已使用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createdAt" width="180" align="center">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  :type="scope.row.isUse === 0 ? 'warning' : 'success'"
                  @click="toggleJdCommentUse(scope.row)"
                >
                  {{ scope.row.isUse === 0 ? '标记已使用' : '标记未使用' }}
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleJdDelete(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination
            v-show="jdTotal > 0"
            :total="jdTotal"
            :page.sync="jdQueryParams.pageNum"
            :limit.sync="jdQueryParams.pageSize"
            @pagination="getJdList"
          />
        </div>
      </el-tab-pane>

      <!-- 淘宝评论标签页 -->
      <el-tab-pane label="淘宝评论" name="tb">
        <div class="comment-container">
          <!-- 搜索区域 -->
          <mobile-search-form
            :model="tbQueryParams"
            @search="handleTbQuery"
            @reset="resetTbQuery"
          >
            <template #form="{ expanded }">
              <el-form 
                :inline="true" 
                :model="tbQueryParams" 
                class="demo-form-inline" 
                size="small"
                label-width="68px"
              >
                <el-form-item label="商品ID">
                  <el-input v-model="tbQueryParams.productId" placeholder="商品ID" clearable @keyup.enter.native="handleTbQuery" />
                </el-form-item>
                <el-form-item label="产品类型">
                  <el-select v-model="tbQueryParams.productType" placeholder="请选择" clearable filterable style="width: 200px;">
                    <el-option
                      v-for="(value, key) in tbProductTypeMap"
                      :key="key"
                      :label="key"
                      :value="key">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="用户名">
                  <el-input v-model="tbQueryParams.userName" placeholder="用户名" clearable @keyup.enter.native="handleTbQuery" />
                </el-form-item>
                <el-form-item label="使用状态">
                  <el-select v-model="tbQueryParams.isUse" placeholder="全部" clearable style="width: 120px;">
                    <el-option label="未使用" :value="0" />
                    <el-option label="已使用" :value="1" />
                  </el-select>
                </el-form-item>
                <el-form-item label="创建时间">
                  <el-date-picker
                    v-model="tbDateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    @change="handleTbDateRangeChange"
                  />
                </el-form-item>
                <!-- 桌面端搜索按钮 -->
                <el-form-item v-if="!expanded">
                  <el-button type="primary" icon="el-icon-search" size="small" @click="handleTbQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" size="small" @click="resetTbQuery">重置</el-button>
                  <el-button type="warning" icon="el-icon-upload2" size="small" :loading="tbFetchLoading" @click="handleTbFetchComments">获取评论</el-button>
                  <el-button type="success" icon="el-icon-download" size="small" @click="handleTbExport">导出</el-button>
                </el-form-item>
              </el-form>
            </template>
          </mobile-search-form>
          
          <!-- 操作按钮区域（移动端单独显示） -->
          <div class="action-buttons-section mobile-only">
            <mobile-button-group
              :buttons="tbActionButtons"
              :primary-count="2"
            />
          </div>
          
          <!-- 桌面端按钮组 -->
          <div class="desktop-action-buttons desktop-only">
            <el-button type="warning" icon="el-icon-upload2" size="small" :loading="tbFetchLoading" @click="handleTbFetchComments">获取评论</el-button>
            <el-button type="success" icon="el-icon-download" size="small" @click="handleTbExport">导出</el-button>
          </div>

          <!-- 表格区域 -->
          <el-table v-loading="tbLoading" :data="tbList" border>
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="ID" prop="id" width="80" />
            <el-table-column label="产品类型" prop="productType" width="150" />
            <el-table-column label="商品ID" prop="productId" width="200" />
            <el-table-column label="用户名" prop="userName" width="120" />
            <el-table-column label="评论内容" prop="commentText" min-width="300" show-overflow-tooltip />
            <el-table-column label="评论ID" prop="commentId" width="150" />
            <el-table-column label="图片" width="100" align="center">
              <template slot-scope="scope">
                <el-button v-if="scope.row.pictureUrls" type="text" @click="viewImages(scope.row.pictureUrls)">查看图片</el-button>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="使用状态" prop="isUse" width="100" align="center">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isUse === 0 ? 'success' : 'info'" size="small">
                  {{ scope.row.isUse === 0 ? '未使用' : '已使用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createdAt" width="180" align="center">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  :type="scope.row.isUse === 0 ? 'warning' : 'success'"
                  @click="toggleTbCommentUse(scope.row)"
                >
                  {{ scope.row.isUse === 0 ? '标记已使用' : '标记未使用' }}
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleTbDelete(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination
            v-show="tbTotal > 0"
            :total="tbTotal"
            :page.sync="tbQueryParams.pageNum"
            :limit.sync="tbQueryParams.pageSize"
            @pagination="getTbList"
          />
        </div>
      </el-tab-pane>

      <!-- 统计信息标签页 -->
      <el-tab-pane label="统计信息" name="statistics">
        <div class="statistics-container">
          <el-form :inline="true" :model="statQueryParams" class="demo-form-inline" size="small">
            <el-form-item label="评论来源">
              <el-select v-model="statQueryParams.source" placeholder="全部" clearable style="width: 150px;">
                <el-option label="京东评论" value="jd" />
                <el-option label="淘宝评论" value="tb" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="small" @click="getStatistics">查询</el-button>
              <el-button icon="el-icon-refresh" size="small" @click="resetStatistics">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 统计表格 -->
          <el-table v-loading="statLoading" :data="statisticsList" border style="margin-top: 20px;">
            <el-table-column label="来源" prop="source" width="120" />
            <el-table-column label="产品类型" prop="productType" width="200" />
            <el-table-column label="商品ID" prop="productId" width="200" />
            <el-table-column label="总评论数" prop="totalCount" width="120" align="center" />
            <el-table-column label="可用数" prop="availableCount" width="120" align="center">
              <template slot-scope="scope">
                <span style="color: #67C23A; font-weight: bold;">{{ scope.row.availableCount }}</span>
              </template>
            </el-table-column>
            <el-table-column label="已使用" prop="usedCount" width="120" align="center">
              <template slot-scope="scope">
                <span style="color: #909399;">{{ scope.row.usedCount }}</span>
              </template>
            </el-table-column>
            <el-table-column label="接口调用次数" prop="apiCallCount" width="150" align="center">
              <template slot-scope="scope">
                <span style="color: #409EFF; font-weight: bold;">{{ scope.row.apiCallCount || 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="今日调用" prop="todayCallCount" width="150" align="center">
              <template slot-scope="scope">
                <span style="color: #E6A23C; font-weight: bold;">{{ scope.row.todayCallCount || 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="使用率" width="150" align="center">
              <template slot-scope="scope">
                <el-progress 
                  :percentage="getUsagePercentage(scope.row)" 
                  :color="getUsageColor(scope.row)"
                  :stroke-width="20"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center" fixed="right">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.source === '京东评论'"
                  type="warning"
                  size="mini"
                  icon="el-icon-upload2"
                  :loading="statFetchLoading"
                  @click="handleStatFetchComments(scope.row)"
                >获取评论</el-button>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 图片查看对话框 -->
    <el-dialog title="评论图片" :visible.sync="imageDialogVisible" width="80%">
      <div class="image-gallery">
        <el-image
          v-for="(img, index) in imageList"
          :key="index"
          :src="img"
          :preview-src-list="imageList"
          fit="contain"
          style="width: 200px; height: 200px; margin: 10px;"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  listJdComment, getJdComment, updateJdComment, delJdComment, resetJdCommentByProductId,
  listTbComment, getTbComment, updateTbComment, delTbComment, resetTbCommentByProductId,
  getCommentStatistics, getJdProductTypeMap, getTbProductTypeMap, fetchComments
} from '@/api/jarvis/comment'
import { mapGetters } from 'vuex'
import MobileSearchForm from '@/components/MobileSearchForm'
import MobileButtonGroup from '@/components/MobileButtonGroup'

export default {
  name: 'CommentManagement',
  components: {
    MobileSearchForm,
    MobileButtonGroup
  },
  data() {
    return {
      activeTab: 'jd',
      // 京东评论
      jdLoading: false,
      jdList: [],
      jdTotal: 0,
      jdQueryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: null,
        productType: null,
        userName: null,
        isUse: null
      },
      jdDateRange: [],
      jdProductTypeMap: {},
      // 淘宝评论
      tbLoading: false,
      tbList: [],
      tbTotal: 0,
      tbQueryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: null,
        productType: null,
        userName: null,
        isUse: null
      },
      tbDateRange: [],
      tbProductTypeMap: {},
      // 统计信息
      statLoading: false,
      statisticsList: [],
      statQueryParams: {
        source: null
      },
      // 图片查看
      imageDialogVisible: false,
      imageList: [],
      // 获取评论 loading
      jdFetchLoading: false,
      tbFetchLoading: false,
      statFetchLoading: false
    }
  },
  computed: {
    ...mapGetters(['device']),
    isMobile() {
      if (this.device === 'mobile') {
        return true
      }
      if (typeof window !== 'undefined' && window.innerWidth < 768) {
        return true
      }
      return false
    },
    jdActionButtons() {
      return [
        { key: 'fetchComments', label: '获取评论', type: 'warning', icon: 'el-icon-upload2', handler: () => this.handleJdFetchComments(), disabled: this.jdFetchLoading },
        { key: 'export', label: '导出', type: 'success', icon: 'el-icon-download', handler: () => this.handleJdExport(), disabled: false }
      ]
    },
    tbActionButtons() {
      return [
        { key: 'fetchComments', label: '获取评论', type: 'warning', icon: 'el-icon-upload2', handler: () => this.handleTbFetchComments(), disabled: this.tbFetchLoading },
        { key: 'export', label: '导出', type: 'success', icon: 'el-icon-download', handler: () => this.handleTbExport(), disabled: false }
      ]
    }
  },
  created() {
    this.getJdList()
    this.getJdProductTypeMap()
    this.getTbProductTypeMap()
  },
  methods: {
    // 京东评论相关
    getJdList() {
      this.jdLoading = true
      listJdComment(this.addDateRange(this.jdQueryParams, this.jdDateRange)).then(response => {
        this.jdList = response.rows
        this.jdTotal = response.total
        this.jdLoading = false
      })
    },
    handleJdQuery() {
      this.jdQueryParams.pageNum = 1
      this.getJdList()
    },
    resetJdQuery() {
      this.jdDateRange = []
      this.resetForm('jdQueryParams')
      this.handleJdQuery()
    },
    handleJdDateRangeChange(value) {
      this.jdDateRange = value
    },
    toggleJdCommentUse(row) {
      const newIsUse = row.isUse === 0 ? 1 : 0
      updateJdComment({ id: row.id, isUse: newIsUse }).then(() => {
        this.$modal.msgSuccess('操作成功')
        this.getJdList()
      })
    },
    handleJdDelete(row) {
      this.$modal.confirm('是否确认删除ID为"' + row.id + '"的评论？').then(() => {
        return delJdComment(row.id)
      }).then(() => {
        this.getJdList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    handleJdExport() {
      this.download('jarvis/comment/jd/export', {
        ...this.jdQueryParams
      }, `jd_comment_${new Date().getTime()}.xlsx`)
    },
    /** 统计信息表格：仅京东商品可点击，用该行商品ID 调用获取评论 */
    handleStatFetchComments(row) {
      if (row.source !== '京东评论') return
      const productId = (row.productId || '').toString().trim()
      if (!productId) {
        this.$modal.msgWarning('商品ID为空')
        return
      }
      this.statFetchLoading = true
      fetchComments(productId).then(() => {
        this.$modal.msgSuccess('获取评论请求已发送')
        this.getStatistics()
      }).catch(e => {
        this.$modal.msgError(e && (e.message || e.msg) || '获取评论失败')
      }).finally(() => {
        this.statFetchLoading = false
      })
    },
    /** 京东：调用获取评论接口，使用商品ID(SKU) 作为 product_id */
    handleJdFetchComments() {
      const productId = (this.jdQueryParams.productId || '').toString().trim()
      if (!productId) {
        this.$modal.msgWarning('请先输入商品ID(SKU)')
        return
      }
      this.jdFetchLoading = true
      fetchComments(productId).then(() => {
        this.$modal.msgSuccess('获取评论请求已发送')
        this.getJdList()
      }).catch(e => {
        this.$modal.msgError(e && (e.message || e.msg) || '获取评论失败')
      }).finally(() => {
        this.jdFetchLoading = false
      })
    },
    // 淘宝评论相关
    getTbList() {
      this.tbLoading = true
      listTbComment(this.addDateRange(this.tbQueryParams, this.tbDateRange)).then(response => {
        this.tbList = response.rows
        this.tbTotal = response.total
        this.tbLoading = false
      })
    },
    handleTbQuery() {
      this.tbQueryParams.pageNum = 1
      this.getTbList()
    },
    resetTbQuery() {
      this.tbDateRange = []
      this.resetForm('tbQueryParams')
      this.handleTbQuery()
    },
    handleTbDateRangeChange(value) {
      this.tbDateRange = value
    },
    toggleTbCommentUse(row) {
      const newIsUse = row.isUse === 0 ? 1 : 0
      updateTbComment({ id: row.id, isUse: newIsUse }).then(() => {
        this.$modal.msgSuccess('操作成功')
        this.getTbList()
      })
    },
    handleTbDelete(row) {
      this.$modal.confirm('是否确认删除ID为"' + row.id + '"的评论？').then(() => {
        return delTbComment(row.id)
      }).then(() => {
        this.getTbList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    handleTbExport() {
      this.download('jarvis/taobaoComment/export', {
        ...this.tbQueryParams
      }, `tb_comment_${new Date().getTime()}.xlsx`)
    },
    /** 淘宝：调用获取评论接口，使用商品ID(SKU) 作为 product_id */
    handleTbFetchComments() {
      const productId = (this.tbQueryParams.productId || '').toString().trim()
      if (!productId) {
        this.$modal.msgWarning('请先输入商品ID(SKU)')
        return
      }
      this.tbFetchLoading = true
      fetchComments(productId).then(() => {
        this.$modal.msgSuccess('获取评论请求已发送')
        this.getTbList()
      }).catch(e => {
        this.$modal.msgError(e && (e.message || e.msg) || '获取评论失败')
      }).finally(() => {
        this.tbFetchLoading = false
      })
    },
    // 统计信息相关
    getStatistics() {
      this.statLoading = true
      getCommentStatistics(this.statQueryParams.source).then(response => {
        this.statisticsList = response.data
        this.statLoading = false
      })
    },
    resetStatistics() {
      this.statQueryParams.source = null
      this.getStatistics()
    },
    getUsagePercentage(row) {
      if (!row.totalCount || row.totalCount === 0) return 0
      return Math.round((row.usedCount / row.totalCount) * 100)
    },
    getUsageColor(row) {
      const percentage = this.getUsagePercentage(row)
      if (percentage < 50) return '#67C23A'
      if (percentage < 80) return '#E6A23C'
      return '#F56C6C'
    },
    // Redis映射
    getJdProductTypeMap() {
      getJdProductTypeMap().then(response => {
        this.jdProductTypeMap = response.data || {}
      })
    },
    getTbProductTypeMap() {
      getTbProductTypeMap().then(response => {
        this.tbProductTypeMap = response.data || {}
      })
    },
    // 标签页切换
    handleTabClick(tab) {
      if (tab.name === 'jd') {
        if (this.jdList.length === 0) {
          this.getJdList()
        }
      } else if (tab.name === 'tb') {
        if (this.tbList.length === 0) {
          this.getTbList()
        }
      } else if (tab.name === 'statistics') {
        if (this.statisticsList.length === 0) {
          this.getStatistics()
        }
      }
    },
    // 查看图片
    viewImages(pictureUrls) {
      if (pictureUrls) {
        try {
          this.imageList = JSON.parse(pictureUrls)
        } catch (e) {
          this.imageList = pictureUrls.split(',').filter(url => url.trim())
        }
        this.imageDialogVisible = true
      }
    }
  }
}
</script>

<style scoped>
.comment-container, .statistics-container {
  padding: 20px;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

/* 操作按钮区域 */
.action-buttons-section {
  margin-top: 12px;
  margin-bottom: 12px;
}

/* 移动端和桌面端按钮组显示控制 */
@media (max-width: 768px) {
  .desktop-only {
    display: none !important;
  }
  
  .action-buttons-section.mobile-only {
    display: block;
  }
}

@media (min-width: 769px) {
  .mobile-only {
    display: none !important;
  }
  
  .desktop-action-buttons.desktop-only {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 12px;
  }
}

.desktop-action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 12px;
}
</style>

