<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable style="width: 170px">
          <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
     
      <el-form-item label="年代" prop="age">
        <el-input
          v-model="queryParams.age"
          placeholder="请输入年代"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="热门标识" prop="isHot">
        <el-input
          v-model="queryParams.isHot"
          placeholder="请输入热门标识"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
        >导出</el-button>
      </el-col>-->
    </el-row>
    <br>

    <el-table v-loading="loading" :data="relicList">
      <!-- <el-table-column label="藏品id" align="center" prop="id" /> -->
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="分类" align="center">
        <template #default="scope">
          <span>{{ scope.row.categoryInfo && scope.row.categoryInfo.name ? scope.row.categoryInfo.name : '—' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="封面" align="center" prop="coverImageUrl">
        <template #default="scope">
          <el-image
            v-if="scope.row.coverImageUrl"
            :src="getFilePrefix + scope.row.coverImageUrl"
            :preview-src-list="[getFilePrefix + scope.row.coverImageUrl]"
            preview-teleported
            fit="cover"
            style="width: 80px; height: 80px; cursor: zoom-in"
          />
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column label="年代" align="center" prop="age" />
      <el-table-column label="材质" align="center" prop="material" />
      <!-- <el-table-column label="出土信息" align="center" prop="excavationInfo" /> -->
      <!-- <el-table-column label="文物故事" align="center" prop="story" /> -->
      <!-- <el-table-column label="3D/360°图地址" align="center" prop="modelUrl" /> -->
      <el-table-column label="热门标识" align="center" prop="isHot">
        <template #default="scope">
          <el-tag v-if="scope.row.isHot === 1" type="danger">热门</el-tag>
          <el-tag v-else type="info">普通</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="success">显示</el-tag>
          <el-tag v-else type="warning">隐藏</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建者id" align="center" prop="creator" />
      <el-table-column label="更新者id" align="center" prop="updater" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="350">
        <template #default="scope">
          
          <el-button
            link
            type="primary"
            v-if="scope.row.isHot === 0"
            @click="toggleHot(scope.row, 1)"
            icon="Sunny"
          >设为热门</el-button>
          <el-button
            link
            type="primary"
            v-if="scope.row.isHot === 1"
            @click="toggleHot(scope.row, 0)"
            icon="CloseBold"
          >取消热门</el-button>
          <el-button
            link
            type="primary"
            v-if="scope.row.status === 1"
            @click="toggleStatus(scope.row, 0)"
            icon="Hide"
          >隐藏</el-button>
          <el-button
            link
            type="primary"
            v-if="scope.row.status === 0"
            @click="toggleStatus(scope.row, 1)"
            icon="View"
          >显示</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <br>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryParams.pageSize"
        layout="->, total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <!-- 添加或修改藏品对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="relicRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 100%">
                <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="封面" prop="coverImageUrl">
              <el-upload
                action="/api/files/upload"
                :headers="headers"
                name="file"
                :data="{filePath: 'relicCover'}"
                list-type="picture-card"
                :file-list="coverFileList"
                :limit="1"
                :on-success="handleCoverSuccess"
                :on-remove="handleCoverRemove"
                :on-exceed="handleCoverExceed"
                :before-upload="beforeCoverUpload"
                accept="image/*"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
              <div class="upload-tips">仅支持一张图片，大小≤10MB</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年代" prop="age">
              <el-input v-model="form.age" placeholder="请输入年代" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="材质" prop="material">
              <el-input v-model="form.material" placeholder="请输入材质" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出土信息" prop="excavationInfo">
              <el-input v-model="form.excavationInfo" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="3D/360°图地址" prop="modelUrl">
              <el-input v-model="form.modelUrl" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="文物故事" prop="story">
              <Editor
                :value="form.story || ''"
                @updateValue="updateStory"
                filePath="relicStoryImg"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Relic">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { listRelic, getRelic, delRelic, addRelic, updateRelic } from "@/api/relic";
import { listAllItemCategory } from "@/api/itemCategory";
import Editor from "@/components/Editor.vue";

const { proxy } = getCurrentInstance();

const relicList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");

const isAdd = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    categoryId: null,
    coverImageUrl: null,
    age: null,
    material: null,
    excavationInfo: null,
    story: null,
    modelUrl: null,
    isHot: null,
    status: null,
    creator: null,
    updater: null
  },
  rules: {
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "分类ID不能为空", trigger: "blur" }
    ],
    coverImageUrl: [
      { required: true, message: "封面不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
const coverFileList = ref([]);
const categoryOptions = ref([]);
const headers = {};

// 上传成功后
function handleUploadSuccess(response, uploadFile, uploadFiles) {
  form.value.coverImageUrl = response
  proxy.$message.success('上传成功')
}

/*** 富文本回调 */
function updateStory(value) {
  form.value.story = value;
}

/** 查询藏品列表 */
function getList() {
  loading.value = true;
  listRelic(queryParams.value).then(response => {
    relicList.value = response.list;
    total.value = response.total;
    loading.value = false;
  });
}

function loadCategories() {
  listAllItemCategory({}).then(res => {
    const arr = res || [];
    categoryOptions.value = Array.isArray(arr) ? arr : [];
  });
}

// 改变每页条数大小
function handleSizeChange(val) {
  queryParams.value.pageSize = val;
  getList();
}

// 换页
function handleCurrentChange(val) {
  queryParams.value.pageNum = val;
  getList();
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    categoryId: null,
    coverImageUrl: null,
    age: null,
    material: null,
    excavationInfo: null,
    story: null,
    modelUrl: null,
    isHot: null,
    status: null,
    createTime: null,
    creator: null,
    updateTime: null,
    updater: null
  };
  const relicRef = proxy.$refs["relicRef"]
  if (relicRef) {
    relicRef.resetFields();
  }
  coverFileList.value = [];
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  const queryRef = proxy.$refs["queryRef"]
  if (queryRef) {
    queryRef.resetFields();
  }
  handleQuery();
}


/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加藏品";
  isAdd.value = true;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getRelic(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改藏品";
    isAdd.value = false;
    coverFileList.value = form.value.coverImageUrl ? [{ name: '封面', url: proxy.getFilePrefix + form.value.coverImageUrl }] : [];
  });
}

/** 表单提交按钮 */
function submitForm() {
  proxy.$refs["relicRef"].validate(valid => {
    if (valid) {
      if (isAdd.value) {  // 添加
        addRelic(form.value).then(response => {
          proxy.$message({
            message: response.msg,
            type: 'success'
          })
          open.value = false;
          getList();
        });
      } else {  // 更新
        updateRelic(form.value).then(response => {
          proxy.$message({
            message: response.msg,
            type: 'success'
          })
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$confirm('是否确认删除藏品编号为"' + row.id + '"的数据项？').then(function() {
    return delRelic(row.id);
  }).then(response => {
    getList();
    proxy.$message({
      message: response.msg,
      type: 'success'
    })
  }).catch(() => {});
}

/** 导出按钮操作 */
// function handleExport() {
//   proxy.download('system/relic/export', {
//     ...queryParams.value
//   }, `relic_${new Date().getTime()}.xlsx`)
// }

function handleCoverSuccess(res, file, fileList) {
  form.value.coverImageUrl = res;
  coverFileList.value = [{ name: file.name, url: proxy.getFilePrefix + form.value.coverImageUrl }];
  const relicRef = proxy.$refs["relicRef"];
  if (relicRef) {
    relicRef.validateField('coverImageUrl');
  }
}

function handleCoverRemove() {
  form.value.coverImageUrl = null;
  coverFileList.value = [];
}

function handleCoverExceed(files, fileList) {
  proxy.$message({
    message: '只允许上传一张图片',
    type: 'warning'
  });
}

function beforeCoverUpload(file) {
  const ok = file.size / 1024 / 1024 <= 10;
  if (!ok) {
    proxy.$message({
      message: '图片大小不能超过10MB',
      type: 'error'
    });
  }
  return ok;
}

function toggleHot(row, nextVal) {
  const text = nextVal === 1 ? '是否要把该藏品设置为热门？' : '是否要取消该藏品的热门？';
  proxy.$confirm(text).then(function() {
    return updateRelic({ id: row.id, isHot: nextVal });
  }).then(response => {
    getList();
    proxy.$message({
      message: response.msg,
      type: 'success'
    })
  }).catch(() => {});
}

function toggleStatus(row, nextVal) {
  const text = nextVal === 1 ? '是否要显示该藏品？' : '是否要隐藏该藏品？';
  proxy.$confirm(text).then(function() {
    return updateRelic({ id: row.id, status: nextVal });
  }).then(response => {
    getList();
    proxy.$message({
      message: response.msg,
      type: 'success'
    })
  }).catch(() => {});
}


getList();
loadCategories();
</script>
<style scoped>
.upload-tips {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}
.el-upload--picture-card {
  width: 120px;
  height: 120px;
}
.el-upload-list__item {
  width: 120px !important;
  height: 120px !important;
}
</style>
