<template>
  <el-dialog v-model="visible" title="主柜配置" width="800px">
    <el-table :data="cabinetList" v-loading="loading" border>
      <el-table-column prop="cabinetId" label="柜体ID" width="100" />
      <el-table-column prop="cabinetName" label="柜体名称" />
      <el-table-column label="柜体类型" width="120">
        <template #default="{ row }">
          <el-tag :type="row.cabinetType === 0 ? 'success' : 'warning'">
            {{ row.cabinetType === 0 ? '主柜' : '副柜' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleConfig(row)">配置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
      @size-change="onSizeChange" @current-change="onCurrentChange" />
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { SmartCabinetDTO } from '@/api/cabinet/smart-cabinet';
import { ElMessage } from 'element-plus';
import { getSmartCabinetList } from '@/api/cabinet/smart-cabinet';
import { updateSmartCabinet } from '@/api/cabinet/smart-cabinet';

const props = defineProps<{
  modelValue: boolean;
  cabinetId: number;
}>();

const emit = defineEmits(['update:modelValue', 'refresh']);

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
});
const cabinetList = ref<SmartCabinetDTO[]>([]);
const loading = ref(false);
const currentCabinetId = ref<number>();
const pagination = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0
});

const loadMainCabinets = async () => {
  try {
    loading.value = true;
    const { data } = await getSmartCabinetList({
      cabinetType: 0,
      pageSize: pagination.value.pageSize,
      pageNum: pagination.value.currentPage
    });
    cabinetList.value = data.rows;
    pagination.value.total = data.total;
  } finally {
    loading.value = false;
  }
};

const onSizeChange = (val: number) => {
  pagination.value.pageSize = val;
  loadMainCabinets();
};

const onCurrentChange = (val: number) => {
  pagination.value.currentPage = val;
  loadMainCabinets();
};

watch(() => props.modelValue, (val) => {
  visible.value = val;
});

watch(() => props.cabinetId, (newVal) => {
  if (newVal) {
    currentCabinetId.value = newVal;
    loadMainCabinets();
  }
});

const handleConfig = async (row: SmartCabinetDTO) => {
  try {
    await updateSmartCabinet(currentCabinetId.value, {
      cabinetId: currentCabinetId.value,
      mainCabinet: row.cabinetId
    });
    ElMessage.success('配置成功');
    emit('update:modelValue', false);
    emit('refresh');
  } catch (error) {
    console.error('配置失败', error);
  }
};
</script>