<template>
  <el-drawer v-model="showDrawer" size="1000" :show-close="false" :close-on-click-modal="false"
    :close-on-press-escape="false" style="background: #f8f8f8">
    <template #header>
      <div class="flex justify-between items-center">
        <span class="text-lg">{{ props.title }}</span>
        <div>
          <el-button type="primary" @click="handleSubmitDialog">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </div>
    </template>
    <div v-loading="fullscreenLoading">
      <div v-if="showErrMessage != ''">
        {{ showErrMessage }}
      </div>
      <div v-else>
        <div class="gva-search-box">
          <div class="section-title">已选择的</div>

          <el-table ref="selectedTableRef" :data="selectedData" row-key="ID">
            <el-table-column align="left" fixed="left" label="ID" min-width="40" prop="ID" />
            <el-table-column align="left" label="标题/副标题" min-width="360" prop="title">
              <template #default="scope">
                <div>
                  <el-link type="primary" :href="getArticlePreviewPath(scope.row.ID)" target="_blank">
                    <el-text :line-clamp="2"> {{ scope.row.title }}</el-text>
                  </el-link>
                </div>
                <el-text :line-clamp="2" size="small">{{ scope.row.subtitle }}</el-text>
              </template>
            </el-table-column>
            <el-table-column align="left" label="类型" min-width="80" prop="articleType">
              <template #default="scope">{{ formatArticleType(scope.row.articleType) }}</template>
            </el-table-column>
            <el-table-column align="left" label="状态" width="80">
              <template #default="scope">{{ formatStatus(scope.row.status) }}</template>
            </el-table-column>
            <el-table-column align="left" fixed="right" label="操作" width="80">
              <template #default="scope">
                <el-button type="danger" link icon="bottom" @click="handleRowRemove(scope.row)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div><br /></div>
        </div>

        <div class="gva-search-box" style="margin-top: 10px">
          <div class="section-title">待选择的</div>
          <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" label-width="0"
            @keyup.enter="handleSubmitSearch">
            <el-form-item prop="createdAt" style="width:260px">
              <el-tooltip content="搜索范围是创建开始日期（包含）至创建结束日期（包含）" placement="top-start">
                <el-icon>
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
              <el-date-picker v-model="searchInfo.dateRange" type="daterange" value-format="YYYY-MM-DD"
                :clearable="false" :editable="false" />
            </el-form-item>
            <el-form-item style="width:200px">
              <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 label="" prop="status" style="width:120px">
              <el-select v-model="searchInfo.status" placeholder="请选择状态" clearable style="width:300px">
                <el-option v-for="item in statusOptions" :key="item.key" :label="item.label" :value="item.key" />
              </el-select>
            </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>

          <el-table ref="multipleTableRef" :data="tableData" row-key="ID">
            <el-table-column align="left" label="ID" min-width="60" prop="ID" />
            <el-table-column align="left" label="标题/副标题" min-width="400" prop="title">
              <template #default="scope">
                <div>
                  <el-link type="primary" :href="getArticlePreviewPath(scope.row.ID)" target="_blank">
                    <el-text :line-clamp="2"> {{ scope.row.title }}</el-text>
                  </el-link>
                </div>
                <el-text :line-clamp="2" size="small">{{ scope.row.subtitle }}</el-text>
              </template>
            </el-table-column>
            <el-table-column align="left" label="类型" min-width="80" prop="articleType">
              <template #default="scope">{{ formatArticleType(scope.row.articleType) }}</template>
            </el-table-column>
            <el-table-column align="left" label="状态" width="80">
              <template #default="scope">{{ formatStatus(scope.row.status) }}</template>
            </el-table-column>
            <el-table-column align="left" fixed="right" label="操作" width="80">
              <template #default="scope">
                <el-button type="primary" link icon="top" @click="handleRowSelect(scope.row)">选择</el-button>
              </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><br /></div>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref } from 'vue'
import { getArticlePreviewPath } from '@/utils/format'
import { getArticleList } from '@/api/article'
// import { getCategoryTree } from '@/api/category'
// import { getChannelTree } from '@/api/channel'
import { formatTimeToStr } from '@/utils/date'
import {
  statusOptions,
  formatArticleType,
  formatStatus
} from '@/utils/options'

// 组件定义
defineOptions({
  name: 'SelectArticle',
})
const emit = defineEmits(['on-select', 'on-close'])
const props = defineProps({
  title: { type: String, default: '选择文章' }
})

const showDrawer = ref(false)
const showErrMessage = ref('')
const fullscreenLoading = ref(true)

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const searchInfo = ref({})
const tableData = ref([])
const elSearchFormRef = ref()

const initSearchInfo = () => {
  const endDate = new Date()
  const startDate = new Date(endDate.getTime() - 30 * 24 * 60 * 60 * 1000)

  searchInfo.value.keyword = ''
  searchInfo.value.dateRange = [
    formatTimeToStr(startDate, 'yyyy-MM-dd'),
    formatTimeToStr(endDate, 'yyyy-MM-dd'),
  ]
  page.value = 1
}

const getTableData = async () => {
  const excludeIds = selectedData.value.map(item => item.ID)
  const res = await getArticleList({ page: page.value, pageSize: pageSize.value, excludeIds, ...searchInfo.value })
  if (res.code === 0) {
    tableData.value = res.data.list
    total.value = res.data.total
  }
}

// 重置
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 handleRowSelect = (row) => {
  selectedData.value.push(row)
  getTableData()
}

const handleRowRemove = (row) => {
  selectedData.value = selectedData.value.filter(item => item.ID != row.ID)
  getTableData()
}

// 关闭弹窗
const handleCloseDialog = () => {
  showDrawer.value = false
  emit('on-close')
}

// 提交表单
const handleSubmitDialog = async () => {
  emit('on-select', transParams.value, selectedData.value)
  showDrawer.value = false
}

// 初始化方法
const selectedData = ref([])
const transParams = ref(null) // 用于透传给调用方
const openPage = async (params, includeIds) => {
  fullscreenLoading.value = true
  transParams.value = params
  selectedData.value = []

  if (includeIds && includeIds.length > 0) {
    const res = await getArticleList({ includeIds })
    if (res && res.code === 0) {
      selectedData.value = res.data.list
    }
  }

  initSearchInfo()
  getTableData()
  showDrawer.value = true
  fullscreenLoading.value = false
}

// 对外暴露方法
defineExpose({ openPage })
</script>
