<script lang="ts" setup name="wordManage_wordDetail">
import { useRoute } from 'vue-router'

import {
  deleteSentence,
  getWordDetail,
  updateMeaning,
  updateSentence,
} from '#/api'
import { meaningService } from '#/api/service/meanig'
import hud from '#/utils/hud'
import { delConfirm } from '#/utils/tool'
import XbTableClass from '#/utils/xbTable'

import column, {
  event_add,
  event_delete_meaning,
  event_delete_sentence,
  event_edit,
} from './column.jsx'
import Dia from './Dia.vue'
import AddMeaning from './popup/add-meaning.vue'
import PopMnemonicList from './popup/MnemonicList/PopMnemonicList.vue'

const route = useRoute()

const tableRef = ref()
const showDia = ref(false)
const showPopMnemnic = ref(false)
const showAddMeaning = ref(false)
const diaTitle = ref('')
const diaData = ref()
const tableData = ref()
const wordId = ref()
const meaningId = ref()
const isEdit = ref(false)
const isParent = ref(true)
const diaDataTotal = ref() // 弹框数据
const xbTable = reactive(
  new XbTableClass({
    column: column(
      {
        clickImage,
        updateState,
        updateLevelFlag,
        handleClick,
      },
      meaningId,
    ),
    page: {
      size: -1,
      current: 1,
      total: 0,
    },
    data: [],
  }),
)
provide('xbTable', xbTable)
async function getTableData() {
  wordId.value = route.params.id
  meaningId.value = route.query.meaningId

  const res = await getWordDetail({
    wordId: wordId.value,
    ...xbTable.table.page,
    // ...filterData.value,
  })
  diaDataTotal.value = res
  for (const item of res.meaningList) {
    item.image =
      item.image && !Array.isArray(item.image) ? item.image.split(',') : []
    if (item.children) {
      for (const child of item.children) {
        addProp(item, child)
        child.enDesc = child.content
        child.image =
          child.image && !Array.isArray(child.image)
            ? child.image.split(',')
            : []
      }
    }
  }
  xbTable.table.data = res.meaningList
}

function addProp(parant: anyObj, child: anyObj) {
  child.canChangeMeaningWordFormLabel = !!(
    parant.typeAbbr === 'n.' ||
    parant.typeAbbr === 'v.' ||
    parant.typeAbbr === 'adj.' ||
    parant.typeAbbr === 'adv.'
  )
}

function clickImage(_: number, _2: string) {}

async function updateLevelFlag(row: anyObj) {
  // row.loading = true;
  try {
    let val = 0
    await updateSentence({
      id: row.id,
      levelFlag: row.levelFlag === 0 ? (val = 1) : (val = 0),
    })
    row.levelFlag = val
  } catch {
    return false
  }
  // finally {
  //     row.loading = false;
  // }
}

async function updateState(row: anyObj) {
  // row.loading = true;
  try {
    // eslint-disable-next-line no-prototype-builtins
    const updateMethod = row.hasOwnProperty('children')
      ? updateMeaning
      : updateSentence
    let val = 0
    await updateMethod({
      id: row.id,
      checkFlag: row.checkFlag === 0 ? (val = 1) : (val = 0),
    })
    row.checkFlag = val
  } catch {
    return false
  }
}

function handleClick(type: number, row: anyObj) {
  isEdit.value = type === 1
  switch (type) {
    case 4: {
      showPopMnemnic.value = true
      diaData.value = row
      break
    }
    case 5: {
      diaTitle.value = '例句验收'
      diaData.value = row
      tableData.value = xbTable.table.data
      showDia.value = true
      break
    }

    case 6: {
      getTableData()
      ElMessage.success('更换成功')
      break
    }
    case event_add: {
      showDia.value = true
      diaTitle.value = '新增'
      diaData.value = {
        meaningId: row.id,
      }
      // eslint-disable-next-line no-prototype-builtins
      isParent.value = row.hasOwnProperty('children')
      break
    }
    case event_delete_meaning: {
      // 删除释义
      hud.confirmLoad(`确定要删除释义【${row.simpleDesc}】？`, {
        task: async () => {
          await meaningService.remove(row.id)
          getTableData()
        },
        option: '删除释义',
      })
      break
    }
    case event_delete_sentence: {
      delConfirm().then(() => {
        deleteSentence(row.id).then(() => {
          getTableData()
          ElMessage.success('删除成功')
        })
      })
      break
    }
    case event_edit: {
      //  编辑
      showDia.value = true
      diaTitle.value = ''
      diaData.value = row
      tableData.value = xbTable.table.data
      // eslint-disable-next-line no-prototype-builtins
      isParent.value = row.hasOwnProperty('children')
      break
    }
  }
}

function handleAdd() {
  showAddMeaning.value = true
}

const tableHeight = computed(() => {
  if (tableRef.value && tableRef.value.getBox) {
    const { top, pageHeight } = tableRef.value!.getBox()
    return `${window.innerHeight - top - pageHeight}px`
  }
  return '600px'
})

onMounted(() => {
  xbTable.table.ref = tableRef.value
  getTableData()
  // nextTick(() => {
  //     xbTable.dragSort()
  // })
})
</script>

<template>
  <section class="page g-container">
    <!-- <Filter ref="filter" v-model="filterData" @handleClick="onFilterClick"></Filter> -->
    <Table
      ref="tableRef"
      class="page-table"
      :height="tableHeight"
      :pagination="false"
    >
      <template #neck>
        <div class="btn">
          <span class="spell">{{ diaDataTotal?.spell }}</span>
          <el-button type="primary" @click="handleAdd"> 添加释义 </el-button>
        </div>
      </template>
    </Table>
    <Dia
      v-model:show-dia="showDia"
      :title="diaTitle"
      :dia-data="diaData"
      :is-edit="isEdit"
      :table-data="tableData"
      :is-parent="isParent"
      @on-refresh="getTableData"
    />
    <PopMnemonicList v-model:show-dia="showPopMnemnic" :dia-data="diaData" />
    <AddMeaning
      v-model="showAddMeaning"
      :word-id="wordId"
      @on-refresh="getTableData"
    />
  </section>
</template>

<style lang="scss" scoped>
@include xbj_table;

.page-table {
  position: relative;
}

.btn {
  // position: absolute;
  // left: 85%;
  // top: 30px;
  // z-index: 9;
  display: flex;
  gap: 20px;
  align-items: center;
  margin-bottom: 20px;

  .spell {
    font-size: 20px;
    font-weight: bold;
  }
}
</style>
