<template>
  <div class="spec-container">
    <!-- 顶部操作区 -->
    <div class="operation-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="规格编号">
          <el-input
            v-model="searchForm.ps_no"
            placeholder="规格编号"
          ></el-input>
        </el-form-item>
        <el-form-item label="规格名称">
          <el-input
            v-model="searchForm.psp_name"
            placeholder="规格名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="规格类型">
          <el-select v-model="searchForm.psp_type" placeholder="规格类型">
            <el-option label="输入" value="输入"></el-option>
            <el-option label="单选" value="单选"></el-option>
            <el-option label="复选" value="复选"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属分类">
          <el-select v-model="searchForm.psp_category" placeholder="所属分类">
            <el-option label="全部" value=""></el-option>
            <el-option label="LED" value="LED"></el-option>
            <el-option label="LCD" value="LCD"></el-option>
            <el-option label="DLP" value="DLP"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" @click="resetSearch"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-button type="primary" @click="handleAdd">新建规格</el-button>
    <!-- 表格区域 -->
    <el-table :data="tableData" style="width: 100%; margin-top: 20px">
      <el-table-column prop="ps_no" label="规格编号"></el-table-column>
      <el-table-column prop="psp_name" label="规格名称"></el-table-column>
      <el-table-column prop="psp_type" label="规格值类型" width="120">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.psp_type"
            :type="
              scope.row.psp_type === '输入'
                ? 'primary'
                : scope.row.psp_type === '单选'
                ? 'success'
                : 'warning'
            "
          >
            {{ scope.row.psp_type }}
          </el-tag>
          <span v-else ></span>
        </template>
      </el-table-column>
      <el-table-column
        prop="psp_value"
        label="规格值"
        width="180"
      >
        <template slot-scope="scope">
          {{ Array.isArray(scope.row.psp_value) ? scope.row.psp_value.join(',') : scope.row.psp_value }}
        </template>
      </el-table-column>
      <el-table-column prop="psp_category" label="所属分类"></el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleView(scope.row)">查看</el-button>
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      style="margin-top: 20px; text-align: right"
    >
    </el-pagination>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="规格编号" prop="ps_no">
          <el-input v-model="form.ps_no" :disabled="dialogTitle=='编辑规格'"></el-input>
        </el-form-item>
        <el-form-item label="规格名称" prop="psp_name">
          <el-input v-model="form.psp_name"></el-input>
        </el-form-item>
        <el-form-item label="规格值类型" prop="psp_type">
          <el-select v-model="form.psp_type" style="width: 100%">
            <el-option label="输入" value="输入"></el-option>
            <el-option label="单选" value="单选"></el-option>
            <el-option label="复选" value="复选"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格值" prop="psp_value">
          <!-- <el-input
            v-model="form.psp_value"
            type="textarea"
            placeholder="多个值请用逗号分隔"
          ></el-input> -->
          <el-select
            ref="categorySelect"
            v-model="form.psp_value"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="点击enter创建选择标签"
            style="width: 100%"
            popper-class="custom-select-dropdown"
            class="hide-arrow-select"
          >
          </el-select>
        </el-form-item>
        <el-form-item label="所属分类" prop="psp_category">
          <el-select v-model="form.psp_category" style="width: 100%">
            <el-option label="全部" value="全部"></el-option>
            <el-option label="LED" value="LED"></el-option>
            <el-option label="LCD" value="LCD"></el-option>
            <el-option label="DLP" value="DLP"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加查看详情对话框 -->
    <el-dialog
      title="查看规格详情"
      :visible.sync="viewDialogVisible"
      width="500px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="规格编号">{{
          viewForm.ps_no
        }}</el-descriptions-item>
        <el-descriptions-item label="规格名称">{{
          viewForm.psp_name
        }}</el-descriptions-item>
        <el-descriptions-item label="规格类型">{{
          viewForm.psp_type
        }}</el-descriptions-item>
         <el-descriptions-item label="规格值">{{
          viewForm.psp_value
        }}</el-descriptions-item>
         <el-descriptions-item label="所属分类">{{
          viewForm.psp_category
        }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer">
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  specList,
  addSpec,
  updateSpec,
  getSpecDetail,
  deleteSpec,
} from "@/api/ProductMent/specMent";

export default {
  name: "SpecManagement",
  data() {
    return {
      searchForm: {
        ps_no: "",
        psp_name: "",
        psp_type: "",
        psp_category: "",
        pageNum: 1,
        pageSize: 10,
      },
      tableData: [],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      dialogVisible: false,
      dialogTitle: "",
      form: {
        ps_no: "",
        psp_name: "",
        psp_type: "",
        psp_value: "",
        psp_category: "",
      },
      rules: {
        ps_no: [{ required: true, message: "请输入规格编号", trigger: "blur" }],
        psp_name: [
          { required: true, message: "请输入规格名称", trigger: "blur" },
        ],
        psp_type: [
          { required: true, message: "请选择规格值类型", trigger: "change" },
        ],
      },
      viewDialogVisible: false,
      viewForm: {
        ps_no: "",
        psp_name: "",
      },
      hideDropdown:false,
    };
  },

  watch:{
    hideDropdown(newVal) {
      const dropdown = document.querySelector(".custom-select-dropdown");
      if (dropdown) {
        dropdown.style.display = newVal ? "none" : "";
      }
    },
  },

  methods: {
    /*  */
    handleSelectFocus(event) {
      this.$refs.categorySelect.blur();
    },
    /* 创建规格项 */
    createTag() {
      // Logic to create a tag
      console.log(
        "Enter key pressed, create a tag with:",
        this.form.psp_value
      );
      // Example: Add the value to a tags array
      if (this.form.psp_value.trim() !== "") {
        this.tags.push(this.form.psp_value.trim());
        this.form.psp_value = ""; // Clear the input
      }
      console.log(this.tags);
    },

    handleSearch() {
      this.pagination.currentPage = 1;
      this.loadData();
    },

    resetSearch() {
      this.searchForm = {
        ps_no: "",
        psp_name: "",
        psp_type: "",
        psp_category: "",
        pageNum: 1,
        pageSize: this.pagination.pageSize,
      };
      this.pagination.currentPage = 1;
      this.loadData();
    },

    handleAdd() {
      this.dialogTitle = "新增规格";
      this.form = {
        ps_no: "",
        psp_name: "",
        psp_type: "",
        psp_value: "",
        psp_category: "",
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = "编辑规格";
      this.form = {
        ps_id: row.ps_id,
        ps_no: row.ps_no,
        psp_name: row.psp_name,
        psp_type: row.psp_type,
        psp_value: typeof row.psp_value === 'string' 
          ? row.psp_value.split(',')
          : Array.isArray(row.psp_value)
            ? row.psp_value
            : [],
        psp_category: row.psp_category,
      };
      this.dialogVisible = true;
    },
    handleDelete(row) {
      // 删除确认对话框
      this.$confirm("此操作将永久删除该规格，是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 使用 async/await 处理异步操作
          try {
            // 显示加载中
            const loading = this.$loading({
              lock: true,
              text: "删除中...",
              spinner: "el-icon-loading",
              background: "rgba(0, 0, 0, 0.7)",
            });

            // 确保 row.ps_id 存在
            if (!row.ps_id) {
              throw new Error("规格ID不存在");
            }

            const res = await deleteSpec(row.ps_id);
            loading.close();

            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });

              // 处理删除后的页面更新逻辑
              if (
                this.tableData.length === 1 &&
                this.pagination.currentPage > 1
              ) {
                this.pagination.currentPage--;
                this.searchForm.pageNum = this.pagination.currentPage;
              }

              if (
                this.tableData.length === 1 &&
                this.pagination.total <=
                  this.pagination.pageSize * this.pagination.currentPage
              ) {
                this.pagination.currentPage = Math.max(
                  1,
                  this.pagination.currentPage - 1
                );
                this.searchForm.pageNum = this.pagination.currentPage;
              }

              // 重新加载数据
              this.loadData();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          } catch (error) {
            console.error("删除失败:", error);
            this.$message.error("删除失败，请稍后重试");
            // 确保加载动画被关闭
            this.$loading().close();
          }
        })
        .catch((err) => {
          // 只有用户点击取消按钮时才显示取消删除的提示
          if (err === "cancel" || err.toString().includes("cancel")) {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          }
        });
    },
    handleView(row) {
      this.viewForm = {
        ps_no: row.ps_no,
        psp_name: row.psp_name,
        psp_type:row.psp_type,
        psp_value:row.psp_value?.join(','),
        psp_category:row.psp_category,
      };
      this.viewDialogVisible = true;
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.searchForm.pageSize = val;
      this.loadData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.searchForm.pageNum = val;
      this.loadData();
    },
    /* 新增,编辑提交 */
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const api = this.dialogTitle === "新增规格" ? addSpec : updateSpec;
          const message = this.dialogTitle === "新增规格" ? "添加成功" : "更新成功";

          // 创建一个新对象，处理 psp_value 的转换
          const submitData = {
            ...this.form,
            // 将数组转换为逗号分隔的字符串
            psp_value: Array.isArray(this.form.psp_value) 
              ? this.form.psp_value.join(',') 
              : this.form.psp_value
          };

          api(submitData)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success(message);
                this.dialogVisible = false;
                this.loadData();
              } else {
                this.$message.error(res.message || "操作失败");
              }
            })
            .catch(() => {
              this.$message.error("操作失败");
            });
        }
      });
    },
    /* 初始化列表 */
    loadData() {
      const params = {
        ...this.searchForm,
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
      };

      specList(params)
        .then((res) => {
          if (res.code === 200) {
            // 添加类型检查，确保字符串处理的安全性
            this.tableData = (res.rows || []).map(item => ({
              ...item,
              psp_value: typeof item.psp_value === 'string'
                ? item.psp_value.split(',')
                : Array.isArray(item.psp_value)
                  ? item.psp_value
                  : []
            }));
            this.pagination.total = res.total || 0;
          } else {
            this.$message.error(res.message || "获取数据失败");
          }
        })
        .catch((error) => {
          console.error("获取数据失败:", error);
          this.$message.error("获取数据失败");
        });
    },
  },
  created() {
    this.loadData();
  },
};
</script>

<style>
.spec-container {
  padding: 20px;
}
.operation-area {
  margin-bottom: 20px;
}
.search-form {
  margin-left: 16px;
  display: inline-block;
}

::v-deep .el-input__inner:focus {
  border: 1px solid #409EFF !important;
}

::v-deep .el-textarea__inner:focus {
  border: 1px solid #409EFF !important;
}
.custom-select-dropdown {
  display: none !important;
}
.el-select-dropdown.custom-select-dropdown {
  display: none !important;
}

/* 或者使用新的深度选择器语法 */
::v-deep .hide-arrow-select  .el-input .el-input__suffix {
  display: none !important;
}
.hide-arrow-select .el-input .el-input__suffix {
 display: none !important;
}
</style>
