<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库" clearable filterable>
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.warehouseId"
                  :label="formatWarehouseLabel(item)"
                  :value="Number(item.warehouseId)"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="机台" prop="machineId">
              <el-input-number v-model="queryParams.machineId" :min="0" :controls="false" placeholder="请输入机台" />
            </el-form-item>
            <el-form-item label="库位编码" prop="locationCode">
              <el-input v-model="queryParams.locationCode" placeholder="请输入库位编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="料箱编码" prop="containerCode">
              <el-input v-model="queryParams.containerCode" placeholder="请输入料箱编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="激活标记" prop="activeFlag">
              <el-select v-model="queryParams.activeFlag" placeholder="请选择激活标记" clearable>
                <el-option v-for="dict in active_flag" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
            <el-form-item label="库位状态" prop="locationStatus">
              <el-select v-model="queryParams.locationStatus" placeholder="请选择库位状态" clearable>
                <el-option v-for="dict in location_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wcs:location:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['wcs:location:edit']">
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['wcs:location:remove']">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wcs:location:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" :columns="columns" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="locationList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column v-if="columns[0].visible" type="index" label="序号" width="60" align="center" />
        <el-table-column v-if="columns[1].visible" label="仓库" align="center" min-width="150" :show-overflow-tooltip="true">
          <template #default="scope">
            <span>{{ scope.row.warehouseName || getWarehouseName(scope.row.warehouseId) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[2].visible" label="机台" align="center" prop="machineId" width="80" />
        <el-table-column v-if="columns[3].visible" label="库位编码" align="center" prop="locationCode" min-width="120" />
        <el-table-column v-if="columns[4].visible" label="AGV点位" align="center" prop="agvPositionCode" min-width="120" />
        <el-table-column v-if="columns[5].visible" label="库位占用" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getLocationState(scope.row).tag">{{ getLocationState(scope.row).label }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns[6].visible"
          label="料箱编码"
          align="center"
          prop="containerCode"
          min-width="140"
          :show-overflow-tooltip="true"
        />
        <el-table-column v-if="columns[7].visible" label="数量" align="center" prop="locCount" width="80" />
        <el-table-column v-if="columns[8].visible" label="激活标记" align="center" prop="activeFlag" width="100">
          <template #default="scope">
            <dict-tag :options="active_flag" :value="scope.row.activeFlag" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[9].visible" label="库位状态" align="center" prop="locationStatus" width="100">
          <template #default="scope">
            <dict-tag :options="location_status" :value="scope.row.locationStatus" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[10].visible" label="RFID设备Key" align="center" prop="equipKey" min-width="120" />
        <el-table-column v-if="columns[11].visible" label="创建人" align="center" prop="createBy" width="100" />
        <el-table-column v-if="columns[12].visible" label="创建时间" align="center" prop="createdTime" width="170">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[13].visible" label="更新人" align="center" prop="updatedBy" width="100" />
        <el-table-column v-if="columns[14].visible" label="更新时间" align="center" prop="updatedTime" width="170">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="150" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['wcs:location:edit']"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.containerCode" content="解绑料箱" placement="top">
              <el-button link type="primary" icon="Unlock" @click="handleUnbindContainer(scope.row)" v-hasPermi="['wcs:location:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wcs:location:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

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

    <el-dialog :title="dialog.title" v-model="dialog.visible" width="760px" append-to-body>
      <el-form ref="locationFormRef" :model="form" :rules="rules" label-width="104px">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="请选择仓库" clearable filterable class="w-full">
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.warehouseId"
                  :label="formatWarehouseLabel(item)"
                  :value="Number(item.warehouseId)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车间编号" prop="workshopId">
              <el-input-number v-model="form.workshopId" :controls="false" class="w-full" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车间层数" prop="workshopLevel">
              <el-input-number v-model="form.workshopLevel" :min="0" :controls="false" class="w-full" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="机台" prop="machineId">
              <el-input-number v-model="form.machineId" :min="0" :controls="false" class="w-full" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库位编码" prop="locationCode">
              <el-input v-model="form.locationCode" placeholder="请输入库位编码" maxlength="64" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="AGV点位" prop="agvPositionCode">
              <el-input v-model="form.agvPositionCode" placeholder="请输入AGV点位编码" maxlength="64" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="料箱编码" prop="containerCode">
              <el-input v-model="form.containerCode" placeholder="为空表示未绑定料箱" maxlength="64" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数量" prop="locCount">
              <el-input-number v-model="form.locCount" :min="0" :controls="false" class="w-full" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="激活标记" prop="activeFlag">
              <el-radio-group v-model="form.activeFlag">
                <el-radio-button v-for="dict in active_flag" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库位状态" prop="locationStatus">
              <el-radio-group v-model="form.locationStatus">
                <el-radio-button v-for="dict in location_status" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="RFID设备Key" prop="equipKey">
              <el-input v-model="form.equipKey" placeholder="请输入RFID设备Key" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入异常库位、临时锁定等现场说明" maxlength="255" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Location" lang="ts">
import { to } from 'await-to-js';
import { addLocation, delLocation, getLocation, listLocation, updateLocation } from '@/api/wcs/location';
import { LocationForm, LocationQuery, LocationVO } from '@/api/wcs/location/types';
import { listWarehouse } from '@/api/wcs/warehouse';
import { WarehouseVO } from '@/api/wcs/warehouse/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { active_flag, location_status } = toRefs<any>(proxy?.useDict('active_flag', 'location_status'));

const locationList = ref<LocationVO[]>([]);
const warehouseOptions = ref<WarehouseVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const locationFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const columns = ref<FieldOption[]>([
  { key: 0, label: '序号', visible: true, children: [] },
  { key: 1, label: '仓库', visible: true, children: [] },
  { key: 2, label: '机台', visible: true, children: [] },
  { key: 3, label: '库位编码', visible: true, children: [] },
  { key: 4, label: 'AGV点位', visible: true, children: [] },
  { key: 5, label: '库位占用', visible: true, children: [] },
  { key: 6, label: '料箱编码', visible: true, children: [] },
  { key: 7, label: '数量', visible: true, children: [] },
  { key: 8, label: '激活标记', visible: true, children: [] },
  { key: 9, label: '库位状态', visible: true, children: [] },
  { key: 10, label: 'RFID设备Key', visible: true, children: [] },
  { key: 11, label: '创建人', visible: true, children: [] },
  { key: 12, label: '创建时间', visible: true, children: [] },
  { key: 13, label: '更新人', visible: true, children: [] },
  { key: 14, label: '更新时间', visible: true, children: [] }
]);

const initFormData: LocationForm = {
  locationId: undefined,
  workshopId: undefined,
  workshopLevel: 1,
  warehouseId: undefined,
  machineId: undefined,
  locationCode: undefined,
  agvPositionCode: undefined,
  containerCode: undefined,
  locCount: undefined,
  activeFlag: 1,
  locationStatus: 0,
  remark: undefined,
  equipKey: undefined
};

const data = reactive<PageData<LocationForm, LocationQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workshopId: undefined,
    workshopLevel: undefined,
    warehouseId: undefined,
    machineId: undefined,
    locationCode: undefined,
    containerCode: undefined,
    activeFlag: undefined,
    locationStatus: undefined,
    equipKey: undefined,
    params: {}
  },
  rules: {
    locationCode: [{ required: true, message: '库位编码不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const getList = async () => {
  loading.value = true;
  try {
    const res = await listLocation(queryParams.value);
    locationList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

const getWarehouseOptions = async () => {
  const res = await listWarehouse({ pageNum: 1, pageSize: 1000 });
  warehouseOptions.value = res.rows || [];
};

const reset = () => {
  form.value = { ...initFormData };
  locationFormRef.value?.resetFields();
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: LocationVO[]) => {
  ids.value = selection.map((item) => item.locationId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增库位';
};

const handleUpdate = async (row?: LocationVO) => {
  reset();
  const locationId = row?.locationId || ids.value[0];
  const res = await getLocation(locationId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改库位';
};

const submitForm = () => {
  locationFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) {
      return;
    }
    buttonLoading.value = true;
    try {
      if (form.value.locationId) {
        await updateLocation(form.value);
      } else {
        await addLocation(form.value);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};

const handleUnbindContainer = async (row: LocationVO) => {
  const [err] = await to(proxy?.$modal.confirm('是否确认解绑库位"' + row.locationCode + '"上的料箱？') as any);
  if (err) {
    return;
  }
  // 解绑只清空料箱字段，其余业务字段原样提交，避免误改库位状态和AGV点位映射。
  const payload: LocationForm = {
    locationId: row.locationId,
    workshopId: row.workshopId,
    workshopLevel: row.workshopLevel,
    warehouseId: row.warehouseId,
    machineId: row.machineId,
    locationCode: row.locationCode,
    agvPositionCode: row.agvPositionCode,
    containerCode: '',
    locCount: row.locCount,
    activeFlag: row.activeFlag,
    locationStatus: row.locationStatus,
    remark: row.remark,
    equipKey: row.equipKey
  };
  await updateLocation(payload);
  proxy?.$modal.msgSuccess('解绑成功');
  await getList();
};

const handleDelete = async (row?: LocationVO) => {
  const locationIds = row?.locationId || ids.value;
  const [err] = await to(proxy?.$modal.confirm('是否确认删除库位编号为"' + locationIds + '"的数据项？') as any);
  if (!err) {
    await delLocation(locationIds);
    proxy?.$modal.msgSuccess('删除成功');
    await getList();
  }
};

const handleExport = () => {
  proxy?.download('wcs/location/export', { ...queryParams.value }, `location_${new Date().getTime()}.xlsx`);
};

const getLocationState = (row: LocationVO) => {
  if (Number(row.locationStatus) === 1) {
    return { label: '锁定', tag: 'warning' as const };
  }
  return row.containerCode ? { label: '占用', tag: 'danger' as const } : { label: '空闲', tag: 'success' as const };
};

const getWarehouseName = (warehouseId?: number) => {
  return warehouseOptions.value.find((item) => Number(item.warehouseId) === Number(warehouseId))?.warehouseName || warehouseId || '';
};

const formatWarehouseLabel = (item: WarehouseVO) => {
  return `${item.warehouseName || '未命名仓库'}（${item.warehouseId}）`;
};

onMounted(async () => {
  await getWarehouseOptions();
  await getList();
});
</script>
