<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="仓库编码" prop="warehouseCode">
        <el-input
          v-model="queryParams.warehouseCode"
          placeholder="请输入仓库编码"
          clearable
          style="width: 220px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库名称" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入仓库名称"
          clearable
          style="width: 220px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库类型" prop="warehouseType">
        <el-select v-model="queryParams.warehouseType" placeholder="请选择仓库类型" clearable style="width: 220px">
          <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="belongOrgName">
        <el-input
          v-model="queryParams.belongOrgName"
          placeholder="请输入所属单位名称"
          clearable
          style="width: 220px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单位类型" prop="belongOrgType">
        <el-select v-model="queryParams.belongOrgType" placeholder="请选择单位类型" clearable style="width: 220px">
          <el-option
            v-for="dict in dict.type.team_org_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 220px">
          <el-option
            v-for="dict in dict.type.warehouse_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </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"
          v-hasPermi="['resource:warehouse:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate()"
          v-hasPermi="['resource:warehouse:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['resource:warehouse:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="warehouseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="仓库编码" align="center" prop="warehouseCode" :show-overflow-tooltip="true" min-width="120" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="仓库类型" align="center" prop="warehouseType" :show-overflow-tooltip="true" width="120">
        <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="belongOrgName" :show-overflow-tooltip="true" width="160" />
      <el-table-column label="单位类型" align="center" width="140">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.team_org_type" :value="scope.row.belongOrgType" />
        </template>
      </el-table-column>
      <el-table-column label="地址" align="center" prop="address" :show-overflow-tooltip="true" width="180" />
      <el-table-column label="负责人" align="center" prop="manager" width="100" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" width="120" />
      <el-table-column label="容量" align="center" prop="capacity" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.capacity">{{ scope.row.capacity }} ㎡</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.warehouse_status" :value="String(scope.row.status || '0')" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['resource:warehouse:edit']"
          >编辑</el-button>
          <el-dropdown>
            <span class="el-dropdown-link">
              状态<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-if="scope.row.status === '0'"
                v-hasPermi="['resource:warehouse:edit']"
                @click.native="handleDisable(scope.row)"
              >停用</el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.status === '1'"
                v-hasPermi="['resource:warehouse:edit']"
                @click.native="handleEnable(scope.row)"
              >启用</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['resource:warehouse:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改仓库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库编码" prop="warehouseCode">
              <el-input v-model="form.warehouseCode" placeholder="请输入仓库编码" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="warehouseName">
              <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库类型" prop="warehouseType">
              <el-select v-model="form.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-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.warehouse_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属单位" prop="belongOrgName">
              <el-input v-model="form.belongOrgName" placeholder="请输入所属单位名称" maxlength="128" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位类型" prop="belongOrgType">
              <el-select v-model="form.belongOrgType" placeholder="请选择所属单位类型" clearable style="width: 100%">
                <el-option
                  v-for="dict in dict.type.team_org_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <div class="address-with-location">
                <el-input
                  v-model="form.address"
                  type="textarea"
                  placeholder="请输入详细地址或使用地图选择"
                  maxlength="500"
                  :rows="2"
                  readonly
                />
                <div class="location-actions">
                  <span
                    v-if="form.longitude != null && form.latitude != null"
                    class="location-status"
                  >
                    已选择位置
                  </span>
                  <span
                    v-else
                    class="location-status is-empty"
                  >
                    未选择坐标
                  </span>
                  <el-button
                    size="mini"
                    type="primary"
                    plain
                    icon="el-icon-location"
                    @click="openLocationPicker"
                  >
                    选择位置
                  </el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="容量" prop="capacity">
              <el-input-number
                v-model="form.capacity"
                :min="0"
                :precision="2"
                placeholder="请输入容量"
                style="width: 100%"
              />
              <span style="margin-left: 5px; color: #909399;">平方米</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="manager">
              <el-input v-model="form.manager" placeholder="请输入负责人" maxlength="64" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" maxlength="500" :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>
    <LocationPickerDialog
      :visible.sync="locationPickerVisible"
      :initial-location="{
        longitude: locationPickerTarget ? locationPickerTarget.longitude : undefined,
        latitude: locationPickerTarget ? locationPickerTarget.latitude : undefined,
        locationName: locationPickerTarget ? (locationPickerTarget.belongOrgName || locationPickerTarget.address || '') : ''
      }"
      @confirm="handleLocationConfirm"
    />
  </div>
</template>

<script>
import { listWarehouse, getWarehouse, addWarehouse, updateWarehouse, delWarehouse, enableWarehouse, disableWarehouse } from '@/api/resource/warehouse'
import LocationPickerDialog from '@/components/location/LocationPickerDialog.vue'

export default {
  name: 'ResourceWarehouse',
  components: {
    LocationPickerDialog
  },
  dicts: ['warehouse_status', 'warehouse_type', 'team_org_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      warehouseCodes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库表格数据
      warehouseList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      locationPickerVisible: false,
      locationPickerTarget: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseCode: undefined,
        warehouseName: undefined,
        warehouseType: undefined,
        belongOrgName: undefined,
        belongOrgType: undefined,
        status: undefined
      },
      // 表单校验
      rules: {
        warehouseCode: [
          { required: true, message: '仓库编码不能为空', trigger: 'blur' },
          { max: 50, message: '仓库编码长度不能超过50个字符', trigger: 'blur' }
        ],
        warehouseName: [
          { required: true, message: '仓库名称不能为空', trigger: 'blur' },
          { max: 100, message: '仓库名称长度不能超过100个字符', trigger: 'blur' }
        ],
        warehouseType: [
          { max: 32, message: '仓库类型长度不能超过32个字符', trigger: 'blur' }
        ],
        belongOrgName: [
          { max: 128, message: '所属单位名称长度不能超过128个字符', trigger: 'blur' }
        ],
        belongOrgType: [
          { max: 32, message: '所属单位类型长度不能超过32个字符', trigger: 'blur' }
        ],
        address: [
          { max: 500, message: '详细地址长度不能超过500个字符', trigger: 'blur' }
        ],
        manager: [
          { max: 64, message: '负责人长度不能超过64个字符', trigger: 'blur' }
        ],
        contactPhone: [
          { max: 20, message: '联系电话长度不能超过20个字符', trigger: 'blur' }
        ],
        remark: [
          { max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询仓库列表 */
    getList() {
      this.loading = true
      const params = { ...this.queryParams }
      this.addDateRange(params, this.dateRange, 'Time')
      listWarehouse(params).then(response => {
        const rows = response.rows || []
        // 确保状态值为字符串类型，以便字典标签正确显示
        this.warehouseList = rows.map(item => ({
          ...item,
          status: item.status != null ? String(item.status) : '0'
        }))
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 打开位置选择器 */
    openLocationPicker() {
      this.locationPickerTarget = {
        longitude: this.form.longitude,
        latitude: this.form.latitude,
        belongOrgName: this.form.belongOrgName,
        address: this.form.address
      }
      this.locationPickerVisible = true
    },
    /** 位置选择器确认 */
    handleLocationConfirm({ lng, lat, address }) {
      this.form.longitude = lng
      this.form.latitude = lat
      if (!this.form.address && address) {
        this.form.address = address
      }
      this.locationPickerVisible = false
      this.locationPickerTarget = null
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        warehouseCode: undefined,
        warehouseName: undefined,
        warehouseType: undefined,
        belongOrgName: undefined,
        belongOrgType: undefined,
        address: undefined,
        longitude: undefined,
        latitude: undefined,
        manager: undefined,
        contactPhone: undefined,
        capacity: undefined,
        status: '0',
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.warehouseCodes = selection.map(item => item.warehouseCode)
      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[0]
      getWarehouse(id).then(response => {
        const data = response.data || {}
        this.form = {
          id: data.id,
          warehouseCode: data.warehouseCode,
          warehouseName: data.warehouseName,
          warehouseType: data.warehouseType,
          belongOrgName: data.belongOrgName,
          belongOrgType: data.belongOrgType,
          address: data.address,
          longitude: data.longitude,
          latitude: data.latitude,
          manager: data.manager,
          contactPhone: data.contactPhone,
          capacity: data.capacity,
          status: data.status || '0',
          remark: data.remark
        }
        this.open = true
        this.title = '编辑仓库'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateWarehouse(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addWarehouse(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // const ids = row.id || this.ids
      let ids = this.ids;
      let curNames = [];
      if (row) {
        ids = row.id || this.ids;
        curNames.push(row.warehouseCode)
      } else if (this.warehouseCodes.length > 0) {
        curNames.push(...this.warehouseCodes)
      }
      const quotedNames = curNames.map(item => `“${item}”`);
      const resNames = quotedNames.join('、');
      this.$modal.confirm('是否确认删除仓库编码为' + resNames + '的数据项？').then(() => {
        return delWarehouse(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 启用仓库 */
    handleEnable(row) {
      this.$modal.confirm('是否确认启用该仓库？').then(() => {
        return enableWarehouse(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('启用成功')
      }).catch(() => {})
    },
    /** 停用仓库 */
    handleDisable(row) {
      this.$modal.confirm('停用后该仓库将不可用，是否确认停用？').then(() => {
        return disableWarehouse(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('停用成功')
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  margin: 0 6px;
}

.address-with-location {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.location-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.location-status.is-empty {
  color: #F56C6C;
}
</style>