<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" :max-height="260" :header-cell-style="{background: '#F1F5FB'}">
        <el-table-column label="追溯码" prop="code" show-overflow-tooltip>
          <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" show-overflow-tooltip>
          <template #default="{row}">
            <span class="edit" @click="openCodeNumEdit(row)">
             {{ row.num }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="90">
          <template #default="{row}">
            <span class="remove" style="color: #ff0000" @click="removeRow(row)">
              <el-icon>
                <Delete/>
              </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 {Delete} 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 {

  .remove {
    cursor: pointer;

    &:hover {
      color: red;
    }
  }
}

:deep(.el-table td.el-table__cell) {
  .edit {
    cursor: pointer;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #4d6de4;
  }
}
</style>