<template>
  <el-dialog v-model="visible" title="商店配置" width="800px">
    <el-table :data="shopList" v-loading="loading" border>
      <el-table-column prop="shopId" label="商店ID" width="100" />
      <el-table-column prop="shopName" label="商店名称" />
      <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 { ref, watch } from 'vue';
import { getShopList } from '@/api/shop/shop';
import { ShopDTO } from '@/api/shop/shop';
import { ElMessage } from 'element-plus';
import { updateSmartCabinet } from '@/api/cabinet/smart-cabinet';

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

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

const visible = ref(props.modelValue);
const shopList = ref<ShopDTO[]>([]);
const loading = ref(false);
const currentCabinetId = ref<number>();
const pagination = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0
});

const loadShops = async () => {
  try {
    loading.value = true;
    const { data } = await getShopList({
      pageSize: pagination.value.pageSize,
      pageNum: pagination.value.currentPage
    });
    shopList.value = data.rows;
    pagination.value.total = data.total;
  } finally {
    loading.value = false;
  }
};

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

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

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

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

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