<template>
    <div class="all" ref="mescrollRef" v-infinite-scroll="getDataByScoll" style="overflow: auto">
        <div style="display: flex;align-items: center;">
            <el-input v-model="form.keyword" placeholder="输入关键字进行搜索（以空格隔开）" class="input-with-select"
                @keyup.enter="handleSearch" style="width: 80%">
                <template #append>
                    <el-button icon="Search" @click="handleSearch" />
                </template>
            </el-input>

            <el-button style="width: 20%" type="text" @click="restData">清空条件</el-button>
        </div>

        <el-date-picker style="margin-top: 20px;width: 100%;max-height: 40px" v-model="daterange" type="daterange"
            range-separator="至" value-format="YYYY-MM-DD" start-placeholder="选择报道时间" end-placeholder="选择报道时间"
            @change="handleSearch" />

        <div class="filter">
            <div class="r_tabs">
                <div class="tabItem" v-for="(item, index) in tabsList" :key="index" @click="changeTab(index)">
                    <text :style="{
                        'color': tabIndex == index ? '#409eff' : '#333',
                        fontWeight: tabIndex == index ? 'bold' : 'normal',
                    }">{{ item.name }}</text>
                    <div class="tab_line" v-if="tabIndex == index"></div>
                </div>
            </div>

            <SortButton ref="sortRef" @changeSort="changeSort"></SortButton>
        </div>

        <div class="r_list" v-loading="loading">
            <el-card v-for="(item, index) in tableData.data" :key="index" class="card">
                <template #header>
                    <div class="card_header" @click.stop="goDetail(1, item, true)">
                        <text class="card_title" v-html="item.title"></text>
                        <div class="r_point" :style="{ color: '#000' }">
                            <div class="point" :style="{ backgroundColor: item.status == 2 ? '#52C41A' : '#D9D9D9' }">
                            </div>
                            <text v-if="item.status == 0" style="color: rgba(0, 0, 0, 0.65)">草稿</text>
                            <text v-if="item.status == 1" style="color: rgba(0, 0, 0, 0.65)">未发布</text>
                            <text v-if="item.status == 2" style="color: rgba(0, 0, 0, 0.65)">已发布</text>
                            <text v-if="item.status == 3" style="color: rgba(0, 0, 0, 0.65)">审核中</text>
                        </div>
                    </div>
                </template>
                <div style="display: flex;align-items: center;" @click.stop="goDetail(1, item, true)">
                    <div style="display: flex;align-items: center;gap: 5px;" v-if="item.submitter">
                        <el-icon>
                            <UserFilled />
                        </el-icon>
                        <text>{{ item.submitter }}</text>
                    </div>

                    <div style="margin-left: 20px;" v-if="item.rating != 0 && item.rating != null">
                        <text>编辑评分：</text>
                        <text>{{ item.rating }}</text>
                    </div>
                </div>
                <template #footer>
                    <div style="display: flex;justify-content: space-between;align-items: center;height: 10px;">
                        <div>
                            <text>报道时间：</text>
                            <text>{{ item.publishTime }}</text>
                        </div>

                        <div class="option">
                            <el-button v-if="item.status == 0 || item.status == 1" type="text"
                                @click.stop="goDetail(1, item, false)">编辑</el-button>

                            <el-button v-if="item.status == 3 && Session.get('userInfoLocal').userType == '01'"
                                type="text" @click="goDetail(1, item, false)">编辑</el-button>
                            <div v-if="Session.get('userInfoLocal').userType == '01'">
                                <!-- 审核人员才有发布和撤稿 -->
                                <el-button type="text" v-if="item.status == 2"
                                    @click="doNewsPublishFn(item, 1)">撤稿</el-button>
                                <el-button type="text" v-else @click="doNewsPublishFn(item, 2)">发布</el-button>
                            </div>

                        </div>
                    </div>
                </template>
            </el-card>
        </div>

        <keep-alive>
            <DetailDrawer v-model="drawer" :data="newsData" :readOnly="readOnly" :type="newstype"
                @handleEditStatus="handleEditStatus" @doNewsPublishFn="doNewsPublishFn" @doDeleteNewsFn="doDeleteNewsFn"
                @getData="getData" />
        </keep-alive>
    </div>

</template>
<script setup lang="ts" name="loginIndex">
import { onUnmounted, onMounted, reactive, ref } from 'vue';
import { NextLoading } from '/@/utils/loading';
import { ElMessage, ElMessageBox } from 'element-plus';
import tableComponents from '/@/components/tableComponents/index.vue';
import { useRoute, useRouter } from 'vue-router';
import icon_table_filter from '/@/assets/icon_table_filter.png';
import DetailDrawer from './DetailDrawer/index.vue';
import SortButton from '/@/components/mobile/SortButton.vue';
import { Session } from '/@/utils/storage';
import { isMobileByWidth } from '/@/utils/Utils'
import {
    doNewRevoke,
    doNewSubmit,
    doNewLog,
    getNews,
    doNewsPublish,
    doDeleteNews,
    getColumn,
    getNewsScore,
    getIndustryHierarchy,
    getTagSource,
    doRecover,
} from '/@/api/api';
import preventBack from 'vue-prevent-browser-back';//组件内单独引入
import router from '/@/router';
import { highlightTitle } from '/@/utils/highlight';

const loading = ref(false)

const tabsList = ref([

    {
        name: "审核中",
        status: 3,
    },
    {
        name: "已发布",
        status: 2,
    },
    {
        name: "全部",
        status: null,
    },
])

const tabIndex = ref(0)

function changeTab(index) {
    tabIndex.value = index;
    form.value.status = tabsList.value[index].status
    getData()
}

function changeSort(sort) {
    form.value.orderBy = 'updateTime$' + sort;
    getData();
}

const form = ref({
    // orderBy: 'updateTime$desc',
    orderBy: null,
    // direction: 'desc',
    keyword: '',
    minScore: '',
    maxScore: '',
    industry: [],
});

const tableData = reactive({
    data: [],
    total: 0,
    page: 1,
    size: 10,
});

function getDataByScoll() {
    if (tableData.data.length < tableData.total) {
        tableData.page++;
        getData();
    }
}

const tableLoading = ref(false);
const daterange = ref('');
// 获取列表
async function getData() {

    // return
    if (form.value.minScore && form.value.maxScore && Number(form.value.maxScore) < Number(form.value.minScore)) {
        ElMessage.error('最高分不能小于最低分');
        return;
    }

    let _sdate = '';
    let _edate = '';
    if (daterange.value) {
        _sdate = daterange.value[0];
        _edate = daterange.value[1];
    }
    console.log('🚀 ~ getData ~ _edate:', _edate);

    const industry = form.value.industry?.length > 0 ? encodeURIComponent(JSON.stringify(form.value.industry)) : '';

    try {
        loading.value = true;
        let { code, data, total } = await getNews({
            ...form.value,
            industry,
            // page: tableData.page,
            current: tableData.page,
            size: tableData.size,
            dateline_from: _sdate || undefined,
            dateline_to: _edate || undefined,
        });
        loading.value = false;
        if (code == 200) {
            tableData.total = total;

            if (tableData.page == 1) {
                tableData.data = data;

            } else {
                tableData.data.push(...data);
            }

            tableData.data.forEach((item, index) => {
                item.columns.forEach((childItem, childIndex) => {
                    if (childIndex < 2) {
                        if (!item.columnsMin) {
                            item.columnsMin = [];
                        }
                        item.columnsMin.push(childItem);
                    }
                });
                item.title = highlightTitle(item.title, form.value.keyword);
            });
        }
    } catch (error) {
        loading.value = false;
    }
}

function handleSearch() {
    tableData.page = 1;
    getData();
}


/**
 * 上下架
 * @param item
 * @param status   1：下架 2：上架
 */
async function doNewsPublishFn(item, status) {
    let str = '请确认要下架该篇资讯？撤稿后前台将不可见本文章';
    if (status == 1) {
        str = '请确认要下架该篇资讯？撤稿后前台将不可见本文章';
    } else {
        str = '请确认已审核该篇资讯，发布后前台将展示本资讯';
    }
    ElMessageBox.confirm(str, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            let { code } =
                status == 1
                    ? await doNewRevoke({
                        id: item.id,
                        status: status,
                    })
                    : await doNewsPublish({
                        id: item.id,
                        status: status,
                    });
            if (code == 200) {
                ElMessage.success('操作成功');
                drawer.value = false;
                getData();
            }
        })
        .catch(() => { });
}

/**  管理后台需求文件0519（V1.1） start */
const drawer = ref(false);
const newsData = ref<any>();
const readOnly = ref(false);
const newstype = ref(0);
/**  管理后台需求文件0519（V1.1） end */

/**
 * 进入详情页
 * @param type 0：创建 1：编辑
 */
function goDetail(type, item, readonly) {
    readOnly.value = readonly;
    newsData.value = item;
    newstype.value = type;
    drawer.value = true;

    // router.push({
    //     path: '/detailMobile',
    //     query: {
    //         type,
    //         item,
    //         readonly,
    //     }
    // })
}

const sortRef = ref(null)

function restData() {
    form.value.keyword = null;
    form.value.industry = null;
    form.value.tag = null;
    daterange.value = null;
    form.value.minScore = null;
    form.value.maxScore = null;
    form.value.mediaId = null;
    form.value.deleted = null;

    form.value.status = null;
    form.value.rating = null;
    form.value.orderBy = null;


    sortRef.value.clearSort()

    tableData.page = 1;
    getData();
}

function handleEditStatus(val: boolean) {
    readOnly.value = val;
}
onMounted(() => {
    changeTab(0)
    // getData();
})

</script>

<style scoped lang="scss">
.all {
    display: flex;
    flex-direction: column;
    max-width: 100vw;
    height: 100vh;
    scrollbar-width: none;
    /* Firefox */
    -ms-overflow-style: none;
    /* IE and Edge 旧版本 */
}


/* 隐藏容器的滚动条 */
.all::-webkit-scrollbar {
    display: none;
    /* Chrome, Safari, Edge, Opera */
}


.filter {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 15px;
    padding: 0 5px;
}

.r_tabs {
    display: flex;
    gap: 30px;
    margin-top: 10px;


    .tabItem {
        font-size: 16px;
        color: #333;
        // font-weight: bold;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: center;
    }

    .tab_line {
        width: 20px;
        height: 5px;
        background-color: #409eff;
        border-radius: 20px;
        margin-top: 5px;
    }
}

.r_list {
    display: flex;
    flex-direction: column;
    margin-top: 20px;
    gap: 15px;
}

.card_header {
    display: flex;
    justify-content: space-between;

    .card_title {
        font-size: 15px;
        font-weight: bold;
        width: 73%;
        // overflow: hidden;
        // text-overflow: ellipsis;
        // white-space: nowrap;

        height: 43px;
        overflow: hidden;
        display: -webkit-box;
        text-overflow: ellipsis; //属性规定当文本溢出包含元素时发生的事情  text-overflow: clip|ellipsis|string; (修剪/省略号/指定字符串)
        -webkit-line-clamp: 2;
        /*要显示的行数*/
        /* autoprefixer: off */
        -webkit-box-orient: vertical; //属性规定框的子元素应该被水平或垂直排列
    }

    .r_point {
        display: flex;
        align-items: center;
        gap: 5px;
        font-weight: 400;
    }

    .point {
        width: 8px;
        height: 8px;
        border-radius: 100px;
    }
}

.card {
    box-shadow: 0 0 5px rgba($color: #474747, $alpha: 0.1);
    border-radius: 5px;
}

.option {
    display: flex;

    button {
        padding: 0 0px 0 15px;
    }
}

:deep(.highlight) {
    color: #ff0000;
    font-weight: bold;
}
</style>
