<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="equipNo">
              <el-input v-model="queryParams.equipNo" placeholder="请输入设备编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备名称" prop="equipName">
              <el-input v-model="queryParams.equipName" placeholder="请输入设备名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <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="equipType">
              <el-select v-model="queryParams.equipType" placeholder="请选择设备类型" clearable>
                <el-option v-for="dict in equip_type" :key="dict.value" :label="dict.label" :value="Number(dict.value)" />
              </el-select>
            </el-form-item>
            <el-form-item label="设备状态" prop="equipStatus">
              <el-select v-model="queryParams.equipStatus" placeholder="请选择设备状态" clearable>
                <el-option v-for="dict in equip_status" :key="dict.value" :label="dict.label" :value="Number(dict.value)" />
              </el-select>
            </el-form-item>
            <el-form-item label="可用标识" prop="useFlag">
              <el-select v-model="queryParams.useFlag" placeholder="请选择可用标识" clearable>
                <el-option v-for="dict in use_flag" :key="dict.value" :label="dict.label" :value="Number(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:equipinfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['wcs:equipinfo:edit']">
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['wcs:equipinfo:remove']">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wcs:equipinfo: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="equipinfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="expand" width="48">
          <template #default="props">
            <div class="parameter-panel">
              <el-table :data="props.row.parameterList || []" border size="small" empty-text="暂无设备参数">
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column label="参数键" prop="paramKey" min-width="130" />
                <el-table-column label="参数名称" prop="paramName" min-width="130" />
                <el-table-column label="参数值" prop="paramValue" min-width="150" />
                <el-table-column label="参数类型" prop="paramType" width="110">
                  <template #default="scope">
                    <dict-tag :options="param_type" :value="scope.row.paramType" />
                  </template>
                </el-table-column>
                <el-table-column label="单位" prop="paramUnit" width="100" />
              </el-table>
            </div>
          </template>
        </el-table-column>
        <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" prop="equipNo" min-width="130" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[2].visible" label="设备名称" align="center" prop="equipName" min-width="160" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[3].visible" label="设备类型" align="center" prop="equipType" width="120">
          <template #default="scope">
            <dict-tag :options="equip_type" :value="scope.row.equipType" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[4].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[5].visible" label="设备状态" align="center" prop="equipStatus" width="100">
          <template #default="scope">
            <dict-tag :options="equip_status" :value="scope.row.equipStatus" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[6].visible" label="可用标识" align="center" prop="useFlag" width="100">
          <template #default="scope">
            <dict-tag :options="use_flag" :value="scope.row.useFlag" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[7].visible" label="服务地址" align="center" min-width="150" :show-overflow-tooltip="true">
          <template #default="scope">
            <span>{{ formatServer(scope.row.serverIp, scope.row.serverPort) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns[8].visible"
          label="AGV点位"
          align="center"
          prop="agvPositionCode"
          min-width="130"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          v-if="columns[9].visible"
          label="托盘编码"
          align="center"
          prop="containerCode"
          min-width="130"
          :show-overflow-tooltip="true"
        />
        <el-table-column v-if="columns[10].visible" label="更新时间" align="center" prop="updateTime" width="170">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="110" 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:equipinfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wcs:equipinfo: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="1040px" append-to-body>
      <el-form ref="equipinfoFormRef" :model="form" :rules="rules" label-width="96px">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="设备编号" prop="equipNo">
              <el-input v-model="form.equipNo" placeholder="请输入唯一设备编号" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备名称" prop="equipName">
              <el-input v-model="form.equipName" placeholder="请输入设备名称" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备类型" prop="equipType">
              <el-select v-model="form.equipType" placeholder="请选择设备类型" class="w-full">
                <el-option v-for="dict in equip_type" :key="dict.value" :label="dict.label" :value="Number(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <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="equipStatus">
              <el-select v-model="form.equipStatus" placeholder="请选择设备状态" class="w-full">
                <el-option v-for="dict in equip_status" :key="dict.value" :label="dict.label" :value="Number(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="可用标识" prop="useFlag">
              <el-radio-group v-model="form.useFlag">
                <el-radio-button v-for="dict in use_flag" :key="dict.value" :value="Number(dict.value)">{{ dict.label }}</el-radio-button>
              </el-radio-group>
            </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="服务IP" prop="serverIp">
              <el-input v-model="form.serverIp" placeholder="请输入服务IP" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务端口" prop="serverPort">
              <el-input-number v-model="form.serverPort" :min="0" :max="65535" :controls="false" class="w-full" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="托盘编码" prop="containerCode">
              <el-input v-model="form.containerCode" placeholder="请输入托盘/料箱编码" maxlength="30" />
            </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="200" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="subtable-header">
          <span>设备参数</span>
          <el-button type="primary" plain icon="Plus" @click="handleAddParameter">新增参数</el-button>
        </div>
        <el-table border :data="form.parameterList" empty-text="暂无设备参数">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="参数键" min-width="140">
            <template #default="scope">
              <el-input v-model="scope.row.paramKey" placeholder="如speed、timeout" />
            </template>
          </el-table-column>
          <el-table-column label="参数名称" min-width="140">
            <template #default="scope">
              <el-input v-model="scope.row.paramName" placeholder="请输入参数名称" />
            </template>
          </el-table-column>
          <el-table-column label="参数值" min-width="160">
            <template #default="scope">
              <el-input v-model="scope.row.paramValue" placeholder="请输入参数值" />
            </template>
          </el-table-column>
          <el-table-column label="参数类型" width="140">
            <template #default="scope">
              <el-select v-model="scope.row.paramType" filterable allow-create>
                <el-option v-for="dict in param_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="单位" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.paramUnit" placeholder="如m/s" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template #default="scope">
              <el-tooltip content="删除参数" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDeleteParameter(scope.$index)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </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="Equipinfo" lang="ts">
import { to } from 'await-to-js';
import { addEquipinfo, delEquipinfo, getEquipinfo, listEquipinfo, updateEquipinfo } from '@/api/wcs/equipinfo';
import { EquipParameterVO, EquipinfoForm, EquipinfoQuery, EquipinfoVO } from '@/api/wcs/equipinfo/types';
import { listWarehouse } from '@/api/wcs/warehouse';
import { WarehouseVO } from '@/api/wcs/warehouse/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 与 BaseEquipinfoVo / BaseEquipParameterVo @ExcelDictFormat 对齐，设备主数据和参数类型均走系统字典。
const { equip_status, use_flag, equip_type, param_type } = toRefs<any>(proxy?.useDict('equip_status', 'use_flag', 'equip_type', 'param_type'));

const equipinfoList = ref<EquipinfoVO[]>([]);
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 equipinfoFormRef = 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: '仓库', visible: true, children: [] },
  { key: 5, label: '设备状态', visible: true, children: [] },
  { key: 6, label: '可用标识', visible: true, children: [] },
  { key: 7, label: '服务地址', visible: true, children: [] },
  { key: 8, label: 'AGV点位', visible: true, children: [] },
  { key: 9, label: '托盘编码', visible: true, children: [] },
  { key: 10, label: '更新时间', visible: true, children: [] }
]);

const buildInitFormData = (): EquipinfoForm => ({
  id: undefined,
  workshopId: undefined,
  workshopLevel: 1,
  warehouseId: undefined,
  equipNo: undefined,
  equipName: undefined,
  serverIp: undefined,
  serverPort: undefined,
  equipStatus: 0,
  useFlag: 1,
  equipType: 1,
  containerCode: undefined,
  agvPositionCode: undefined,
  remark: undefined,
  parameterList: []
});

const data = reactive<PageData<EquipinfoForm, EquipinfoQuery>>({
  form: buildInitFormData(),
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workshopId: undefined,
    workshopLevel: undefined,
    warehouseId: undefined,
    equipNo: undefined,
    equipName: undefined,
    equipStatus: undefined,
    useFlag: undefined,
    equipType: undefined,
    agvPositionCode: undefined,
    params: {}
  },
  rules: {
    equipNo: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }]
  }
});

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

const getList = async () => {
  loading.value = true;
  try {
    const res = await listEquipinfo(queryParams.value);
    equipinfoList.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 = buildInitFormData();
  equipinfoFormRef.value?.resetFields();
};

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

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

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

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

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

const handleUpdate = async (row?: EquipinfoVO) => {
  reset();
  const id = row?.id || ids.value[0];
  const res = await getEquipinfo(id);
  Object.assign(form.value, res.data, {
    parameterList: res.data.parameterList || []
  });
  dialog.visible = true;
  dialog.title = '修改设备';
};

const handleAddParameter = () => {
  if (!form.value.parameterList) {
    form.value.parameterList = [];
  }
  form.value.parameterList.push({
    paramKey: undefined,
    paramName: undefined,
    paramValue: undefined,
    paramType: 'STRING',
    paramUnit: undefined
  });
};

const handleDeleteParameter = (index: number) => {
  form.value.parameterList?.splice(index, 1);
};

const lookupEquipTypeLabel = (value?: number) => {
  const dict = (equip_type.value || []).find((item: any) => Number(item.value) === Number(value));
  return dict?.label || String(value ?? '');
};

const syncParameterMasterFields = () => {
  // 子表以设备编号做业务关联，提交前统一同步主表值，避免现场改编号后参数仍指向旧设备。
  form.value.parameterList = (form.value.parameterList || []).map((item: EquipParameterVO) => ({
    ...item,
    equipCode: form.value.equipNo,
    equipName: form.value.equipName,
    equipType: lookupEquipTypeLabel(form.value.equipType)
  }));
};

const validateParameterRows = () => {
  const invalidIndex = (form.value.parameterList || []).findIndex((item) => !item.paramKey || !item.paramValue);
  if (invalidIndex >= 0) {
    proxy?.$modal.msgError(`第${invalidIndex + 1}行设备参数缺少参数键或参数值`);
    return false;
  }
  return true;
};

const submitForm = () => {
  equipinfoFormRef.value?.validate(async (valid: boolean) => {
    if (!valid || !validateParameterRows()) {
      return;
    }
    syncParameterMasterFields();
    buttonLoading.value = true;
    try {
      if (form.value.id) {
        await updateEquipinfo(form.value);
      } else {
        await addEquipinfo(form.value);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};

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

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

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}）`;
};

const formatServer = (ip?: string, port?: number) => {
  if (!ip && !port) {
    return '';
  }
  return port ? `${ip || '-'}:${port}` : ip;
};

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

<style scoped>
.parameter-panel {
  padding: 10px 18px;
  background: #fafafa;
}

.subtable-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 6px 0 10px;
  font-weight: 600;
}
</style>
