<template>
  <el-dialog :model-value="visible" class="chat-commonwords-dialog" :close-on-click-modal="false" :width="width" @close="close">
    <template #header="{ titleClass }">
      <div :class="titleClass"><span font-14 font-semibold>{{ currentWords._id ? '编辑常用语' : '新增常用语' }}</span></div>
    </template>
    <el-form px-15 pt-10 :label-width="0">
      <el-form-item class="mb-0">
        <div w-full class="mb-15px">
          <el-input type="textarea" :maxlength="1500" show-word-limit v-model="currentWords.content"
            placeholder="请输入常用语内容" :autosize="{ minRows: 4, maxRows: 8 }"></el-input>
        </div>
      </el-form-item>
      <el-form-item prop="name">
        <el-select w-full v-model="currentWords.cateId" placeholder="请选择常用语分类">
          <el-option v-for="item in cates" :class="item._id === 'all'?'hidden':''" :key="item._id" :label="item.label"
            :value="item._id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div text-center>
        <el-button class="w-100px" @click="close()">取消</el-button>
        <el-button :loading="saveLoading" class="w-100px" type="primary" @click="setWords()"> 保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { computed, ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import useCommonWordsApi from './useApi';

const emits = defineEmits(['close', 'change', 'changeWords'])
const props = defineProps({
  visible: { type: Boolean, default: false },
  cates: { type: Array, default: () => [] },
  words: { type: Object, default: () => ({}) }
})

const { remove, getCommonWords, setWords: setMyWords, setCate } = useCommonWordsApi()

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


const currentWords = ref({});

async function removeWords(words) {
  await ElMessageBox.confirm('确认删除该常用语吗？', '提示', { type: 'warning' });
  const success = await remove(words._id);
  if (success) {
    ElMessage.success('删除成功');
    page.value = 1;
    getList();
    emits('changeWords', { id: words._id, cateId: words.cateId })
  }
}

async function setWords() {
  if (!currentWords.value.cateId || !props.cates.some(i => i._id === currentWords.value.cateId)) {
    ElMessage.info('请选择常用语分类')
  } else if (!currentWords.value.content || currentWords.value.content.trim() === '') {
    ElMessage.info('请输入常用语内容')
  } else {
    const success = await setMyWords(currentWords.value.cateId, currentWords.value.content, currentWords.value._id)
    if (success) {
      emits('change')
      close()
    }
  }
}
watch(() => props.visible, n => {
  if (n) {
    currentWords.value = { ...props.words }
  }
})

</script>