<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'

import type { meaningListType, searchWordType } from '../interface'

import { Search } from '@element-plus/icons-vue'

import { searchWordAdminApi } from '#/api'
// import Deformation from './Deformation.vue';
const props: any = defineProps({
  data: {
    type: Object,
    default: () => ({
      originWordId: null,
      form: null,
      simpleDesc: '',
      enDesc: '',
      subTypeStr: '',
      znDesc: '',
      originWordSpell: '',
      typeAbbr: '',
    }),
  },
  hideRemove: {
    type: Boolean,
    default: false,
  },
  index: {
    type: Number,
    default: 0,
  },
  wordSpinnerTypeList: {
    type: Array,
    default: () => [
      {
        abbr: '',
        code: 0,
        spell: '',
        znDesc: '',
      },
    ],
  },
  wordSonSpinnerList: {
    type: Array,
    default: () => [{ spell: '', znDesc: '' }],
  },
  wordSpinnerList: {
    type: Array,
    default: () => [{ type: 0, name: '' }],
  },
})
const emit = defineEmits(['changeData', 'deleteMeaning'])
const WordMeaningData = ref<meaningListType>({ ...props.data })
watch(
  () => WordMeaningData.value,
  (nv) => {
    emit('changeData', nv)
  },
  {
    deep: true,
  },
)

const wordFormRef = ref<FormInstance | undefined>()
const seachStr = ref('')
const searchWord = ref<searchWordType[]>([])
const globalLoading = ref(false)
const closeTag = () => {
  WordMeaningData.value.originWordId = null
  WordMeaningData.value.originWordSpell = ''
}
const handleGlobalSeach = () => {
  globalLoading.value = true
  searchWordAdminApi({ spell: seachStr.value })
    .then((res) => {
      searchWord.value = res
    })
    .finally(() => (globalLoading.value = false))
}
const handleWordSelected = (word: searchWordType) => {
  if (word.id === WordMeaningData.value.originWordId) return
  WordMeaningData.value.originWordId = word.id
  WordMeaningData.value.originWordSpell = word.spell
}
const wordType = ref(1)
watch(
  () => wordType.value,
  (nv) => {
    WordMeaningData.value.form = nv === 2 ? 1 : null
  },
)
const wordTypeList = reactive([
  { label: '关联词', value: 1 },
  { label: '独立词', value: 2 },
])

const rules = reactive<FormRules>({
  // typeAbbr: [{ required: true, message: '单词释义不能为空', trigger: 'blur' }],
  typeAbbr: [{ validator: checkAge, required: true, trigger: 'blur' }],
})

function checkAge(rule: any, value: any, callback: any) {
  let isPassed = false
  isPassed =
    wordType.value === 1
      ? !WordMeaningData.value.typeAbbr ||
        !WordMeaningData.value.originWordId ||
        !WordMeaningData.value.form ||
        WordMeaningData.value.form === 1
      : !WordMeaningData.value.typeAbbr || !WordMeaningData.value.simpleDesc
  if (isPassed) {
    ElMessage.error('请填写完整单词释义信息')

    callback(new Error(''))
  } else {
    callback()
  }
}

async function checkFlag() {
  return wordFormRef.value?.validate()
}
function onClear() {
  WordMeaningData.value = {
    originWordId: null,
    form: null,
    simpleDesc: '',
    enDesc: '',
    subTypeStr: '',
    znDesc: '',
    originWordSpell: '',
    typeAbbr: '',
  }
}

defineExpose({
  checkFlag,
  onClear,
})
</script>

<template>
  <div class="word-meaning">
    <el-form
      ref="wordFormRef"
      label-width="90px"
      :model="WordMeaningData"
      :rules="rules"
    >
      <el-row style="margin-top: 20px">
        <el-col :span="3.5">
          <el-form-item :label="`单词释义${index + 1}`" prop="typeAbbr" />
          <!-- <div prop="typeAbbr">
                        {{ `单词释义${index + 1}` }}
                    </div> -->
        </el-col>

        <el-col :span="5" flex>
          <el-select
            v-model="WordMeaningData.typeAbbr"
            class="w-full"
            placeholder="请选择"
          >
            <el-option
              v-for="item in props.wordSpinnerTypeList"
              :key="item.code"
              :label="item.abbr"
              :value="item.abbr"
            />
          </el-select>
        </el-col>
        <el-col :span="12">
          <div class="select_box">
            <el-select v-model="wordType" class="w-full" placeholder="请选择">
              <el-option
                v-for="item in wordTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </el-col>
        <el-col v-if="!hideRemove" :span="3">
          <el-popconfirm
            title="确定删除该释义吗？"
            :width="180"
            @confirm="$emit('deleteMeaning', index)"
          >
            <!-- @confirm="handleDeleteDefinition(index)" -->

            <template #reference>
              <el-button type="primary">删除</el-button>
            </template>
          </el-popconfirm>
        </el-col>
      </el-row>
      <template v-if="wordType === 1">
        <el-form-item label="搜索框">
          <el-input
            v-model="seachStr"
            :prefix-icon="Search"
            @change="handleGlobalSeach()"
          />
        </el-form-item>
        <div class="edit__item">
          <el-form-item label="关联词">
            <div class="words__list w-full">
              <span class="words__item">
                <el-tag
                  v-if="WordMeaningData.originWordId"
                  class="mx-1"
                  size="large"
                  closable
                  @close="closeTag()"
                >
                  {{ WordMeaningData.originWordSpell }}</el-tag
                >
              </span>
            </div>
          </el-form-item>
        </div>
        <div class="searcn-result-list">
          <el-scrollbar
            v-loading="globalLoading"
            class="words__container global__words"
          >
            <div
              v-show="searchWord.length > 0"
              :infinite-scroll-immediate="false"
              class="search_data_box"
            >
              <div class="words-list-search flex flex-wrap gap-x-4 gap-y-2">
                <div
                  v-for="(word, index) in searchWord"
                  :key="index"
                  class="words-list-search-item"
                  :class="{
                    isHidden: word.id === WordMeaningData.originWordId,
                  }"
                  @click="handleWordSelected(word)"
                >
                  {{ word.spell }}
                </div>
              </div>
            </div>
            <div v-show="searchWord.length === 0">
              <h4 class="text-center">暂无数据</h4>
            </div>
          </el-scrollbar>
        </div>
        <el-form-item label="联系">
          <el-col :span="13">
            <el-select
              v-model="WordMeaningData.form"
              class="w-full"
              placeholder="请选择"
            >
              <el-option
                v-for="item in props.wordSpinnerList"
                :key="item.type"
                :label="item.name"
                :value="item.type"
              />
            </el-select>
          </el-col>
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item label="英文描述">
          <el-col :span="20">
            <el-input
              v-model="WordMeaningData.enDesc"
              type="textarea"
              size="small"
              :rows="3"
              placeholder="请输入"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="中文描述">
          <el-col :span="20">
            <el-input
              v-model="WordMeaningData.simpleDesc"
              type="textarea"
              size="small"
              :rows="3"
              placeholder="请输入"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="添加子词性">
          <el-col :span="13">
            <el-select
              v-model="WordMeaningData.subTypeStr"
              class="w-full"
              placeholder="请选择"
            >
              <el-option
                v-for="item in props.wordSonSpinnerList"
                :key="item.spell"
                :label="item.spell"
                :value="item.spell"
              />
            </el-select>
          </el-col>
        </el-form-item>
        <!-- <Deformation
                        :data="item.DeformationList"
                        @changeList="item.DeformationList = $event"
                    /> -->
      </template>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.word-meaning {
  .word-title {
    // position: absolute;
    transform: translate(-10px, -10px);
  }

  .select_box {
    width: 150px;
    margin-left: 20px;
  }

  .searcn-result-list {
    height: 115px;
    margin-bottom: 20px;
    margin-left: 90px;
    border: 1px solid #dcdfe6;
    border-radius: 8px;

    h4 {
      margin: 0;
      line-height: 115px;
    }
  }

  :deep(.el-form-item__label) {
    font-weight: bold;
  }

  .words__list {
    min-height: 34px;
    padding: 5px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }

  .words-list-search {
    padding: 5px;

    .words-list-search-item {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 5px 2px;
      cursor: pointer;
      border: 1px solid #dcdfe6;
      border-radius: 8px;
      transition: opacity 0.3s;

      &:hover {
        background-color: #f5f7fa;
      }

      &.isHidden {
        // opacity: 0;
        display: none;
      }
    }
    // @keyframes hidden {
    //     from {
    //         opacity: 1;
    //     }
    //     to {
    //         opacity: 0;
    //         transform: translateY(-40px);
    //     }
    // }
  }
}

.add-box {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
