<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.keyword" prefix-icon="Search" style="width: 240px; margin-right: 10px; margin-bottom: 3px" placeholder="请输入资源名称或适用症状"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin-right: 10px" @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px;">
      <el-table :data="data.tableData" stripe>
        <el-table-column label="资源标题" prop="title"></el-table-column>
        <el-table-column label="分类" prop="categoryName"></el-table-column>
        <el-table-column label="适用症状" prop="applicableSymptoms" show-overflow-tooltip></el-table-column>
        <el-table-column label="审核状态" width="100">
          <template #default="scope">
            <span v-if="scope.row.auditStatus === '已通过'" class="text-success">已审核</span>
            <span v-else class="text-warning">待审核</span>
          </template>
        </el-table-column>
        <el-table-column label="访问次数" prop="visitCount" width="100"></el-table-column>
        <el-table-column label="下载次数" prop="downloadCount" width="100"></el-table-column>
        <el-table-column label="操作" align="center" width="280" fixed="right">
          <template #default="scope">
            <!-- 只能编辑自己创建且未审核的资源 -->
            <el-button v-if="scope.row.auditStatus !== '已通过'" type="primary" plain size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="warning" plain size="small" @click="handleView(scope.row)">查看</el-button>
            <!-- 只能删除自己创建且未审核的资源 -->
            <el-button v-if="scope.row.auditStatus !== '已通过'" type="danger" plain size="small" @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination 
        @current-change="load" 
        background 
        layout="total, prev, pager, next" 
        :page-size="10" 
        v-model:current-page="data.pageNum" 
        :total="data.total"/>
    </div>

    <el-dialog :title="data.formTitle" v-model="data.formVisible" width="60%" :close-on-click-modal="false" destroy-on-close @closed="handleBeforeDestroy">
      <el-form :model="data.form" label-width="120px" style="padding: 20px 30px">
        <el-form-item label="资源标题" prop="title" required>
          <el-input v-model="data.form.title" placeholder="请输入资源标题"></el-input>
        </el-form-item>
        <el-form-item label="资源分类" prop="categoryId" required>
          <el-select v-model="data.form.categoryId" placeholder="请选择资源分类" style="width: 100%">
            <el-option v-for="item in data.categories" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资源内容" prop="content" required>
          <div style="border: 1px solid #DCDFE6; border-radius: 4px;">
            <div v-if="!data.isView" style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="editorConfig"
                mode="default"
              />
              <Editor
                style="height: 300px; overflow-y: hidden;"
                v-model="data.form.content"
                :defaultConfig="editorConfig"
                mode="default"
                @onCreated="editorRef = $event"
              />
            </div>
            <div v-else v-html="data.form.content" class="view-html-content"></div>
          </div>
        </el-form-item>
        <el-form-item label="资源链接" prop="resourceUrl">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-success="handleFileUploadSuccess"
            :on-error="handleFileUploadError"
            :headers="uploadHeaders"
            :disabled="data.isView"
          >
            <el-button type="primary" :disabled="data.isView">上传资源文件</el-button>
            <template #tip>
              <div class="el-upload__tip">支持各种类型文件，如PDF、Word、视频等</div>
            </template>
          </el-upload>
          <div v-if="data.form.resourceUrl">
            <el-link 
              v-if="data.isView" 
              type="primary" 
              @click="handleDownload(data.form.id, data.form.resourceUrl)"
            >
              下载资源
            </el-link>
            <div v-else class="resource-url">
              <span>当前文件: {{ getFileName(data.form.resourceUrl) }}</span>
              <el-button type="danger" link @click="removeFile">删除</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="适用症状" prop="applicableSymptoms" required>
          <el-input v-model="data.form.applicableSymptoms" placeholder="请输入适用症状，多个症状用逗号分隔"></el-input>
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus" v-if="data.isView">
          <span v-if="data.form.auditStatus === '已通过'" class="text-success">已审核</span>
          <span v-else class="text-warning">待审核</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save" v-if="!data.isView">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, onMounted, shallowRef, ref } from "vue";
import request from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';

// 定义上传URL，避免在模板中直接使用import.meta.env
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload';
const uploadHeaders = {
  token: JSON.parse(localStorage.getItem('xm-user') || '{}').token || ''
};

// 获取当前用户信息
const userInfo = JSON.parse(localStorage.getItem('xm-user') || '{}');
const userId = userInfo.id || 0;

// 编辑器实例，必须用shallowRef
const editorRef = shallowRef();

// 配置编辑器，添加图片上传功能
const editorConfig = {
  placeholder: '请输入资源内容...',
  autoFocus: false,
  MENU_CONF: {
    uploadImage: {
      server: uploadUrl,
      fieldName: 'file',
      maxFileSize: 5 * 1024 * 1024, // 5MB
      maxNumberOfFiles: 10,
      allowedFileTypes: ['image/*'],
      // 自定义上传参数
      meta: {},
      // 自定义增加 http 请求头
      headers: uploadHeaders,
      // 上传之前触发
      onBeforeUpload(file) {
        return file;
      },
      // 上传进度的回调函数
      onProgress(progress) {
        console.log('progress', progress);
      },
      // 单个文件上传成功的回调函数
      onSuccess(file, res) {
        console.log('onSuccess', file, res);
      },
      // 单个文件上传失败的回调函数
      onFailed(file, res) {
        console.log('onFailed', file, res);
        ElMessage.error('图片上传失败');
      },
      // 上传错误的回调函数
      onError(file, err, res) {
        console.log('onError', file, err, res);
        ElMessage.error('图片上传错误');
      },
      // 自定义插入图片
      customInsert(res, insertFn) {
        // res 即服务端的返回结果
        if (res.code === '200') {
          // 从后端响应中获取图片 URL
          const url = res.data || res;
          // 插入图片到编辑器
          insertFn(url);
        } else {
          ElMessage.error('图片插入失败');
        }
      }
    }
  }
};

const data = reactive({
  keyword: "",
  tableData: [],
  total: 0,
  pageNum: 1,
  pageSize: 10,
  formVisible: false,
  formTitle: "",
  isView: false,
  form: {},
  categories: [],
  search: {}
});

// 加载数据
const load = async () => {
  try {
    data.loading = true;
    // 构建查询参数
    const params = {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      title: data.keyword
    };
    // 调用后端API获取我的资源列表
    const res = await request.get('/treatmentResource/myResources', { params });
    if (res.code === "200") {
      data.tableData = res.data.list || [];
      data.total = res.data.total;
    } else {
      ElMessage.error(res.msg || '加载资源列表失败');
    }
  } catch (e) {
    console.error('加载资源列表失败', e);
    ElMessage.error('加载资源列表失败');
  } finally {
    data.loading = false;
  }
  
  // 加载分类
  request.get("/resourceCategory").then((res) => {
    if (res.code === "200") {
      data.categories = res.data;
    }
  });
};

// 重置查询条件
const reset = () => {
  data.keyword = "";
  load();
};

// 打开新增对话框
const handleAdd = () => {
  data.formVisible = true;
  data.formTitle = "新增心理资源";
  data.form = {};
  data.isView = false;
};

// 打开编辑对话框
const handleEdit = (row) => {
  data.formVisible = true;
  data.formTitle = "编辑心理资源";
  data.form = JSON.parse(JSON.stringify(row));
  data.isView = false;
};

// 打开查看对话框
const handleView = (row) => {
  data.formVisible = true;
  data.formTitle = "查看心理资源";
  data.form = JSON.parse(JSON.stringify(row));
  data.isView = true;
  
  // 查看资源时，访问次数+1
  incrementVisitCount(row.id);
};

// 增加访问次数
const incrementVisitCount = (id) => {
  // 修改API路径
  request.put(`/treatmentResource/incrementVisit/${id}`).then((res) => {
    if (res.code === "200") {
      // 静默处理，不需要提示用户
      console.log("访问次数已更新");
      // 刷新当前资源的访问次数（可选）
      const index = data.tableData.findIndex(item => item.id === id);
      if (index !== -1) {
        data.tableData[index].visitCount = (data.tableData[index].visitCount || 0) + 1;
      }
    }
  }).catch(error => {
    console.error("更新访问次数失败", error);
    // 即使失败也不影响用户体验，所以不显示错误提示
  });
};

// 增加下载次数
const incrementDownloadCount = (id) => {
  // 修改API路径
  request.put(`/treatmentResource/incrementDownload/${id}`).then((res) => {
    if (res.code === "200") {
      // 静默处理，不需要提示用户
      console.log("下载次数已更新");
      // 刷新当前资源的下载次数（可选）
      const index = data.tableData.findIndex(item => item.id === id);
      if (index !== -1) {
        data.tableData[index].downloadCount = (data.tableData[index].downloadCount || 0) + 1;
      }
    }
  }).catch(error => {
    console.error("更新下载次数失败", error);
    // 即使失败也不影响用户体验，所以不显示错误提示
  });
};

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

// 删除
const del = (id) => {
  ElMessageBox.confirm('确定要删除该资源吗？', '删除提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete("/treatmentResource/" + id).then((res) => {
      if (res.code === "200") {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(() => {});
};

// 保存
const save = () => {
  if (!data.form.title || !data.form.categoryId || !data.form.content || !data.form.applicableSymptoms) {
    ElMessage.warning("请填写必填项");
    return;
  }

  let method = data.form.id ? "put" : "post";

  request[method]("/treatmentResource", data.form).then((res) => {
    if (res.code === "200") {
      ElMessage.success("保存成功");
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 组件销毁时，也及时销毁编辑器
const handleBeforeDestroy = () => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
};

// 处理文件上传成功后的回调
const handleFileUploadSuccess = (response, file) => {
  if (response.code === '200') {
    data.form.resourceUrl = response.data;
    ElMessage.success('文件上传成功');
  } else {
    ElMessage.error('文件上传失败');
  }
};

// 处理文件上传错误后的回调
const handleFileUploadError = (error) => {
  ElMessage.error('文件上传错误');
};

// 获取文件名
const getFileName = (url) => {
  if (!url) return '';
  const parts = url.split('/');
  return parts[parts.length - 1];
};

// 移除文件
const removeFile = () => {
  data.form.resourceUrl = '';
  ElMessage.success('文件删除成功');
};

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

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

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

.text-warning {
  color: #E6A23C;
}

.text-danger {
  color: #F56C6C;
}

.view-html-content {
  padding: 10px;
  min-height: 100px;
  max-height: 300px;
  overflow-y: auto;
}

:deep(.w-e-text-container) {
  min-height: 300px;
}

.resource-url {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style> 