<template>
  <div class="preview-doc-back pointer">
    <el-icon @click="router.go(-1)">
      <ArrowLeftBold />
    </el-icon>
    {{ query?.name || '维度名称' }}
  </div>
  <div class="tag-page">
    <div class="tag-page-search">
      <el-input v-model="keyword" placeholder="请输入关键词" style="width: 25%" @input="searchPageData" :prefix-icon="Search" />
      <div class="tag-page-content-action">
        <el-space>
          <el-dropdown>
            <el-button>
              批量操作
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :disabled="ids.length <= 0" @click="handleBatchDelete">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  批量删除
                </el-dropdown-item>
                <el-dropdown-item :disabled="ids.length <= 0" @click="handleBatchMove">
                  <el-icon>
                    <Refresh />
                  </el-icon>
                  批量移动
                </el-dropdown-item>

              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button :icon="Plus" type="primary" @click="handleOpenForm">新建 </el-button>
        </el-space>
      </div>
    </div>
    <div class="tag-page-table">
      <!--loading-->
      <div
        v-if="loading"
        v-loading="loading"
        class="loading-page"
        element-loading-text="正在加载..."
        style="width: 100%; height: calc(100vh - 250px)"
      ></div>
      <!--搜索结果-->
      <lz-page-empty v-else-if="!tagData.length && !loading" type="5">
        <lz-svg-icon icon-class="empty2" style="font-size: 312px" />
      </lz-page-empty>
      <!-- table列表和分页-->
      <app-table
        v-else
        :data="tagData"
        :pagination-config="paginationConfig"
        :tableDefaultHeight="210"
        class="mt-16"
        style="width: 100%"
        @changePage="getPageData"
        @sizeChange="handleSizeChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="标签名称" min-width="220" prop="name">
          <template #default="{ row }">
            <AutoTooltip >
              {{ row.name }}
            </AutoTooltip>
          </template>
        </el-table-column>
        <el-table-column label="关联文件数" min-width="100" prop="create_id">
          <template #default="{ row }">
            <span @click="viewFile(row)">
              <AutoTooltip style="color: #3067ef; cursor: pointer">
              {{ row.fileCount }}
            </AutoTooltip>
            </span>

          </template>
        </el-table-column>
        <el-table-column label="更新时间" min-width="180" prop="modify_time">
          <template #default="{ row }">
            <AutoTooltip>
              {{ row.updatedTime }}
            </AutoTooltip>
          </template>
        </el-table-column>
        <el-table-column label="创建人" min-width="120" prop="modify_time">
          <template #default="{ row }">
            <AutoTooltip>
              {{ row.crateName }}
            </AutoTooltip>
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="right" label="操作" width="220">
          <template #default="{ row }">
            <div>
              <span class="mr-10 primary-text" style="cursor: pointer" @click="handleEdit(row)">
                编辑
              </span>
              <span class="mr-10 primary-text" style="cursor: pointer" @click="handleMove(row)">
                移动
              </span>
              <span class="mr-10 primary-text" style="cursor: pointer" @click="handleDelete(row)">
                删除
              </span>
            </div>
          </template>
        </el-table-column>
      </app-table>
    </div>
    <TagForm
      ref="tagFormRef"
      :title="tagFormTitle"
      @refresh="handleSizeChange"
    />
    <ViewDoc ref="viewDocRef" />
    <DialogForm
      ref="dialogFormRef"
      title="标签移动"
      moveLabel="目标维度"
      type="move"
      :move-current-id="query?.id as string"
      @submitHandle="handleMoveSubmit"
    />
  </div>
</template>

<script lang="ts" setup>
import AppTable from '@/components/app-table/index.vue'
import AutoTooltip from '@/components/auto-tooltip/index.vue'
import router from '@/router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { debounce } from 'lodash-es'
import { onMounted, reactive, ref } from 'vue'
import { Delete, Plus, Refresh, Search } from '@element-plus/icons-vue'
import TagForm from './components/TagForm.vue'
import ViewDoc from './components/ViewDoc.vue'
import DialogForm from '@/views/knowledge/components/DialogForm.vue'
import api from '@/servers/finyx/api/index'
import { useRoute } from 'vue-router'

const go = (name: string, query?: any) => {
  router.push({ name, query })
}
const { query } = useRoute();

const keyword = ref<string>()

const loading = ref<boolean>(false)
const tagData = ref<any>([])
const ids = ref<Array<string>>([])
const id = ref<string>('')
const paginationConfig = reactive({
  current_page: 1,
  page_size: 10,
  total: 0
})

// 搜索按钮
const searchPageData = debounce(() => {
  handleSizeChange()
}, 300)

const getListParams = () => {
  const { current_page, page_size } = paginationConfig
  const model: any = {
    model: {
      name: keyword.value,
      dimensionId: query?.id,
    },
    size: page_size,
    current: current_page
  }
  return model
}

const getPageData = async () => {
  try {
    loading.value = true
    const { records, total } = await api.weidubiaoqie.page1(getListParams())
    tagData.value = records
    paginationConfig.total = total
  } catch (e) {
    ElMessage.error('获取文档列表失败！')
  } finally {
    loading.value = false
  }
}
onMounted(getPageData)

const handleSizeChange = () => {
  paginationConfig.current_page = 1
  getPageData()
}

const handleSelectionChange = (val: any) => {
  ids.value = val.map((v: any) => v.id)
}

const viewDocRef = ref<any>(null)
const viewFile = (row: any) => {
  if (row.fileCount <= 0) {
    return ElMessage.warning('该标签下暂无文件！')
  }
  viewDocRef.value.open(row.id)
}

const tagFormTitle = ref<string>('')
const tagFormRef = ref<any>(null)
const handleOpenForm = () => {
  tagFormRef.value.open([{ name: '' }])
  tagFormTitle.value = '新建标签'
}
const handleEdit = (item: any) => {
  tagFormRef.value.open([item])
  tagFormTitle.value = '编辑标签'
}

const dialogFormRef = ref<any>(null)
// 单个移动
const handleMove = (row: any) => {
  id.value = row.id
  dialogFormRef.value.open()
}
// 批量移动
const handleBatchMove = () => {
  dialogFormRef.value.open()
}
// 移动确定按钮逻辑
const handleMoveSubmit = async (data: any) => {
  try {
    loading.value = true
    const model: any = {
      id: data.target
    }
    // 区分单个和多个
    if (id.value) {
      model.ids = [id.value]
    } else {
      model.ids = ids.value
    }
    await api.weidu.moveLabels(model)
    dialogFormRef.value.close()
    ElMessage.success('标签移动成功！')
    await getPageData()
  } catch (e: any) {
    ElMessage.error('标签移动失败！')
  } finally {
    id.value = ''
    loading.value = false
  }
  dialogFormRef.value.close()
}

const handleDelete = async (row: any) => {
  const confirm = await ElMessageBox.confirm('标签删除后，文件已打标签将同步删除且不可恢复！', {
    title: '确认删除标签',
    type: 'warning'
  })
  if (confirm) {
    try {
      loading.value = true
      await api.weidubiaoqie.delete1([row.id])
      ElMessage.success('标签删除成功！')
      handleSizeChange()
    } catch (e) {
      ElMessage.error('标签删除失败！')
    } finally {
      loading.value = false
      await getPageData()
    }
  }
}
const handleBatchDelete = async () => {
  const confirm = await ElMessageBox.confirm('标签删除后，文件已打标签将同步删除且不可恢复！', {
    title: '确认删除标签',
    type: 'warning'
  })
  if (confirm) {
    try {
      loading.value = true
      await api.weidubiaoqie.delete1(ids.value)
      ElMessage.success('标签删除成功！')
      handleSizeChange()
    } catch (e) {
      ElMessage.error('标签删除失败！')
    } finally {
      loading.value = false
      await getPageData()
    }
  }
}
</script>

<style lang="scss" scoped>
.preview-doc-back {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 20px;

  .el-icon {
    margin-right: 6px;
  }
}

.tag-page {
  display: flex;
  height: 100%;
  flex-direction: column;

  &-search {
    width: 100%;
    display: flex;
    justify-content: space-between;

    &-action {
      width: 200px;
      margin-left: 10px;
    }
  }

  &-table {
    height: calc(100% - 32px);
    position: relative;
  }
}
</style>
