<template>
  <el-drawer v-model="visible" title="地址配置" size="30%" direction="rtl">
    <div class="shop-config-container">
      <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" class="pagination" />
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { computed, 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;
  // belongType?: number;
}>();

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

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
});
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,
      // belongType: props.belongType
    });
    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;
  if (val) {
    loadShops();
  }
});

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);
    emit('refresh');
  } catch (error) {
    console.error('配置失败', error);
  }
};
</script>
<style lang="scss" scoped>
.shop-config-container {
 padding: 12px;
 background-color: #fff!important;
}
.pagination {
  margin-top: 10px;
}
</style>