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

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

import { getWordRootList, postAssistMemory } from '#/api'
import dictManagementApi from '#/api/modules/setting/dictManagement'

interface AssistType {
  code: number
  type: string
}

interface rootSelectedItem {
  wordRootId: string
  wordRootName: string
}

interface WordRootItem {
  createTime: null | string
  createUser: null | string
  delFlag: number
  id: string
  note: string
  sameSourceWords: string
  sort: string
  updateTime: string
  updateUser: string
  wordRoot: string
  wordRootFrom: string
  wordRootMeaning: string
  wordRootType: number
}

interface PropType {
  diaData: {
    assistText: string
    assistType: number
    id?: string
    wordId?: string
    wordRootVoList: Array<rootSelectedItem>
  }
  diaTitle: string
  showDia: boolean
}

const props = withDefaults(defineProps<PropType>(), {
  diaData: () => ({
    assistType: 1,
    assistText: '',
    wordRootVoList: [],
  }),
})
const emits = defineEmits(['update:showDia', 'update:diaData', 'onRefresh'])
const handleChange = (val: string) => {
  if (!val) {
    rootWordList.data.result = []
  }
}
const maskData = ref('')
const showMask = ref(false)
const leftX = ref()
const topY = ref()
const show = computed({
  get() {
    return props.showDia
  },
  set(val) {
    emits('update:showDia', val)
  },
})
const ruleFormRef = ref<FormInstance>()
/* 下拉框 */
const assistTypeList = ref<Array<AssistType>>([])
/* 表单 */
const form = {
  data: reactive({
    assistType: 1,
    assistText: '',
    wordRootVoList: [] as Array<rootSelectedItem>,
  }),
  rules: {
    assistType: [{ required: true, message: '请输入类型', trigger: 'blur' }],
    assistText: [
      { required: true, message: '请输入助记内容', trigger: 'blur' },
    ],
  },
  submit() {
    ruleFormRef.value?.validate((valid, _) => {
      if (valid) {
        if (props.diaTitle === '添加助记') {
          postAssistMemory([
            {
              meaningId: props.diaData.id,
              wordId: props.diaData.wordId,
              assistType: form.data.assistType,
              assistText: form.data.assistText,
              wordRootIds:
                form.data.wordRootVoList.length > 0
                  ? form.data.wordRootVoList
                      .map(
                        (childItem: rootSelectedItem) => childItem.wordRootId,
                      )
                      .join(',')
                  : '',
            },
          ]).then(() => {
            emits('onRefresh')
          })
        } else {
          emits('update:diaData', { ...props.diaData, ...form.data })
        }
        show.value = false
      }
    })
  },
}
/* 下拉框所选值为词根时，显示相关内容 */
const showFormRoot = computed(() => {
  const currentType = form.data.assistType
  const typeName = assistTypeList.value.find(
    (item) => item.code === currentType,
  )?.type
  return typeName === '词根'
})
/* 已选词根 */
const rootWordSelectd = {
  add(item: WordRootItem) {
    form.data.wordRootVoList.push({
      wordRootId: item.id,
      wordRootName: item.wordRoot,
    })
  },
  remove(index: number) {
    form.data.wordRootVoList.splice(index, 1)
  },
}
/* 词根列表 */
const rootWordList = {
  data: reactive({
    loading: false,
    result: [] as Array<WordRootItem>,
  }),
  params: {
    searchVal: ref(''),
    page: {
      current: 1,
      size: 20,
      totalPage: 1,
      totalRows: 0,
    },
  },
  init() {
    const _this = rootWordList
    _this.params.page.current = 1
    rootWordList.data.result = []
    _this.load()
  },
  async load() {
    const { params, data } = rootWordList
    if (params.page.current > params.page.totalPage) {
      return
    }

    const res = await getWordRootList({
      current: params.page.current,
      size: params.page.size,
      wordRoot: params.searchVal.value,
    })
    data.result = [...data.result, ...res.rows]
    params.page.totalPage = res.totalPage
    params.page.totalRows = res.totalRows
    params.page.current++
  },
}
/* 加载下拉框列表并设值 */
async function getAssistTypeList() {
  const res = await dictManagementApi.getDictTypePage({ name: '助记类型' })
  assistTypeList.value = JSON.parse(res.rows[0].remark)
  form.data.assistType = assistTypeList.value[0]?.code as any
}

function onOpen() {
  rootWordList.params.searchVal.value = ''
  rootWordList.data.result = []
  nextTick(async () => {
    form.data.assistText = props.diaData.assistText
    form.data.assistType = props.diaData.assistType
    form.data.wordRootVoList = props.diaData.wordRootVoList ?? []
  })
}
function onClose() {
  rootWordList.data.result = []
}

function handleshow(value: boolean, str: string) {
  showMask.value = value
  maskData.value = str
}

function handleMove(e: MouseEvent) {
  leftX.value = e.clientX - 85
  topY.value = e.clientY + 30
}

onMounted(() => {
  getAssistTypeList()
})
</script>
<template>
  <el-dialog
    v-model="show"
    :title="props.diaTitle"
    width="700px"
    top="10vh"
    class="box"
    destroy-on-close
    @open="onOpen"
    @close="onClose"
  >
    <el-form
      ref="ruleFormRef"
      label-width="140px"
      :model="form.data"
      :rules="form.rules"
    >
      <el-form-item label="类型" prop="assistType">
        <el-select v-model="form.data.assistType" placeholder="请选择">
          <el-option
            v-for="item in assistTypeList"
            :key="item.code"
            :disabled="props.diaTitle.includes('编辑')"
            :label="item.type"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="助记内容" prop="assistText">
        <el-input
          v-model="form.data.assistText"
          :rows="2"
          type="textarea"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item v-show="showFormRoot" label="搜索词根">
        <div class="flex items-center">
          <el-input
            v-model="rootWordList.params.searchVal.value"
            placeholder="输入名称搜索"
            :prefix-icon="Search"
            clearable
            @change="handleChange"
          />
          <el-button class="ml-4" type="primary" @click="rootWordList.init">
            搜索
          </el-button>
        </div>
      </el-form-item>
      <el-form-item v-show="showFormRoot" label="已选词根">
        <div class="result-list">
          <el-tag
            v-for="(item, index) in form.data.wordRootVoList"
            :key="item.wordRootId"
            class="mx-1"
            size="large"
            closable
            @close="rootWordSelectd.remove(Number(index))"
          >
            {{ item.wordRootName }}
          </el-tag>
        </div>
      </el-form-item>
      <el-form-item v-show="showFormRoot" label="搜索结果">
        <el-scrollbar v-loading="rootWordList.data.loading" class="result__box">
          <div
            v-show="rootWordList.data.result.length > 0"
            v-infinite-scroll="rootWordList.load"
            :infinite-scroll-immediate="false"
            class="result-list"
          >
            <div
              v-for="item in rootWordList.data.result"
              :key="item.id"
              class="result-item"
              @click="rootWordSelectd.add(item)"
              @mouseenter="handleshow(true, item.wordRootMeaning)"
              @mousemove="handleMove($event)"
              @mouseleave="handleshow(false, '')"
            >
              <!-- <div class="mask"> -->
              <!-- {{ item.wordRootMeaning }} -->
              <!-- </div> -->
              {{ item.wordRoot }}
            </div>
          </div>
          <div v-show="rootWordList.data.result.length === 0">
            <h4 class="text-center">暂无数据</h4>
          </div>
        </el-scrollbar>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="show = false"> 取消 </el-button>
        <el-button type="primary" @click="form.submit"> 保存 </el-button>
      </span>
    </template>
    <div
      v-if="showMask"
      class="mask"
      :style="{ left: `${leftX}px`, top: `${topY}px` }"
    >
      {{ maskData }}
    </div>
  </el-dialog>
</template>
<style lang="scss" scoped>
.result__box {
  width: 100%;
  height: 200px;
  overflow-y: auto;
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);

  .result-list {
    .result-item {
      position: relative;
      display: inline-block;
      padding: 0 20px;
      margin: 4px;
      cursor: pointer;
      border: var(--el-border);
      border-radius: var(--el-border-radius-round);

      &:hover {
        border-color: var(--el-border-color-hover);
      }
    }
  }
}

.mask {
  position: fixed;
  z-index: 3;
  width: 170px;
  padding: 10px 20px;
  color: #fff;
  text-align: center;
  background-color: rgba($color: #000, $alpha: 70%);
  border-radius: 8px;
}

.mx-1 {
  margin-bottom: 5px;
}
</style>
