<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="60px">
      <el-form-item label="库位编码" prop="warehouseCode">
        <el-input
          v-model="queryParams.warehouseCode"
          placeholder="请输入库位编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库位名称" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入库位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="启用状态" prop="isEnabled">
        <el-select v-model="queryParams.isEnabled" placeholder="请选择启用状态" clearable>
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </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"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 替换树形表格为卡片布局 -->
    <el-row :gutter="20" v-loading="loading">
      <!-- 1. 新增卡片动态class区分启用/禁用状态 -->
      <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in warehouseList" :key="item.warehouseId" class="mb20">
        <el-card 
          shadow="hover" 
          class="warehouse-card"
          :class="{'enabled-card': item.isEnabled == 1, 'disabled-card': item.isEnabled == 0}"
        >
          <div class="card-content">
            <!-- 2. 合并名称和编码为 名称#编码 形式 -->
            <div class="card-item">
              <span class="label">库位信息：</span>
              <span class="value">{{ item.warehouseName }}#{{ item.warehouseCode }}</span>
            </div>
            <!-- <div class="card-item">
              <span class="label">排序号：</span>
              <span class="value">{{ item.sortNo }}</span>
            </div> -->
            <div class="card-item">
              <span class="label">备注：</span>
              <!-- 3. 备注添加多行省略样式类 -->
              <span class="value remark-text">{{ item.remark || '无' }}</span>
            </div>
            <div class="card-actions">
              <!-- 4. 新增启用/禁用快捷开关 -->
              <el-switch
                v-model="item.isEnabled"
                :active-value="1"
                :inactive-value="0"
                @change="handleSwitchChange(item)"
                :disabled="switchLoading"
              />
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(item)">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(item)">删除</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改库位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级节点" prop="parentId" v-show="false">
          <el-input v-model="form.parentId" disabled />
        </el-form-item>
        <el-form-item label="库位编码" prop="warehouseCode">
          <el-input v-model="form.warehouseCode" placeholder="请输入库位编码" />
        </el-form-item>
        <el-form-item label="库位名称" prop="warehouseName">
          <el-input v-model="form.warehouseName" placeholder="请输入库位名称" />
        </el-form-item>
        <el-form-item label="排序号" prop="sortNo">
          <el-input v-model="form.sortNo" placeholder="请输入排序号" />
        </el-form-item>
        <el-form-item label="启用状态" prop="isEnabled">
          <el-select v-model="form.isEnabled" placeholder="请选择启用状态">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWarehouse, getWarehouse, delWarehouse, addWarehouse, updateWarehouse } from "@/api/wms/warehouse";

export default {
  name: "Warehouse",
  components: {},
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 开关loading（新增）
      switchLoading: false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 库位表格数据（一维数组，非树形）
      warehouseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 重新渲染表格状态（树结构相关，保留但无实际作用）
      refreshTable: true,
      // 查询参数
      queryParams: {
        parentId: undefined, // 固定查询parentId=0的数据
        warehouseCode: undefined,
        warehouseName: undefined,
        warehouseType: undefined,
        sortNo: undefined,
        isEnabled: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验（移除warehouseType必填规则）
      rules: {
        warehouseCode: [
          { required: true, message: "库位/库区编码不能为空", trigger: "blur" }
        ],
        warehouseName: [
          { required: true, message: "库位/库区名称不能为空", trigger: "blur" }
        ],
        isEnabled: [
          { required: true, message: "启用状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询库位列表（移除树形处理） */
    getList() {
      this.loading = true;
      listWarehouse(this.queryParams).then(response => {
        // 直接使用一维数组，按sortNo排序（无需递归）
        const list = response.data.sort((a, b) => a.sortNo - b.sortNo);
        this.warehouseList = list;
        this.loading = false;
      });
    },

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

    // 表单重置
    reset() {
      this.form = {
        warehouseId: null,
        parentId: undefined, // 固定parentId为0
        warehouseCode: null,
        warehouseName: null,
        warehouseType: 1,
        sortNo: null,
        isEnabled: 1, // 默认启用
        delFlag: null,
        remark: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 重置后仍保留parentId=0
      this.queryParams.parentId = undefined;
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 固定parentId为0，无需树形选择器
      this.form.parentId = undefined;
      this.open = true;
      this.title = "添加库位/库区";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      // 固定parentId为0
      this.form.parentId = 0;
      getWarehouse(row.warehouseId).then(response => {
        this.loading = false;
        // 覆盖parentId为0
        this.form = { ...response.data, parentId: undefined };
        this.open = true;
        this.title = "修改库位/库区";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          // 强制设置parentId为0
          const submitData = { ...this.form, parentId: undefined };
          if (this.form.warehouseId != null) {
            updateWarehouse(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addWarehouse(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除库位/库区编号为"' + row.warehouseId + '"的数据项？').then(() => {
        this.loading = true;
        return delWarehouse(row.warehouseId);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },

    /** 新增：开关切换启用/禁用状态 */
    handleSwitchChange(item) {
      this.switchLoading = true;
      // 构造更新参数（仅更新状态）
      const updateData = {
        ...item,
        isEnabled: item.isEnabled
      };
      updateWarehouse(updateData).then(() => {
        this.$modal.msgSuccess(`已${item.isEnabled === 1 ? '启用' : '禁用'}该库位`);
        this.getList(); // 刷新列表确保数据一致
      }).catch(() => {
        // 切换失败时恢复原状态
        item.isEnabled = item.isEnabled === 1 ? 0 : 1;
        this.$modal.msgError("状态切换失败");
      }).finally(() => {
        this.switchLoading = false;
      });
    }
  }
};
</script>

<style scoped>
/* 卡片样式优化 */
.warehouse-card {
  height: 100%;
  transition: border-color 0.3s;
}

/* 1. 启用卡片绿色边框 */
.enabled-card {
  border-color: #67c23a !important;
}

/* 禁用卡片红色边框 */
.disabled-card {
  border-color: #f56c6c !important;
}

.card-content {
  padding: 10px 0;
}

.card-item {
  margin-bottom: 8px;
  display: flex;
  align-items: flex-start; /* 适配多行文本对齐 */
}

.label {
  color: #606266;
  width: 80px;
  flex-shrink: 0;
}

.value {
  color: #303133;
  flex: 1;
}

/* 2. 备注文本多行省略样式 */
.remark-text {
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 最多显示2行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5; /* 行高适配 */
  max-height: 3em; /* 2行 * 1.5行高 = 3em */
}

.card-actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;
  align-items: center; /* 开关和按钮垂直居中 */
}

.mb20 {
  margin-bottom: 20px;
}
</style>