<template>
  <el-dialog :model-value="props.visible" :width="width" title="设置分类" @close="close()">
    <div class="p-15px">
      <el-cascader v-model="cateId" class="w-full" :show-all-levels="false" :options="cateTree"
        :props="{checkStrictly:true,value:'_id'}" clearable placeholder="请选择分类" />
    </div>
    <template #footer>
      <div text-center>
        <el-button plain class="w-100px" type="primary" :icon="Plus" @click="close()">取消</el-button>
        <el-button class="w-100px" :loading="loading" type="primary" :icon="Plus" @click="confirm()">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { computed, ref, watch } from "vue";
const emits = defineEmits(['close', 'change']);
const props = defineProps({
  id: { type: String, default: '' },
  visible: { type: Boolean, default: false },
  cateTree: { type: Array, default: () => [] },
  updateMethod: { type: Function, default: () => { } },
  width: { type: String, default: '500px' },
})
const cateId = ref('');
const cateIdStr = computed(() => {
  if (typeof cateId.value === 'string') return cateId.value;
  return Array.isArray(cateId.value) ? cateId.value[cateId.value.length - 1] || '' : '';
})

function close() {
  emits('close')
}

const loading = ref(false);
async function confirm() {
  if (props.id === cateIdStr.value) {
    close()
    return
  }
  loading.value = true;
  const { success, message } = await props.updateMethod(cateIdStr.value);
  if (success) {
    ElMessage.success(message);
    close();
  } else {
    ElMessage.error(message);
  }
  loading.value = false
}

watch(() => props.visible, (n) => {
  if (n) {
    cateId.value = props.id;
  }
})

</script>