<template>
  <div>
    <div class="card">
      <h2>心理资源个性化推荐</h2>
      <p class="sub-title">根据您的评分记录和相似用户的喜好为您推荐</p>
    </div>

    <!-- 推荐资源列表 -->
    <div class="card" v-loading="data.loading">
      <div v-if="data.recommendResources.length > 0" class="recommend-list">
        <el-row :gutter="20">
          <el-col :span="12" v-for="(item, index) in data.recommendResources" :key="index">
            <el-card class="resource-card" shadow="hover">
              <div class="resource-card-header">
                <span class="resource-title">{{ item.title }}</span>
                <span :class="getStatusClass(item.auditStatus)">{{ getStatusText(item.auditStatus) }}</span>
              </div>
              <div class="resource-card-content">
                <div class="resource-meta">
                  <div class="meta-item">
                    <el-icon><Folder /></el-icon>
                    <span>{{ item.categoryName }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><InfoFilled /></el-icon>
                    <span>{{ item.applicableSymptoms }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><View /></el-icon>
                    <span>浏览: {{ item.visitCount || 0 }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><Download /></el-icon>
                    <span>下载: {{ item.downloadCount || 0 }}</span>
                  </div>
                </div>
                <div class="similarity-info">
                  <div class="similarity-score">
                    <el-progress :percentage="item.similarityScore" :color="getSimilarityColor(item.similarityScore)" :show-text="false" />
                    <span>匹配度: {{ Math.round(item.similarityScore) }}%</span>
                  </div>
                  <div class="rating-score">
                    <el-rate v-model="item.predictedRating" disabled show-score text-color="#ff9900" />
                    <span>预测评分</span>
                  </div>
                </div>
                <div class="recommendation-reason">
                  <p v-if="item.reason">{{ item.reason }}</p>
                </div>
              </div>
              <div class="resource-card-footer">
                <el-button type="info" plain size="small" @click="handleView(item)">查看详情</el-button>
                <el-button v-if="item.resourceUrl" type="primary" plain size="small" @click="handleDownload(item.id, item.resourceUrl)">下载资源</el-button>
                <el-button type="success" plain size="small" @click="handleRate(item)">评价</el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <div v-else-if="!data.loading" class="empty-state">
        <el-empty description="暂无推荐资源，请先对一些资源进行评分" />
        <el-button type="primary" @click="goToResourcePage">浏览所有资源</el-button>
      </div>
    </div>

    <!-- 算法解释卡片 -->
    <div class="card algorithm-explanation">
      <el-collapse>
        <el-collapse-item title="推荐算法说明" name="1">
          <div class="explanation-content">
            <h3>基于协同过滤的推荐系统</h3>
            <p>本推荐系统采用基于用户的协同过滤算法(User-Based Collaborative Filtering)，通过以下步骤为您推荐资源：</p>
            <ol>
              <li>收集用户对资源的评分数据，构建用户-资源评分矩阵</li>
              <li>使用余弦相似度计算用户之间的相似性</li>
              <li>找出与您相似度最高的用户群体</li>
              <li>基于相似用户的评分预测您可能喜欢的资源</li>
              <li>为您推荐预测评分最高且您尚未查看或评价的资源</li>
            </ol>
            <p>推荐列表中的匹配度表示该资源与您的兴趣匹配程度，预测评分则是基于相似用户的实际评分计算得出的预估分数。</p>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>

    <!-- 评分对话框 -->
    <el-dialog v-model="data.ratingVisible" title="资源评价" width="500px">
      <el-form :model="data.ratingForm" label-width="80px">
        <el-form-item label="资源">
          <span>{{ data.ratingForm.title }}</span>
        </el-form-item>
        <el-form-item label="评分">
          <el-rate v-model="data.ratingForm.rating" :colors="rateColors" show-score />
        </el-form-item>
        <el-form-item label="评价">
          <el-input v-model="data.ratingForm.comment" type="textarea" :rows="3" placeholder="请输入您对该资源的评价"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.ratingVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRating">提交评价</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 资源详情对话框 -->
    <el-dialog v-model="data.resourceVisible" :title="data.currentResource.title" width="800px">
      <div v-if="data.currentResource" class="resource-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="资源分类" :span="1">{{ data.currentResource.categoryName }}</el-descriptions-item>
          <el-descriptions-item label="审核状态" :span="1">
            <span :class="getStatusClass(data.currentResource.auditStatus)">
              {{ getStatusText(data.currentResource.auditStatus) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="适用症状" :span="2">{{ data.currentResource.applicableSymptoms }}</el-descriptions-item>
          <el-descriptions-item label="访问次数" :span="1">{{ data.currentResource.visitCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="下载次数" :span="1">{{ data.currentResource.downloadCount || 0 }}</el-descriptions-item>
        </el-descriptions>

        <div class="resource-content">
          <h3>资源内容：</h3>
          <div v-html="data.currentResource.content"></div>
        </div>

        <div v-if="data.currentResource.resourceUrl" class="resource-download">
          <el-button type="primary" @click="handleDownload(data.currentResource.id, data.currentResource.resourceUrl)">
            <el-icon><Download /></el-icon> 下载资源
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import request from "@/utils/request";
import { ElMessage } from "element-plus";
import { Folder, InfoFilled, View, Download } from "@element-plus/icons-vue";

const router = useRouter();

// 评分颜色
const rateColors = {
  1: '#F56C6C',  // 红色
  2: '#E6A23C',  // 橙色
  3: '#5CB87A',  // 绿色
};

const data = reactive({
  loading: false,
  userId: JSON.parse(localStorage.getItem("xm-user") || "{}").id,
  userRole: JSON.parse(localStorage.getItem("xm-user") || "{}").role,
  // 推荐资源列表
  recommendResources: [],
  // 评分对话框
  ratingVisible: false,
  ratingForm: {
    resourceId: null,
    title: '',
    rating: 5,
    comment: ''
  },
  // 资源详情对话框
  resourceVisible: false,
  currentResource: {}
});

// 获取状态类
const getStatusClass = (status) => {
  if (status === '已通过') return 'text-success';
  if (status === '待审核') return 'text-warning';
  return 'text-danger';
};

// 获取状态文本
const getStatusText = (status) => {
  if (status === '已通过') return '已审核';
  if (status === '待审核') return '待审核';
  return status;
};

// 获取相似度颜色
const getSimilarityColor = (score) => {
  if (score >= 80) return '#67C23A'; // 高匹配度 - 绿色
  if (score >= 60) return '#E6A23C'; // 中匹配度 - 橙色
  return '#909399'; // 低匹配度 - 灰色
};

// 跳转到资源页面
const goToResourcePage = () => {
  router.push('/manager/treatmentResource');
};

// 打开资源详情
const handleView = (resource) => {
  data.currentResource = resource.resource || resource;
  data.resourceVisible = true;
  
  // 增加访问次数
  incrementVisitCount(data.currentResource.id);
};

// 增加访问次数
const incrementVisitCount = (id) => {
  request.put(`/treatmentResource/incrementVisit/${id}`).then((res) => {
    if (res.code === "200") {
      console.log("访问次数已更新");
      const index = data.recommendResources.findIndex(item => 
        (item.resource ? item.resource.id : item.id) === id);
      if (index !== -1) {
        if (data.recommendResources[index].resource) {
          data.recommendResources[index].resource.visitCount = 
            (data.recommendResources[index].resource.visitCount || 0) + 1;
        } else {
          data.recommendResources[index].visitCount = 
            (data.recommendResources[index].visitCount || 0) + 1;
        }
      }
    }
  }).catch(error => {
    console.error("更新访问次数失败", error);
  });
};

// 处理下载资源
const handleDownload = (id, url) => {
  // 增加下载次数
  incrementDownloadCount(id);
  
  // 打开资源链接
  window.open(url, '_blank');
};

// 增加下载次数
const incrementDownloadCount = (id) => {
  request.put(`/treatmentResource/incrementDownload/${id}`).then((res) => {
    if (res.code === "200") {
      console.log("下载次数已更新");
      const index = data.recommendResources.findIndex(item => 
        (item.resource ? item.resource.id : item.id) === id);
      if (index !== -1) {
        if (data.recommendResources[index].resource) {
          data.recommendResources[index].resource.downloadCount = 
            (data.recommendResources[index].resource.downloadCount || 0) + 1;
        } else {
          data.recommendResources[index].downloadCount = 
            (data.recommendResources[index].downloadCount || 0) + 1;
        }
      }
    }
  }).catch(error => {
    console.error("更新下载次数失败", error);
  });
};

// 打开评分对话框
const handleRate = (item) => {
  const resource = item.resource || item;
  data.ratingVisible = true;
  data.ratingForm = {
    resourceId: resource.id,
    title: resource.title,
    rating: 5,
    comment: ''
  };
};

// 提交评分
const submitRating = () => {
  if (!data.ratingForm.rating) {
    ElMessage.warning("请先进行评分");
    return;
  }

  const ratingData = {
    resourceId: data.ratingForm.resourceId,
    rating: data.ratingForm.rating,
    comment: data.ratingForm.comment
  };

  request.post("/resourceRating", ratingData).then((res) => {
    if (res.code === "200") {
      ElMessage.success("评价提交成功");
      data.ratingVisible = false;
      
      // 重新加载推荐
      loadRecommendations();
    } else {
      ElMessage.error(res.msg || "评价提交失败");
    }
  }).catch(error => {
    console.error("评价提交失败", error);
    ElMessage.error("评价提交失败");
  });
};

// 加载推荐数据
const loadRecommendations = async () => {
  data.loading = true;
  try {
    // 从后端获取推荐资源
    const response = await request.get("/recommendation/resources", {
      params: { limit: 4 }
    });
    
    if (response.code === "200") {
      data.recommendResources = response.data || [];
      
      // 处理数据格式，适配前端展示
      data.recommendResources = data.recommendResources.map(item => {
        return {
          ...item,
          title: item.resource.title,
          categoryName: item.categoryName || item.resource.categoryName,
          applicableSymptoms: item.resource.applicableSymptoms,
          auditStatus: item.resource.auditStatus,
          visitCount: item.resource.visitCount,
          downloadCount: item.resource.downloadCount,
          resourceUrl: item.resource.resourceUrl,
          id: item.resource.id,
          content: item.resource.content
        };
      });
    } else {
      ElMessage.warning(response.msg || "获取推荐失败");
    }
  } catch (error) {
    console.error("加载推荐数据失败", error);
    ElMessage.error("加载推荐数据失败，请刷新页面重试");
  } finally {
    data.loading = false;
  }
};

onMounted(() => {
  loadRecommendations();
});
</script>

<style scoped>
.card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
  background-color: #fff;
  color: #303133;
  margin: 10px 0;
  padding: 20px;
  border-radius: 6px;
}

h2 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.sub-title {
  color: #909399;
  font-size: 14px;
  margin-top: 0;
  margin-bottom: 0;
}

.recommend-list {
  margin-top: 20px;
}

.resource-card {
  margin-bottom: 20px;
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.resource-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.resource-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.resource-card-content {
  flex: 1;
}

.resource-meta {
  margin-bottom: 15px;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
  color: #606266;
  font-size: 14px;
}

.meta-item .el-icon {
  margin-right: 5px;
  font-size: 16px;
}

.similarity-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.similarity-score {
  width: 45%;
}

.rating-score {
  width: 50%;
  display: flex;
  flex-direction: column;
}

.rating-score span {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.recommendation-reason {
  margin-top: 10px;
  font-size: 13px;
  color: #606266;
  font-style: italic;
}

.resource-card-footer {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.algorithm-explanation {
  margin-top: 20px;
}

.explanation-content {
  padding: 10px;
}

.explanation-content h3 {
  margin-top: 0;
  color: #303133;
}

.explanation-content p, .explanation-content li {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.resource-content {
  margin-top: 20px;
  border-top: 1px solid #EBEEF5;
  padding-top: 20px;
}

.resource-download {
  margin-top: 20px;
  text-align: center;
}

.text-success {
  color: #67C23A;
}

.text-warning {
  color: #E6A23C;
}

.text-danger {
  color: #F56C6C;
}
</style> 