<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" label-width="0" class="demo-form-inline"
        @keyup.enter="handleSubmitSearch">
        <el-form-item style="width:300px">
          <el-tooltip content="从名称中搜索" placement="top-start">
            <el-input v-model="searchInfo.keyword" class="keyword" placeholder="请输入关键词" clearable style="width:100%" />
          </el-tooltip>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleSubmitSearch">查询</el-button>
          <el-button icon="refresh" @click="handleResetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="handleAdd">新增院士</el-button>
        <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length"
          @click="handleMultiDelete">删除</el-button>
      </div>

      <!-- 由于此处菜单跟左侧列表一一对应所以不需要分页 pageSize默认999 -->
      <el-table ref="multipleTable" :data="tableData" row-key="ID" @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" width="40" align="center" />
        <el-table-column align="left" label="ID" min-width="40" prop="ID" />
        <el-table-column align="left" label="首字母" min-width="50" prop="headChar">
          <template #default="scope">
            <el-text size="large" tag="b">{{ scope.row.headChar }}</el-text>
          </template>
        </el-table-column>
        <el-table-column align="left" label="头像" min-width="120" prop="avatar">
          <template #default="scope">
            <el-image v-if="scope.row.avatar" :src="scope.row.avatar" class="file" fit="cover"
              :preview-src-list="[scope.row.avatar]" preview-teleported hide-on-click-modal close-on-press-escape
              style="max-width: 70px; max-height: 90px" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="姓名/职称" min-width="120" prop="name">
          <template #default="scope">
            <el-link type="primary" :href="getAcademicianPreviewPath(scope.row.ID)" target="_blank">
              <el-text size="large" tag="b">{{ scope.row.name }}</el-text>
            </el-link>
            <div>{{ scope.row.title }}</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="简介" min-width="300" prop="brief" class-name="text-truncate">
          <template #default="scope">
            <el-text :line-clamp="3">{{ scope.row.brief }}</el-text>
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="right" label="操作" width="200">
          <template #default="scope">
            <div>
              <el-button type="primary" link icon="edit" @click="handleRowEdit(scope.row.ID)">编辑</el-button>
              <el-button type="success" link icon="Guide" @click="handleSelProject(scope.row)">关联项目</el-button>
            </div>
            <div>
              <el-button type="danger" link icon="delete" @click="handleRowDelete(scope.row.ID)">删除</el-button>
              <el-button type="success" link icon="VideoPlay" @click="handleSelLecture(scope.row)">关联讲座</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination layout="total, sizes, prev, pager, next, jumper" :current-page="page" :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]" :total="total" @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>

    <AcademicianEdit ref="elEditRef" :title="editTitle" @on-save="handlerFormSave" />

    <SelectArticle ref="elSelectArticleRef" :title="selectArticleTitle" @on-select="handleSelectArticle" />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAcademicianPreviewPath } from '@/utils/format'
import {
  getAcademicianList,
  deleteAcademician,
  deleteAcademicianByIds,
  setAcademicianRel,
} from '@/api/academician'
import AcademicianEdit from '@/view/content/components/academicianEdit.vue'
import SelectArticle from '@/view/content/components/selectArticle.vue'

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const searchInfo = ref({})
const tableData = ref([])
const multipleSelection = ref([])// 多选数据
const elSearchFormRef = ref()
const elSelectArticleRef = ref()

const initSearchInfo = () => {
  searchInfo.value.keyword = ''
  page.value = 1
}
initSearchInfo()
const getTableData = async valid => {
  const res = await getAcademicianList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (res.code === 0) {
    tableData.value = res.data.list
    total.value = res.data.total
  }
}

getTableData()

// 重置
const handleResetSearch = () => {
  initSearchInfo()
  getTableData()
}
// 搜索
const handleSubmitSearch = () => {
  elSearchFormRef.value?.validate(async valid => {
    if (!valid) return
    getTableData()
  })
}
// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// ------ 列表操作相关 -----
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
// 批量删除
const handleMultiDelete = () => {
  ElMessageBox.confirm('确定要删除所选内容吗?', '请确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async valid => {
    const IDs = []
    if (multipleSelection.value.length === 0) {
      ElMessage({
        type: 'warning',
        message: '请选择要删除的数据'
      })
      return
    }
    multipleSelection.value &&
      multipleSelection.value.map(item => {
        IDs.push(item.ID)
      })
    const res = await deleteAcademicianByIds({ IDs })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      if (tableData.value.length === IDs.length && page.value > 1) {
        page.value--
      }
      getTableData()
    }
  })
}
// 删除
const handleRowDelete = (ID) => {
  ElMessageBox.confirm('此操作将删除院士, 是否继续?', '请确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async valid => {
    const res = await deleteAcademician({ ID })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      if (tableData.value.length === 1 && page.value > 1) {
        page.value--
      }
      getTableData()
    }
  })
}

const elEditRef = ref(null)
const editTitle = ref('')
// 添加
const handleAdd = () => {
  editTitle.value = '添加院士'
  elEditRef.value.openPage({ id: 0 })
}
// 修改
const handleRowEdit = async (ID) => {
  editTitle.value = '修改院士-' + ID
  elEditRef.value.openPage({ ID: ID })
}
// 保存后
const handlerFormSave = () => {
  getTableData()
}

const selectArticleTitle = ref('')
const handleSelProject = (row) => {
  selectArticleTitle.value = '关联院士项目'
  let articleIds = []
  if (row.projects != '') {
    articleIds = JSON.parse(row.projects)
  }
  const params = { kind: 'projects', ID: row.ID }
  elSelectArticleRef.value.openPage(params, articleIds)
}
const handleSelLecture = (row) => {
  selectArticleTitle.value = '关联院士讲座'
  let articleIds = []
  if (row.lectures != '') {
    articleIds = JSON.parse(row.lectures)
  }
  const params = { kind: 'lectures', ID: row.ID }
  elSelectArticleRef.value.openPage(params, articleIds)
}
const handleSelectArticle = async (params, rows) => {
  // 保存关联项目
  const articleIds = rows.map(item => item.ID)
  const res = await setAcademicianRel({ ...params, articleIds: articleIds })
  if (res && res.code === 0) {
    ElMessage({
      type: 'success',
      message: '更新成功!'
    })
    getTableData()
  }
}
</script>

<style type="scss">
.admin-box .el-table td .cell {
  line-height: 28px;
}
</style>
