<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="标签名称" prop="tagName">
        <el-input
          v-model="queryParams.tagName"
          placeholder="请输入标签名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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-input-->
<!--          v-model="queryParams.isPhoto"-->
<!--          placeholder="请输入是否需要拍照"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @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="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:tag:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:tag:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:tag:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:tag:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tagList" @sort-change="handleSortChange"
              @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="isPhoto" 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="tagType" sortable='custom'>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tag_type" :value="scope.row.tagType"/>
        </template>
      </el-table-column>
      <el-table-column label="拍照数量要求" align="center" prop="photoNum" sortable='custom'/>
      <el-table-column label="照片存放目录" align="center" prop="saveDir" sortable='custom'>
        <template slot-scope="scope">
          {{ getCateName(scope.row.saveDir) }}
        </template>
      </el-table-column>
      <el-table-column label="标签说明" align="center" prop="tagDesc" />
      <el-table-column label="备注" align="center" prop="remarks" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:tag:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:tag:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      hide-on-single-page
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改标签信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="标签名称" prop="tagName">
              <el-input
                v-model="form.tagName"
                placeholder="请输入标签名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否需要拍照" prop="isPhoto">
              <el-radio-group v-model="form.isPhoto" class="radio-group">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                  style="margin-right: 16px;"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 标签类型 + 拍照数量要求 -->
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="标签类型">
              <el-select
                v-model="form.tagType"
                placeholder="请选择"
                clearable
                filterable
                style="width: 100%;"
              >
                <el-option
                  v-for="dict in dict.type.tag_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拍照数量要求" prop="photoNum">
              <el-input-number
                v-model="form.photoNum"
                placeholder="请输入拍照数量要求"
                :min="0"
                :step="1"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 照片存放目录（单独一行， span=24） -->
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="照片存放目录" prop="saveDir">
              <treeselect
                v-model="form.saveDir"
                :options="cates"
                :normalizer="normalizer"
                placeholder="选择照片存放目录"
                :allow-empty="true"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 标签说明（文本域，单独一行） -->
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="标签说明" prop="tagDesc">
              <el-input
                v-model="form.tagDesc"
                type="textarea"
                placeholder="请输入内容"
                :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 备注（文本域，单独一行） -->
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="form.remarks"
                type="textarea"
                placeholder="请输入内容"
                :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 附件（单独一行） -->
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="附件" prop="files">
              <FileUpload
                v-model="form.files"
                accept=".xls,.xlsx,.doc,.docx,.pdf,.png,.jpg,.jpeg,.gif,.ppt,.pptx"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageListTag, getTag, delTag, addTag, updateTag } from "@/api/system/tag";
import FileUpload from "@/components/FileUpload";
import BranchCascaderDialog from "@/components/BranchCascaderDialog";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listCata } from "@/api/gallery/cata";

// 提取表单验证规则到单独的变量
const formRules = {
  tagName: [
    { required: true, message: "标签名称不能为空", trigger: "blur" }
  ],
  isPhoto: [
    { required: true, message: "是否需要拍照不能为空", trigger: "blur" }
  ],
  photoNum: [
    { required: true, message: "拍照数量要求不能为空", trigger: "blur" }
  ],
  saveDir: [
    { required: true, message: "照片存放目录不能为空", trigger: "change" }
  ]
};

export default {
  components: {
    FileUpload,
    Treeselect
  },
  name: "Tag",
  dicts: ['sys_yes_no','tag_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中名字
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 标签信息表格数据
      tagList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tagName: null,
        tagDesc: null,
        isPhoto: null,
        photoNum: null,
        saveDir: null,
        fileId: null,
        remarks: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: formRules,
      cates: [],
      defaultProps: {
        children: 'children',
        label: 'cataName'
      },
    };
  },
  created() {
    this.getList();
    listCata().then(res => {
      const list = res.data || [];
      this.cates = list;
    });
  },
  methods: {
    normalizer(node) {
      return {
        id: node.id,
        label: node.cataName,
        children: node.children,
      };
    },
    getCateName(saveDir) {
      const index = this.cates.findIndex(val => val.id == saveDir);
      return index > -1 ? this.cates[index].cataName : "";
    },
    /** 查询标签信息列表 */
    getList() {
      this.loading = true;
      pageListTag(this.queryParams)
        .then(response => {
          this.tagList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch(this.handleApiError);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tagName: null,
        tagDesc: null,
        isPhoto: null,
        photoNum: null,
        saveDir: null,
        fileId: null,
        remarks: null
      };
      this.resetForm("form");
    },
    // 排序
    handleSortChange(col) {
      this.$sortBy(col, this.queryParams);
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.names = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加标签信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getTag(id)
        .then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改标签信息";
        })
        .catch(this.handleApiError);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const api = this.form.id != null? updateTag : addTag;
          api(this.form)
            .then(response => {
              this.$modal.msgSuccess(this.form.id != null? "修改成功" : "新增成功");
              this.open = false;
              this.getList();
            })
            .catch();
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.id || this.names;
      this.$modal.confirm('是否确认删除标签信息为"' + names + '"的数据项？')
        .then(() => delTag(ids))
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(this.handleApiError);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/tag/export', {
        ...this.queryParams
      }, `标签信息_${new Date().getTime()}.xlsx`);
    },
    // 统一处理接口请求错误
    handleApiError(error) {
      this.loading = false;
      this.$modal.msgError("操作失败：" + error.message);
    }
  }
};
</script>

<style scoped>
/* 可以根据需要调整标签和输入框的样式 */
.el-form-item__label {
  width: 120px; /* 调整标签宽度 */
}
</style>
