<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="success"
          plain
          icon="el-icon-upload"
          size="medium"
          @click="handleImport"
          v-hasPermi="['inventory:warehouses:add']"
        >导入</el-button>
      </template>
    </PageTitle>

       <div class="page-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <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
            class="w20"
          >
            <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
            class="w20"
          >
            <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>


      <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="allowMaterialCodes" min-width="150">
            <template slot-scope="scope">
              <el-tooltip
                :content="scope.row.allowMaterialCodes && scope.row.allowMaterialCodes.length ? scope.row.allowMaterialCodes.join(',') : '无'"
                placement="top"
                effect="light"
              >
                <div class="material-tags">
                  <el-tag
                    v-for="(code, index) in (scope.row.allowMaterialCodes && scope.row.allowMaterialCodes.length ? scope.row.allowMaterialCodes.slice(0, 3) : [])"
                    :key="index"
                    type="info"
                    size="small"
                    style="margin-right: 5px;"
                  >
                    {{ code }}
                  </el-tag>
                  <el-tag
                    v-if="scope.row.allowMaterialCodes && scope.row.allowMaterialCodes.length > 3"
                    type="info"
                    size="small"
                    style="background: #f0f9eb; border-color: #c2e7b0;"
                  >
                    +{{ scope.row.allowMaterialCodes.length - 3 }}
                  </el-tag>
                </div>
              </el-tooltip>
            </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="请输入仓库编码"
                :readonly="!!form.id"  <!-- 修改时编码不可改 -->
              />
            </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-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="允许存放物料" prop="allowMaterialCodes">
              <el-input
                v-model="allowMaterialDisplay"
                placeholder="请选择允许存放的物料（可选）"
                readonly
                @click="openMaterialSelector"
                :suffix-icon="''"
              >
                <template v-if="allowMaterialDisplay" #suffix>
                  <i
                    class="el-icon-circle-close el-input__icon"
                    style="cursor: pointer;"
                    @click.stop="clearMaterialSelection"
                  ></i>
                </template>
              </el-input>
            </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="1000px"
      append-to-body
      :close-on-click-modal="false"
    >
      <MaterialSelector
        ref="materialSelector"
        @selection-change="handleMaterialSelectionChange"
        :selected-material-codes="form.allowMaterialCodes"
        :multiple="true"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="materialSelectorVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmMaterialSelection">确认选择</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: {
        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: '', // 物料选择器显示文本
      tempSelectedMaterials: [], // 临时选中的物料编码
      // 表单校验
      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) => {
              if (!value) return callback();
              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 || 0
        this.loading = false
      }).catch(error => {
        console.error('查询仓库列表失败:', error)
        this.warehousesList = []
        this.total = 0
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
      // 重置物料选择器
      this.materialSelectorVisible = false
      this.allowMaterialDisplay = ''
      this.tempSelectedMaterials = []
    },

    // 表单重置
    reset() {
      if (this.$refs.form) {
        this.$refs.form.resetFields()
        this.$refs.form.clearValidate()
      }
      // 重置表单为初始状态
      this.form = {
        id: null,
        warehousesCode: '',
        warehousesName: '',
        warehouseType: undefined,
        address: '',
        area: '',
        capacity: null,
        manager: '',
        contactPhone: '',
        isEnabled: 1,
        isUsed: null,
        sortNo: 0,
        createTime: null,
        createUserCode: null,
        updateTime: null,
        updateUserCode: null,
        allowMaterialCodes: []
      }
      // 重置选中状态
      this.ids = []
      this.single = true
      this.multiple = true
      // 重置物料选择相关
      this.allowMaterialDisplay = ''
      this.tempSelectedMaterials = []
    },

    /** 搜索按钮操作 */
    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()
      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.allowMaterialDisplay = this.form.allowMaterialCodes.join(', ')
          this.tempSelectedMaterials = [...this.form.allowMaterialCodes]
        }
        this.open = true
        this.title = "修改仓库"
      }).catch(error => {
        console.error('获取仓库详情失败:', error)
        this.$modal.msgError('获取仓库详情失败，请重试')
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 格式化物料编码（去重、过滤空值）
          this.form.allowMaterialCodes = this.tempSelectedMaterials
            .filter(code => code && code.trim())
            .filter((code, index, self) => self.indexOf(code) === index)

          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.reset() // 提交后重置表单
          }).catch(error => {
            console.error('提交仓库数据失败:', error)
            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.tempSelectedMaterials = [...this.form.allowMaterialCodes]
      this.materialSelectorVisible = true
      // 清空子组件选中状态（如果有该方法）
      this.$nextTick(() => {
        if (this.$refs.materialSelector && this.$refs.materialSelector.clearSelection) {
          this.$refs.materialSelector.clearSelection()
          // 回显已选物料
          if (this.tempSelectedMaterials.length) {
            this.$refs.materialSelector.setSelection(this.tempSelectedMaterials)
          }
        }
      })
    },

    // 物料选择变化回调
    handleMaterialSelectionChange(selectedData) {
      // 兼容不同格式的返回值
      this.tempSelectedMaterials = (selectedData.materialIds || selectedData || [])
        .filter(code => code && code.trim())
        .map(code => code.trim())
        .filter((code, index, self) => self.indexOf(code) === index)
    },

    // 确认物料选择
    confirmMaterialSelection() {
      if (!this.tempSelectedMaterials.length) {
        this.allowMaterialDisplay = ''
      } else {
        this.allowMaterialDisplay = this.tempSelectedMaterials.join(', ')
      }
      this.form.allowMaterialCodes = [...this.tempSelectedMaterials]
      this.materialSelectorVisible = false
    },

    // 清空物料选择
    clearMaterialSelection() {
      this.allowMaterialDisplay = ''
      this.tempSelectedMaterials = []
      this.form.allowMaterialCodes = []
    }
  }
}
</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;
}

.material-tags {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

/deep/ .el-tooltip__popper {
  max-width: 300px;
  white-space: normal;
}
</style>