<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>
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="medium"
          @click="handleImport"
          v-hasPermi="['inventory:warehouses:add']"
        >导入</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%"
          >
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </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" width="120" fixed />
          <el-table-column label="仓库名称" align="center" prop="warehousesName" width="150" />
          <el-table-column label="仓库类型" align="center" prop="warehouseType" 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" width="200" />
          <el-table-column label="仓库区域" align="center" prop="area" width="120" />
          <el-table-column label="仓库容量" align="center" prop="capacity" width="100" />
          <el-table-column label="仓库管理员" align="center" prop="manager" width="120" />
          <el-table-column label="联系电话" align="center" prop="contactPhone" width="120" />
          <el-table-column label="应用状态" align="center" prop="isEnabled" width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.isEnabled"/>
            </template>
          </el-table-column>
          <el-table-column label="排序" align="center" prop="sortNo" width="80" />
          <el-table-column label="创建日期" align="center" prop="createTime" 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="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="12">
            <el-form-item label="排序" prop="sortNo">
              <el-input-number 
                v-model="form.sortNo" 
                placeholder="请输入排序" 
                :min="0" 
                :step="1" 
                style="width: 100%"
              />
            </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-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="允许存放物料" prop="allowMaterialCodes">
              <el-input
                v-model="allowMaterialDisplay"
                placeholder="请选择允许存放的物料"
                readonly
                @click="openMaterialSelector"
                style="margin-bottom: 10px"
              />
            </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>

    <!-- 物料选择器弹窗 -->
    <el-dialog
      title="选择允许存放的物料"
      :visible.sync="materialSelectorVisible"
      width="90%"
      height="80vh"
    >
      <MaterialSelector
        ref="materialSelector"
        :selectedMaterialCodes="form.allowMaterialCodes || []"
        :multiple="true"
        @selection-change="handleMaterialSelect"
      />
      <div slot="footer">
        <el-button @click="materialSelectorVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmMaterialSelect">确定</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
      },
      // 表单参数
      form: {},
      // 新增：物料选择器相关
      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' }
        ],
        sortNo: [
          { required: true, message: '排序不能为空', trigger: 'blur' },
          { type: 'number', message: '排序必须为数字值', trigger: 'blur' }
        ],
        area: [
          { type: 'number', message: '仓库区域必须为数字值', trigger: 'blur' }
        ],
        // 新增：联系电话校验（手机号格式）
        contactPhone: [
          { validator: validatePhone, trigger: 'blur' }
        ],
        // 可选：添加物料编码的非必填校验
        allowMaterialCodes: [
          { type: 'array', message: '允许存放物料必须为数组格式', trigger: 'change' }
        ]
      }
    }
  },
  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() {
      this.form = {
        id: null,
        warehousesCode: null,
        warehousesName: null,
        warehouseType: null,
        address: null,
        area: null,
        capacity: null,
        manager: null,
        contactPhone: null,
        isEnabled: 1,
        isUsed: 0,
        sortNo: 0,
        createTime: null,
        createUserCode: null,
        updateTime: null,
        updateUserCode: null,
        // 新增：允许存放物料编码
        allowMaterialCodes: []
      }
      // 重置物料显示文本
      this.allowMaterialDisplay = ''
      // 延迟重置表单验证状态
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields()
        }
      })
    },
    /** 搜索按钮操作 */
    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.reset()
      this.open = true
      this.title = "添加仓库"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      // 修复：ids是数组，取第一个元素
      const id = row.id || (this.ids.length > 0 ? this.ids[0] : null)
      if (!id) {
        this.$modal.msgWarning("请选择要修改的仓库")
        return
      }
      getWarehouses(id).then(response => {
        this.form = response.data
        // 新增：反显物料编码并格式化显示文本
        if (this.form.allowMaterialCodes && this.form.allowMaterialCodes.length) {
          this.formatMaterialDisplay(this.form.allowMaterialCodes)
        }
        this.open = true
        this.title = "修改仓库"
      })
    },
    /** 提交按钮 */
    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()
    },
    // 新增：打开物料选择器
    openMaterialSelector() {
      this.materialSelectorVisible = true
    },
    // 新增：物料选择变化回调
    handleMaterialSelect(data) {
      this.form.allowMaterialCodes = data.materialCodes
    },
    // 新增：确认选择物料
    confirmMaterialSelect() {
      const selection = this.$refs.materialSelector.getSelection()
      this.form.allowMaterialCodes = selection.materialCodes
      // 格式化显示文本（名称+编码）
      this.formatMaterialDisplay(selection.materialCodes, selection.names)
      this.materialSelectorVisible = false
    },
    // 新增：格式化物料显示文本
    formatMaterialDisplay(codes, names) {
      if (!codes || !codes.length) {
        this.allowMaterialDisplay = ''
        return
      }
      // 有名称则显示“[名称] 编码”，无名称则仅显示编码
      if (names && names.length) {
        this.allowMaterialDisplay = names.map((name, idx) => `[${name}] ${codes[idx]}`).join('、')
      } else {
        this.allowMaterialDisplay = codes.join('、')
      }
    }
  }
}
</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>