<template>
  <div class="app-container">
    <PageTitle>
      <template #buttons>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="medium"
          @click="handleAdd"
          v-hasPermi="['inventory:warehouses:add']"
        >新增</el-button>
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="medium"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['inventory:warehouses:edit']"
        >修改</el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="medium"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inventory:warehouses:remove']"
        >删除</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="medium"
          @click="handleExport"
          v-hasPermi="['inventory:warehouses:export']"
        >导出</el-button>

      </template>
    </PageTitle>

    <div class="page-container">
      <page-wrapper-search
        :model="queryParams"
        ref="queryForm"
        size="small"
        @search="handleQuery"
        @reset="resetQuery"
      >
        <el-form-item label="仓库编码" prop="warehousesCode">
          <el-input
            v-model="queryParams.warehousesCode"
            placeholder="请输入仓库编码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehousesName">
          <el-input
            v-model="queryParams.warehousesName"
            placeholder="请输入仓库名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="仓库类型" prop="warehouseType">
          <el-select
            v-model="queryParams.warehouseType"
            placeholder="请选择仓库类型"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.warehouse_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库管理员" prop="manager">
          <el-input
            v-model="queryParams.manager"
            placeholder="请输入仓库管理员"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
       <el-form-item label="应用状态" prop="isEnabled">
              <el-select
                v-model="queryParams.isEnabled"
                placeholder="请选择应用状态"
                clearable
                style="width: 100%"
                @change="handleQuery"
              >
                <el-option label="启用" value="1" />
                <el-option label="停用" value="0" />
              </el-select>
            </el-form-item>
      </page-wrapper-search>

      <div class="table-container">
        <el-table v-loading="loading" :data="warehousesList" height="100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" fixed />
          <el-table-column label="仓库编码" align="center" prop="warehousesCode" min-width="120" fixed />
          <el-table-column label="仓库名称" align="center" prop="warehousesName" min-width="150" />
          <el-table-column label="仓库类型" align="center" prop="warehouseType" min-width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.warehouse_type" :value="scope.row.warehouseType"/>
            </template>
          </el-table-column>
          <el-table-column label="仓库地点" align="center" prop="address" min-width="200" />
          <el-table-column label="仓库区域" align="center" prop="area" min-width="120" />
          <el-table-column label="仓库容量" align="center" prop="capacity" min-width="100" />
          <el-table-column label="仓库管理员" align="center" prop="manager" min-width="120" />
          <el-table-column label="联系电话" align="center" prop="contactPhone" min-width="120" />
           <el-table-column label="应用状态" align="center" prop="isEnabled" min-width="100">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.isEnabled === 1 ? 'success' : 'danger'"
                size="small"
              >
                {{ scope.row.isEnabled === 1 ? '启用' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建日期" align="center" prop="createTime" min-width="160" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['inventory:warehouses:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['inventory:warehouses:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改仓库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库编码" prop="warehousesCode">
              <el-input v-model="form.warehousesCode" placeholder="请输入仓库编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="warehousesName">
              <el-input v-model="form.warehousesName" placeholder="请输入仓库名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库类型" prop="warehouseType">
              <el-select v-model="form.warehouseType" placeholder="请选择仓库类型" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.warehouse_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="Number(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用状态" prop="isEnabled">
              <el-radio-group v-model="form.isEnabled" style="width: 100%">
                <el-radio-button label="1">启用</el-radio-button>
                <el-radio-button label="0">禁用</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库区域" prop="area">
              <el-input v-model="form.area" placeholder="请输入仓库区域" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库容量" prop="capacity">
              <el-input-number
                v-model="form.capacity"
                placeholder="请输入仓库容量"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库管理员" prop="manager">
              <el-input v-model="form.manager" placeholder="请输入仓库管理员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="仓库地点" prop="address">
              <el-input v-model="form.address" type="textarea" placeholder="请输入内容" :rows="3" />
            </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>


    <!-- 导入组件 -->
    <import-excel
      ref="import"
      title="仓库导入"
      import-url="/inventory/warehouses/import"
      template-url="inventory/warehouses/importTemplate"
      template-name="warehouses_importTemplate"
      @success="getList"
    />
  </div>
</template>

<script>
import { listWarehouses, getWarehouses, delWarehouses, addWarehouses, updateWarehouses } from "@/api/inventory/warehouses"
import ImportExcel from "@/components/ImportExcel/index"
// 仅注册组件，不修改路径（保持你原有路径）
import MaterialSelector from '@/components/materialsSeletor.vue'

export default {
  name: "Warehouses",
  components: { ImportExcel, MaterialSelector },
  dicts: ['warehouse_type', 'sys_normal_disable'],
  data() {
    // 自定义校验规则：验证手机号
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(); // 非必填，空值直接通过
      } else {
        const reg = /^1[3-9]\d{9}$/;
        if (!reg.test(value)) {
          callback(new Error('请输入正确的11位手机号码'));
        } else {
          callback();
        }
      }
    };

    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库表格数据
      warehousesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehousesCode: null,
        warehousesName: null,
        warehouseType: null,
        address: null,
        area: null,
        capacity: null,
        manager: null,
        contactPhone: null,
        isEnabled: null,
        isUsed: null,
        sortNo: null,
        createUserCode: null,
        updateUserCode: null
      },
      // 表单参数
       // 1. 先强制重置form为初始值（新增场景的默认值）
       form:{
         id: null,
         warehousesCode: null,
         warehousesName: null,
         warehouseType: null,
         address: null,
         area: null,
         capacity: null,
         manager: null,
         contactPhone: null,
         isEnabled: 1, // 新增默认启用
         isUsed: null,
         sortNo: 0,
         createTime: null,
         createUserCode: null,
         updateTime: null,
         updateUserCode: null,
         allowMaterialCodes: []
       },
      // 新增：物料选择器相关
      materialSelectorVisible: false,
      allowMaterialDisplay: '',
      // 表单校验
      rules: {
        warehousesCode: [
          { required: true, message: '仓库编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '仓库编码长度不能超过50个字符', trigger: 'blur' }
        ],
        warehousesName: [
          { required: true, message: '仓库名称不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '仓库名称长度不能超过100个字符', trigger: 'blur' }
        ],
        warehouseType: [
          { required: true, message: '仓库类型不能为空', trigger: 'change' }
        ],
        isEnabled: [
          { required: true, message: '应用状态不能为空', trigger: 'change' }
        ],
        area: [
  {
    validator: (rule, value, callback) => {
      // 空值直接通过（如果需要必填，可加required规则）
      if (!value) return callback();
      // 验证是否为数字（兼容字符串格式的数字，如"123"）
      if (isNaN(Number(value))) {
        callback(new Error('仓库区域必须为数字值'));
      } else {
        callback();
      }
    },
    trigger: 'blur'
  }
],
        // 新增：联系电话校验（手机号格式）
        contactPhone: [
          { validator: validatePhone, trigger: 'blur' }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询仓库列表 */
    getList() {
      this.loading = true
      listWarehouses(this.queryParams).then(response => {
        this.warehousesList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
      // 重置选中状态
      this.ids = []
      this.single = true
      this.multiple = true
      // 重置物料选择器
      this.materialSelectorVisible = false
      this.allowMaterialDisplay = ''
    },
   reset() {
    if (this.$refs.form) {
     this.$refs.form.resetFields(); // 恢复初始值
     this.$refs.form.clearValidate(); // 清除校验提示
     }
     this.form.id = null;
     this.form.warehousesCode = ''; // 用空字符串而非null，匹配输入框默认值
     this.form.warehousesName = '';
     this.form.warehouseType = undefined; // 让下拉框回到未选择状态
     this.form.address = '';
     this.form.area = '';
     this.form.capacity = null;
     this.form.manager = '';
     this.form.contactPhone = '';
     this.form.isEnabled = 1; // 新增默认启用
     this.form.sortNo = 0;
     this.form.allowMaterialCodes = [];
     this.allowMaterialDisplay = '';

     // 3. 重置选中状态
     this.ids = [];
     this.single = true;
     this.multiple = true;
     this.materialSelectorVisible = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        warehousesCode: null,
        warehousesName: null,
        warehouseType: null,
        address: null,
        area: null,
        capacity: null,
        manager: null,
        contactPhone: null,
        isEnabled: null,
        isUsed: null,
        sortNo: null,
        createUserCode: null,
        updateUserCode: null
      }
      // 重置选中状态
      this.ids = []
      this.single = true
      this.multiple = true
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.title = "添加仓库";
      this.open = true; // 先打开弹窗，渲染表单DOM
      // 等待DOM渲染完成后再重置
      this.$nextTick(() => {
        this.reset();
      });
    },
    handleUpdate(row) {
      // 1. 先重置，再赋值（避免旧数据残留）
      this.reset();
      const id = row.id || (this.ids.length > 0 ? this.ids[0] : null);
      if (!id) {
        this.$modal.msgWarning("请选择要修改的仓库");
        return;
      }
      getWarehouses(id).then(response => {
        // 2. 赋值前确保弹窗已打开
        this.open = true;
        this.title = "修改仓库";
        // 3. 深度赋值，避免响应式丢失
        this.form = { ...response.data };
        // 4. 处理物料编码反显（如果有）
        if (this.form.allowMaterialCodes && this.form.allowMaterialCodes.length) {
          this.formatMaterialDisplay(this.form.allowMaterialCodes);
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const request = this.form.id ? updateWarehouses(this.form) : addWarehouses(this.form)
          request.then(response => {
            this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功")
            this.open = false
            this.getList()
            // 重置选中状态
            this.ids = []
            this.single = true
            this.multiple = true
          }).catch(() => {
            this.$modal.msgError(this.form.id ? "修改失败" : "新增失败")
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // 统一转为数组格式
      const ids = row.id ? [row.id] : this.ids
      if (ids.length === 0) {
        this.$modal.msgWarning("请选择要删除的仓库")
        return
      }
      this.$modal.confirm(
        row.id ? `是否确认删除仓库编号为"${row.warehousesCode}"的数据项？` : `是否确认删除选中的${ids.length}条仓库数据项？`
      ).then(() => {
        return delWarehouses(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
        // 重置选中状态
        this.ids = []
        this.single = true
        this.multiple = true
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('inventory/warehouses/export', {
        ...this.queryParams
      }, `warehouses_${new Date().getTime()}.xlsx`)
    },
    /** 导入组件 */
    handleImport() {
      this.$refs.import.show()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  height: 100%;
}

.page-container {
  display: flex;
  flex-direction: column;
  height: calc(100% - 80px);
}

.table-container {
  flex: 1;
  margin-top: 16px;
  overflow: hidden;
}

.dialog-footer {
  text-align: center;
}
</style>
