<template>
  <el-dialog :title="title" width="410px" v-model="show" @close="reset">
    <el-input :rows="6" type="textarea" v-model="note" placeholder="请输入备注"></el-input>
    <div>
      <el-tag
        v-for="(tag, index) in tags"
        @click="addNote(tag)"
        :key="index"
        closable
        @close="delTag(index)"
        type="primary"
      >
        {{ tag }}
      </el-tag>
    </div>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
let show = ref(false);
let tags = ref([]);
let note = ref("");
let title = ref("整单备注(提交订单时生效)");
let isOne = ref(false);
watch(
  () => tags.length,
  () => {
    localStorage.setItem("tags", JSON.stringify(tags.value));
  }
);

function reset() {
  note.value = "";
}
function delTag(index) {
  this.tags.splice(index, 1);
}
function addNote(tag) {
  if (!note.value) {
    return (note.value = tag);
  }
  note.value = tag + "," + note.value;
}
function open(remark, isOneNote) {
  isOne.value = isOneNote;
  title.value = !isOneNote ? "整单备注(提交订单时生效)" : "单品备注(提交订单时生效)";
  show.value = true;
  note.value = remark ? remark : "";
  const tags = localStorage.getItem("tags");
  console.log(tags);
  this.tags = tags ? JSON.parse(tags) : ["免香菜", "不要辣", "不要葱"];
}
function close() {
  show.value = false;
}
const emits = defineEmits(["confirm"]);
function confirm() {
  const originTags = [...tags.value];
  if (note.value) {
    if (originTags >= 10) {
      originTags.shift();
    }
    if (note.value.length <= 16) {
      const newTags = new Set([note.value, ...originTags]);
      localStorage.setItem("tags", JSON.stringify([...newTags]));
    }
  }
  emits("confirm", note.value, isOne.value);
  close();
}

defineExpose({
  open,
  close,
});
</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
  margin-bottom: 14px;
  margin-top: 14px;
}
:deep(.el-tag) {
  margin-top: 10px;
  margin-right: 10px;
  margin-bottom: 5px;
  cursor: pointer;
  font-size: 15px;
  line-height: 35px;
  height: 35px;
}
</style>