<template>
  <div>
    <div class="button-group">
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="handleAddTag"
        :disabled="disabled"
        class="add-button"
      >
        新增标签
      </el-button>
      <el-button
        type="danger"
        icon="el-icon-delete"
        @click="handleDeleteTag"
        :disabled="!multiple || disabled"
        class="delete-button"
      >
        删除标签
      </el-button>
    </div>

    <el-table
      :data="tags"
      border
      :disabled="disabled"
      style="width: 100%; margin-top: 16px;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标签名称" align="center" prop="tagName" sortable="custom" />
      <el-table-column label="标签说明" align="center" prop="tagDesc" sortable="custom" />
      <el-table-column label="是否需要拍照" align="center" sortable="custom">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isPhoto"/>
        </template>
      </el-table-column>
      <el-table-column label="拍照数量要求" align="center" prop="photoNum" sortable="custom" />
      <el-table-column label="照片存放目录" align="center" prop="saveDir" sortable="custom" />
      <el-table-column label="附件" align="center" sortable="custom">
        <template slot-scope="scope">
          <template v-if="scope.row.files && scope.row.files.length > 0">
            <div v-for="(file, index) in scope.row.files" :key="index">
              <el-link :href="`${baseUrl}${file.attachFileUrl}`" :underline="false" target="_blank">
                <span class="el-icon-document"> {{ file.oldName || '未知文件名' }} </span>
              </el-link>
            </div>
          </template>
          <template v-else>
            无附件
          </template>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" sortable="custom" />
    </el-table>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="60%"
      append-to-body
    >
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
        <el-form-item label="标签名称" prop="tagName">
          <el-input
            v-model="queryParams.tagName"
            placeholder="请输入标签名称"
            clearable
            @keyup.enter.native="fetchAvailableTags"
          />
        </el-form-item>
        <el-form-item label="是否需要拍照" prop="isPhoto">
          <el-select v-model="queryParams.isPhoto" placeholder="是否需要拍照" clearable>
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchAvailableTags">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="availableTags"
        border
        style="width: 100%; margin-top: 16px;"
        @selection-change="handleDialogSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="标签名称" align="center" prop="tagName" sortable="custom" />
        <el-table-column label="标签说明" align="center" prop="tagDesc" sortable="custom" />
        <el-table-column label="是否需要拍照" align="center" sortable="custom">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isPhoto"/>
          </template>
        </el-table-column>
        <el-table-column label="拍照数量要求" align="center" prop="photoNum" sortable="custom" />
        <el-table-column label="照片存放目录" align="center" prop="saveDir" sortable="custom" />
        <el-table-column label="附件ID" align="center" sortable="custom">
          <template slot-scope="scope">
            <template v-if="scope.row.files && scope.row.files.length > 0">
              <div v-for="(file, index) in scope.row.files" :key="index">
                <el-link :href="`${baseUrl}${file.attachFileUrl}`" :underline="false" target="_blank">
                  <span class="el-icon-document"> {{ file.oldName || '未知文件名' }} </span>
                </el-link>
              </div>
            </template>
            <template v-else>
              无附件
            </template>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remarks" sortable="custom" />
      </el-table>
      <pagination
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="fetchAvailableTags"
        style="margin-top: 16px;"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAdd">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addTag, removeTag } from "@/api/task/template";
import { listTag, pageListTag } from "@/api/system/tag";
import FileUpload from "@/components/FileUpload";
import Pagination from "@/components/Pagination";

export default {
  components: {
    FileUpload,
    Pagination
  },
  name: "TagTable",
  dicts: ['sys_yes_no'],
  props: {
    tags: {
      type: Array,
      default: () => []
    },
    disabled: {
      type: Boolean,
      default: false
    },
    templateId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      availableTags: [],
      dialogVisible: false,
      selectedTags: [],
      selectedRows: [],
      multiple: false,
      dialogTitle: "",
      dialogSelectedTags: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tagName: '',
        isPhoto: ''
      },
      total: 0
    };
  },
  created() {
    this.fetchAvailableTags();
  },
  methods: {
    async fetchAvailableTags() {
      try {
        const response = await pageListTag(this.queryParams);
        this.availableTags = response.rows;
        this.total = response.total;
      } catch (error) {
        this.$message.error("获取标签列表失败");
      }
    },
    handleAddTag() {
      this.dialogTitle = "选择标签";
      this.dialogVisible = true;
      this.resetQuery();
      this.fetchAvailableTags();
    },
    handleDialogSelectionChange(selection) {
      this.dialogSelectedTags = selection;
    },
    async confirmAdd() {
      if (this.dialogSelectedTags.length === 0) {
        return this.$message.warning("请选择要添加的标签");
      }

      // 过滤出不存在的新标签
      const newTags = this.dialogSelectedTags.filter(newTag => {
        return!this.tags.some(existingTag => {
          return existingTag.tagName === newTag.tagName && existingTag.tagDesc === newTag.tagDesc;
        });
      });

      if (newTags.length === 0) {
        this.$message.warning("所选标签已存在");
        this.dialogVisible = false;
        this.dialogSelectedTags = [];
        return;
      }

      const tagIds = newTags.map(tag => tag.id);

      try {
        await addTag({
          id: this.templateId,
          tagIds: tagIds
        });

        this.$emit("update:tags", [...this.tags, ...newTags]);
        this.$message.success(`成功添加${newTags.length}个标签`);

        this.dialogVisible = false;
        this.dialogSelectedTags = [];
      } catch (error) {
        this.$message.error("标签添加失败");
      }
    },
    handleSelectionChange(rows) {
      this.selectedRows = rows;
      this.multiple = rows.length > 0;
    },
    async handleDeleteTag() {
      if (this.selectedRows.length === 0) {
        return this.$message.warning("请选择要删除的标签");
      }

      const tagIds = this.selectedRows.map(row => row.id);

      try {
        await removeTag({
          templateId: this.templateId,
          tagIds: tagIds
        });

        this.$emit("update:tags", this.tags.filter(tag =>!tagIds.includes(tag.id)));
        this.$message.success(`成功删除${this.selectedRows.length}个标签`);
      } catch (error) {
        this.$message.error("标签删除失败");
      }
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        tagName: '',
        isPhoto: ''
      };
      this.fetchAvailableTags();
    }
  }
};
</script>

<style scoped>
.button-group {
  display: flex;
  gap: 12px;
  align-items: center;
}

.add-button {
  min-width: 100px;
}

.delete-button {
  min-width: 100px;
}

.el-table {
  margin-top: 16px;
}

.el-table__header {
  background-color: #f8f9fa;
}

.el-table__row:nth-child(even) {
  background-color: #f8f9fa;
}

/* 调整遮罩层样式 */
.el-dialog__wrapper {
  z-index: 2000; /* 调整遮罩层的层级 */
}

.el-dialog {
  z-index: 2001; /* 调整对话框的层级，确保在遮罩层之上 */
}

.dialog-search {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 0 16px;
}
</style>
