<template>
  <el-dialog
    class="synonym-dialog"
    v-model="dialogVisible"
    title=""
    :width="900"
    align-center
    :close-on-click-modal="false"
    destroy-on-close
    @closed="closed"
  >
    <div class="table-box scroll-y">
      <div class="h-flex flex-space-between">
        <el-space class="ml20">
          <yx-title>标准词</yx-title>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item v-for="(item, i) in wordLink" :key="item.id">
              <span :style="i === wordLink.length - 1 ? { fontWeight: 'bold' } : undefined">
                {{ item.wordName }}
              </span>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </el-space>
        <el-form-item label="同义词：" class="mr20" style="margin-bottom: 0">
          <el-input v-model="searchValue" style="width: 200px" placeholder="请输入" clearable></el-input>
        </el-form-item>
      </div>
      <ProTable
        style="min-height: 100px"
        ref="proTable"
        :columns="columns"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
        :pagination="false"
        :request-auto="false"
        :tool-button="false"
        :data="fitlerTableData"
      >
        <!-- 标准词名称 -->
        <template #synonymWordName="scope">
          <AutoSaveInput
            :ref="scope.row.id.toString()"
            :maxlength="50"
            :display-value="scope.row.synonymWordName"
            @focus="editing = true"
            @done="editNameSave($event, scope.row)"
          >
            <template #suffix v-if="scope.row.wordSourceType === 2">
              <img
                class="ml5"
                style="vertical-align: middle"
                src="@/assets/images/label_tag.png"
                width="48"
                height="20"
                alt="标注"
              />
            </template>
          </AutoSaveInput>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button
            v-auth="['wordLib:write']"
            type="primary"
            link
            :icon="EditPen"
            :disabled="editing"
            @click="editAction(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            v-auth="['wordLib:write']"
            type="primary"
            link
            :icon="Delete"
            :disabled="editing"
            @click="delAction(scope.row)"
          >
            删除
          </el-button>
        </template>
      </ProTable>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, getCurrentInstance, computed } from "vue";
import { ElMessage } from "element-plus";
import { Delete, EditPen } from "@element-plus/icons-vue";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { AnnoLexicon, WordLib } from "@/api/interface";
import { getSynonymWordList, editSynonymWord, deleteSynonymWord } from "@/api/modules/annotation/lexicon";
import AutoSaveInput from "./AutoSaveInput.vue";
//* 接收注入
const dialogVisible = ref(false);

const proxy: any = getCurrentInstance()?.proxy;
// ProTable 实例
const proTable = ref<ProTableInstance>();
//* ref
const openPromise = ref<any>({});
const editing = ref(false);
const wordLink = ref<WordLib.Standard[]>([]);
const tableData = ref<AnnoLexicon.ResSynonymList[]>([]);
const standardWordId = ref<number>();
const searchValue = ref<string>("");

const fitlerTableData = computed(() => {
  const keyword = searchValue.value.trim().toLowerCase();
  if (keyword) return tableData.value.filter(item => item.synonymWordName.toLowerCase().includes(keyword));
  return tableData.value;
});
//* 方法

function closed() {
  editing.value = false;
  tableData.value = [];
}

// 表格配置项
const columns = reactive<ColumnProps<AnnoLexicon.ResSynonymList & { index: number }>[]>([
  { type: "index", label: "序号", width: 80 },
  { prop: "synonymWordName", label: "同义词", align: "left" },
  { prop: "operation", label: "操作", width: 200, fixed: "right" }
]);

// 分页列表获取数据
const getTableList = () => {
  if (editing.value) return;
  getSynonymWordList({ id: standardWordId.value as number }).then(res => {
    tableData.value = res.data;
  });
};

// 编辑名称失去焦点自动保存
async function editNameSave({ event, inputValue, displayValue, callback }: any, row: AnnoLexicon.ResSynonymList) {
  if (inputValue.length === 0) {
    ElMessage.warning("同义词名称为空");
    event.target.focus();
    return;
  }
  if (inputValue !== displayValue) {
    try {
      await editSynonymWord({ synonymWordId: row.id, synonymWordName: inputValue });
      editing.value = false;
      getTableList();
    } catch (err) {
      console.log(err);
      event.target.focus();
      return;
    }
  }
  editing.value = false;
  callback();
}

// 编辑
const editAction = (row: AnnoLexicon.ResSynonymList) => {
  proxy?.$refs[row.id].startEditing();
};

// 删除
const delAction = async (row: AnnoLexicon.ResSynonymList) => {
  await useHandleData(deleteSynonymWord, { id: row.id }, `是否删除当前词语，删除后该词语关联关系取消！`);
  getTableList();
};

function open(params: { id: number; wordLink: WordLib.Standard[] }) {
  dialogVisible.value = true;
  wordLink.value = params.wordLink || [];
  console.log(wordLink.value);
  standardWordId.value = params.id;
  getTableList();
  return new Promise(resolve => {
    openPromise.value.resolve = resolve;
  });
}
defineExpose({
  open
});
</script>

<style lang="scss" scoped>
.table-box {
  display: block;
  width: 100% !important;
  min-height: 241px;
  max-height: 80vh;
}
</style>
<style lang="scss">
.synonym-dialog {
  .el-dialog__header {
    border-bottom: none;
  }
}
</style>
