<template>
  <el-popover placement="bottom-end" :visible="isVisible" width="400">
    <template #reference>
      <el-input v-model="input" style="width:100%;height: 100%" placeholder="追溯码" size="small" @focus="focus"
                @blur="handlerBlur" @keydown.enter="addCode"></el-input>
    </template>
    <div class="code-popo">
      <el-table :data="list">
        <el-table-column label="追溯码" prop="code">
          <template #default="{row}">
            {{ row.code.slice(0, 7) }}&nbsp;{{ row.code.slice(7) }}
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="num" width="70">
          <template #default="{row}">
            <span class="edit" @click="openCodeNumEdit(row)">
             {{ row.num }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="70">
          <template #default="{row}">
            <span class="remove" @click="removeRow(row)">
              <el-icon>
                <Close/>
              </el-icon>
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-popover>
  <CodeNumEditDialog ref="codeNumEditDialogRef"></CodeNumEditDialog>
</template>
<script setup lang="ts">
import {ref, watch, onMounted, onUnmounted, nextTick} from "vue";
import {Close} from "@element-plus/icons-vue";
import CodeNumEditDialog from "@/components/inventory/purchase/CodeNumEditDialog.vue";

interface listType {
  code: string;
  num: number;
}

const list = defineModel<listType[]>();
const input = ref("");
const isVisible = ref(false);
const focus = () => {
  isVisible.value = true;
};
const handlerBlur = () => {
  isVisible.value = false;
}
const addCode = () => {
  if (!list.value) {
    list.value = []
  }
  let index = list.value?.findIndex((item: any) => item.code === input.value);
  if (index !== -1) {
    list.value[index].num++;
  } else {
    list.value?.push({
      code: input.value,
      num: 1,
    });
  }
  clearInput()
};

const clearInput = () => {
  input.value = "";
};
const removeRow = (row: any) => {
  list.value = list.value?.filter((item: any) => item.code !== row.code);
};
const codeNumEditDialogRef = ref();
const openCodeNumEdit = (row: any) => {
  nextTick(() => {
    codeNumEditDialogRef.value?.init(row);
  })
};
</script>
<style scoped lang="scss">
.code-popo {
  .edit{
    cursor: pointer;
  }
  .remove {
    cursor: pointer;

    &:hover {
      color: red;
    }
  }
}
</style>