<script setup>
import {onMounted, ref} from 'vue';
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElPagination,
  ElTable,
  ElTableColumn
} from 'element-plus';
import axios from "axios";
import {useStore} from "vuex";
import {useRouter} from "vue-router";
import EditNews from "@views/news-management/EditNews.vue";

const router = useRouter();

const store = useStore();
const token = store.getters['authentication/token']

const searchTitle = ref('');
const searchPath = ref('');
const searchAuthor = ref('');
const searchSummary = ref('');
const sortOrder = ref('');

const allNewsData = ref([]);
const newsData = ref([]);

const currentPage = ref(1);
const pageSize = ref(10);
const newsCount = ref(0);
const firstTimeLoad = ref(true);

const selections = ref([]);

const editNewsDialogVisible = ref(false);
const editNewsDialogMode = ref('create');
const editId = ref("");

const searchMode = ref(false);
const loadNews = async () => {
  if (searchMode.value) {
    newsData.value = allNewsData.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
    return;
  }
  if (firstTimeLoad.value || allNewsData.value.length < (currentPage.value * pageSize) && (currentPage.value * pageSize) <= newsCount) {
    // console.error(allNewsData.value.length, currentPage.value, pageSize.value, newsCount.value)
    let params = {
      token: token,
      start: allNewsData.value.length,
      end: allNewsData.value.length + pageSize.value * 2
    }
    try {
      const response = await axios.get('/api/news', {params})
      const data = response.data
      newsCount.value = data.newsCount;
      allNewsData.value.push(...data.newsList);
      ElMessage.success('列表已刷新');
    } catch (e) {
      console.log(e)
    }
    firstTimeLoad.value = false;
  }
  newsData.value = allNewsData.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)
  // console.error((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value, newsData.value);
};

onMounted(() => {
  loadNews();

})


const handleSearch = async () => {
  const params = {
    token: token,
    title: searchTitle.value,
    author: searchAuthor.value,
    summary: searchSummary.value,
    imagePath: searchPath.value
  }

  try {
    const response = await axios.post('/api/news/search', params);
    const data = response.data;
    allNewsData.value = data.newsList;
    newsCount.value = data.newsCount;
    newsData.value = allNewsData.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
    searchMode.value = true;
    ElMessage.success('搜索成功');
  } catch (e) {
    ElMessage.error('搜索失败');
    console.error(e);
  }
};


const handleReset = async () => {
  searchTitle.value = '';
  searchPath.value = '';
  searchAuthor.value = '';
  searchSummary.value = '';
  sortOrder.value = '';

  searchMode.value = false;
  await refreshNewsList();
};

const handleCreateButton = () => {
  editNewsDialogMode.value = 'create'
  openEditNewsDialog()
};

const handleEditButton = () => {
  if (selections.value.length === 1) {
    editNewsDialogMode.value = 'edit'
    editId.value = selections.value[0].id
    openEditNewsDialog()
    return
  }
  //读取每一个selection中的选项id并新建标签页分别跳转打开编辑页面
  selections.value.forEach(selection => {
    const url = router.resolve({name: 'editNews', query: {mode: 'edit', id: selection.id}}).href;
    window.open(url, '_blank');
  });
};

// 删除按钮的处理方法
const handleDeleteButton = () => {
  if (selections.value.length === 0) {
    ElMessage.warning('请选择要删除的资讯');
    return;
  }

  ElMessageBox.confirm(
      `你是否确认要删除<span style="color: red; ">${selections.value.length}</span>条资讯`,
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
  ).then(async () => {
    try {
      for (const selection of selections.value) {
        await axios.delete(`/api/news/${selection.id}`, {params: {token: token}});
      }
      ElMessage.success('删除成功');
      // 刷新列表
      await refreshNewsList()
    } catch (e) {
      ElMessage.error('删除失败');
      console.error(e);
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

const handleSelectionChange = (newSelections) => {
  selections.value = newSelections
}

const handleEditInTable = async (index) => {
  // router.push({name: 'editNews', query: {mode: 'edit', id: newsData.value[index].id}})
    editNewsDialogMode.value = 'edit'
    editId.value = newsData.value[index].id
    openEditNewsDialog()
};

const handleDeleteInTable = async (index) => {
  try {
    await axios.delete(`/api/news/${newsData.value[index].id}`, {params: {token: token,}})
    newsData.value.splice(index, 1);
    allNewsData.value.splice(index, 1);
    newsCount.value--;
  } catch (e) {
    ElMessage.error('删除失败')
    console.error(e)
  }
};
const refreshNewsList = async () => {
  newsData.value = [];
  allNewsData.value = [];
  newsCount.value = 0;
  currentPage.value = 1;
  firstTimeLoad.value = true;
  await loadNews();
};

const openEditNewsDialog = () => {
  editNewsDialogVisible.value = true;
};

const setNewsDialogInvisible = (changed) => {
  editNewsDialogVisible.value = false;
  if (changed){
    refreshNewsList();
  }
}
</script>

<template>
  <div class="container">
    <div class="search-container">
      <el-form inline>
        <el-form-item label="新闻标题">
          <el-input v-model="searchTitle" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="新闻图片路径">
          <el-input v-model="searchPath" placeholder="请输入路径"/>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="sortOrder" placeholder="请输入排序"/>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="searchAuthor" placeholder="请输入作者"/>
        </el-form-item>
        <el-form-item label="新闻简介">
          <el-input v-model="searchSummary" placeholder="请输入简介"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="button-container">
      <el-button type="success" @click="handleCreateButton">新增</el-button>
      <el-button type="warning" @click="handleEditButton">修改</el-button>
      <el-button type="danger" @click="handleDeleteButton">删除</el-button>
    </div>

    <el-table :data="newsData" style="width: 100%;"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="title" label="新闻标题" align="center"></el-table-column>
      <el-table-column prop="author" label="作者" align="center"></el-table-column>
      <el-table-column prop="summary" label="新闻简介" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button @click="handleEditInTable(scope.$index)" type="text">修改</el-button>
          <el-button @click="handleDeleteInTable(scope.$index)" type="text">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
          @size-change="pageSize = $event;loadNews()"
          @current-change="currentPage = $event;loadNews()"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="newsCount"
          :page-sizes="[10, 20, 50, 100]"
      >
      </el-pagination>
    </div>
  </div>
  <el-dialog
      v-model="editNewsDialogVisible"
      width="60%"
      top="8vh"
      destroy-on-close
  >
    <EditNews :mode="editNewsDialogMode" :id="editId" @setNewsDialogInvisible="setNewsDialogInvisible"/>
  </el-dialog>
</template>

<style scoped>
.container {
  padding: 20px;
}

.search-container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-bottom: 20px;
}

.button-container {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.el-table {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>