<template>
    <div class="topBg">
        <!-- 页面头部 -->
        <HomePageHead></HomePageHead>
        <!-- 页面导航 -->
        <HomePageNavigation></HomePageNavigation>
    </div>
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
        <div class="inner">
            <span class="location">当前位置:</span>
            <el-breadcrumb :separator-icon="ArrowRight">
                <el-breadcrumb-item>
                    <NuxtLink to="/">首页</NuxtLink>
                </el-breadcrumb-item>
                <el-breadcrumb-item v-if="parent_children_count > 0">
                    <NuxtLink :to="`/${parent_pinyin}/index.html`"> {{ parent_name }}</NuxtLink>
                </el-breadcrumb-item>
                <el-breadcrumb-item v-if="parent_children_count == 0">
                    <NuxtLink :to="`/${parent_pinyin}/list-1.html`"> {{ parent_name }}</NuxtLink>
                </el-breadcrumb-item>
                <el-breadcrumb-item class="phone_breadcrumb_text" v-if="!routeNewsTtitle">
                    {{ routeNewsTtitle }}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
    </div>
    <!-- 资讯列表 -->
    <div class="newsDetail">
        <div class="inner">
            <div class="innerLeft">
                <div class="LeftTop">
                    <h1>{{ newsDetail.title }}</h1>
                    <p class="phone_none">
                        发布时间: <span>{{ time }}</span>
                        来源: <span>{{ newsDetail.copyfrom }}</span>
                        作者: <span>{{ newsDetail.author }}</span>
                    </p>
                </div>
                <div class="leftBottom" v-html="newsDetail.content" v-if="newsDetail.content" @click="openPreview">
                </div>
                <div v-if="previewVisible" class="preview-modal" @click="closePreview">
                    <img :src="selectedImage" alt="Preview">
                </div>
                <!-- 免责声明: -->
                <div class="disclaimer" v-if="newsDetail.copyfrom != '本网'">
                    <p>原文链接：{{ newsDetail.fromurl }}</p>
                    <p>[免责声明]本文来源于网络转载，仅供学习交流使用，不构成商业目的。 版权归原作者所有，如涉及作品内容，版权和其他问题，请在30日与本网联系，我们将第一时间处理。</p>
                </div>
                <!-- 投票 start ---------------------------------------->
                <!-- <div v-if="articleChoice">
                    <div class="index_3_box_vote" v-if="articleChoice">
                        <div class="voteTitle">投票区</div>
                        <div class="inquire">
                            <p v-if="voteList.length > 0">{{ voteList[0].survey_name }}</p>
                            <div class="radioBox">
                                投票选项
                                <div v-if="!isDisabled">
                                    <div class="radio" v-if="isRadio">
                                        <el-radio-group v-model="radio1" @change="handleRadioChange">
                                            <el-radio v-for="item in voteList" :key="item.id" :value="item.id"
                                                size="large">
                                                <span v-if="item.is_other == 0">{{ item.choice_name }}</span>
                                                <span v-else>其他</span>
                                            </el-radio>
                                        </el-radio-group>
                                        <el-input v-if="showUserChoice" v-model="userChoice" :rows="2" type="textarea"
                                            resize="none" placeholder="请输入.." />
                                    </div>
                                    <div class="checkInputBox" v-else>
                                        <el-checkbox-group v-model="check1" @change="handleCheckboxChange">
                                            <span v-for="item in voteList" :key="item.id">
                                                <span v-if="item.is_other == 0">
                                                    <el-checkbox size="large" :label="item.choice_name"
                                                        :value="item.id" />
                                                </span>
                                                <span v-else>
                                                    <el-checkbox size="large" label="其他" :value="item.id" />
                                                </span>
                                            </span>
                                        </el-checkbox-group>
                                        <el-input v-if="showUserChoice" v-model="userChoice" :rows="2" type="textarea"
                                            resize="none" placeholder="请输入.." />
                                    </div>
                                </div>
                                投票结果
                                <div class="inquireData" v-else>
                                    <div v-for="item in websiteSurveyData.data" :key="item.id">
                                        <div class="inquireDataItem active" v-if="item.status == 1">
                                            <div class="inquireDataItemTitle">
                                                <span v-if="item.choice_name == ''">其他</span>
                                                <span v-else>{{ item.choice_name }}</span>
                                            </div>
                                            <div class="inquireDataItemNum">{{ item.results }}票</div>
                                        </div>
                                        <div class="inquireDataItem" v-else>
                                            <div class="inquireDataItemTitle">
                                                <span v-if="item.choice_name == ''">其他</span>
                                                <span v-else>{{ item.choice_name }}</span>
                                            </div>
                                            <div class="inquireDataItemNum">{{ item.results }}票</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="btn">
                                <button class="voting" @click="addWebsiteSurvey" :disabled="isDisabled"
                                    v-if="!isDisabled">投票</button>
                            </div>
                        </div>
                    </div>
                </div> -->
                <!-- 投票 end ---------------------------------------->
                <!-- <div class="recommendRead" v-if="newsDetail.commendArticle != false">
                    <div class="recommendReadTitle">
                        <span class="read_title">
                            推荐阅读
                        </span>
                    </div>
                    <div class="recommendReadList">
                        <div class="recommendReadListTitle" v-for="(item, index) in newsDetail.commendArticle"
                            :key="item.id">
                            <a :href="`/${item.alias_pinyin}/${item.id}.html`" v-if="index < 3">
                                {{ item.title }}
                            </a>
                        </div>
                    </div>
                </div> -->
            </div>
            <div class="innerRight">
                <!-- 热点资讯1 -->
                <div class="hotList1">
                    <DetailHotNews></DetailHotNews>
                </div>
                <!-- 热点资讯2 -->
                <!-- <div class="hotList2">
                    <DetailHotNews2></DetailHotNews2>
                </div> -->
            </div>
        </div>
    </div>
    <!-- 页面底部 -->
    <HomeFoot></HomeFoot>
</template>

<script setup>
//1.页面依赖 start ---------------------------------------->
import { onMounted } from 'vue'
import { ElBreadcrumb, ElBreadcrumbItem, ElRadio, ElRadioGroup, ElCheckbox, ElCheckboxGroup, ElMessage, ElInput } from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'

const nuxtApp = useNuxtApp();
const axios = nuxtApp.$axios;

//1.1 获得跳转过来的id
const route = useRoute();
//获得详情id
const articleId = parseInt(route.params.id); //获得该页面的id

//获得当前的完整路径
const fullPath = route.path;
//拆分，取出来中间这一段，然后提取数字部分
const segments = fullPath.split('/');
const targetSegment = segments[1];
// const numberPart = targetSegment.match(/\d+$/)?.[0]; 
// let routeId = 20 //排除路径错误可以打开这个
// const routeId = numberPart;
let routeId;
//通过导航路径反向查询导航id
const getRouteId = await requestDataPromise('/web/getWebsiteRoute', {
    method: 'GET',
    query: {
        'pinyin': targetSegment,
    },
});
if (getRouteId.code == 200) {
    routeId = getRouteId.data.category_id
} else {
    console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
    console.log("错误位置：通过url路径查询导航池id")
    console.log("后端错误反馈：", getRouteId.message)
    console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
}


//1.2 获得父级栏目的名称、id
const parent_name = ref([]);
const parent_id = ref([]);
const parent_pinyin = ref("");
const parent_children_count = ref(0)
let getParentNav = async () => {
    const listData = await requestDataPromise('/web/getOneWebsiteCategory', {
        method: 'GET',
        query: {
            'catid': routeId
        },
    });
    console.log("获取父级栏目数据")
    console.log(listData)
    if (listData.code == 200) {
        console.log(listData.data);
        parent_name.value = listData.data.alias;
        parent_id.value = listData.data.parent_id;
        parent_pinyin.value = listData.data.aLIas_pinyin;
        parent_children_count.value = listData.data.children_count;

    } else {
        console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
        console.log("错误位置：获取面包屑导航")
        console.log("后端错误反馈：", listData.message)
        console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
    }
}
//获得父级栏目详情
getParentNav();
//1.页面依赖 end ---------------------------------------->

//2.页面数据 start ---------------------------------------->
//2.1 资讯详情
const newsDetail = ref({})
const routeNewsTtitle = ref("");
//2.2 发布日期
const time = ref("");
//2.3 路径
const routLevelTitle = ref("");
const routLevelId = ref("");
//是否展示投票
const articleChoice = ref(false);
//2.4获取详情
async function getPageData() {
    const mkdata = await requestDataPromise('/web/selectWebsiteArticleInfo', {
        method: 'GET',
        query: {
            'articleid': articleId
        },
    });
    if (mkdata.code == 200) {
        console.log('资讯详情1111', mkdata.data)
        //判断是否显示投票
        if (mkdata.data.is_survey == 1) {
            console.log("本篇文章含有投票！")
            articleChoice.value = true;
            getVoteList();
        }
        //获取内容
        newsDetail.value = mkdata.data;
        //获取路径
        // routLevelTitle.value = newsDetail.value.cat_name;
        // routLevelId.value = newsDetail.value.category_id;
        //获取发布时间
        // time.value = newsDetail.value.updated_at.split(' ')[0];
        //修正标题长度
        if (newsDetail.value.title.length >= 30) {
            routeNewsTtitle.value = newsDetail.value.title.substr(0, 30) + "...";
        } else {
            routeNewsTtitle.value = newsDetail.value.title
        }
    } else {
        console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
        console.log("错误位置：获取详情内容")
        console.log("后端错误反馈：", mkdata.message)
        console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
    }
}
getPageData();

//2.5 获得广告
//广告列表
let adImg1 = ref([]);
// async function getAdData(){
//     const adData = await requestDataPromise('/web/getWebsiteAdvertisement',{method:'GET',query:{'ad_tag':'DETAIL'}});
//     if(adData.code==200){
//         for(let item of adData.data){
//             if(item.ad_tag == 'DETAIL_0001'){
//                 adImg1.value = item;
//             }
//         }
//     }else{
//         console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
//         console.log("错误位置：获取详情页广告列表")
//         console.log("后端错误反馈：",adData.message)
//         console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
//     }
// }
// getAdData();

onMounted(async () => {
    const { $webUrl, $CwebUrl } = useNuxtApp();
    //广告1
    let url = `${$webUrl}/web/getWebsiteAdvertisement?ad_tag=snzxw_detail_0001`
    const responseAd1 = await fetch(url, {
        headers: {
            'Content-Type': 'application/json',
            'Userurl': $CwebUrl,
            'Origin': $CwebUrl
        }
    });
    const resultAd1 = await responseAd1.json();
    adImg1.value = resultAd1.data[0];
})

//2.页面数据 end ---------------------------------------->

//3.设置seo信息 start---------------------------------------->
//3.1 设置seo信息
const setData = await requestDataPromise('/web/selectWebsiteArticleInfo', {
    method: 'GET',
    query: {
        'articleid': articleId
    },
});
if (setData.code == 200) {
    let seoTitle = setData.data.title;
    let seoDescription = setData.data.introduce;
    let seoKeywords = setData.data.keyword;
    let seoSuffix = setData.data.suffix;
    let seoName = setData.data.website_name;

    useSeoMeta({
        title: seoTitle + "_" + seoName + "_" + seoSuffix,
        meta: [
            { name: 'description', content: seoDescription + "_" + seoName + "_" + seoSuffix, tagPriority: 10 },
            { name: 'keywords', content: seoKeywords + "_" + seoName + "_" + seoSuffix, tagPriority: 10 }
        ]
    });
} else {
    console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
    console.log("错误位置：设置详情页面SEO数据")
    console.log("后端错误反馈：", setData.message)
    console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
}
//3.设置seo信息 end---------------------------------------->

//4.投票 start---------------------------------------->
const radio1 = ref(''); //单选
const check1 = ref([]); //多选
const isDisabled = ref(false);//是否禁用提交按钮
const isRadio = ref(true);//是否渲染单选

const userSurId = ref('');//投票属于哪一篇文章
const userChoice = ref('');//用于判断用户选择了其他选项以后，输入的值
const userIsChoice = ref('');//用于判断其他选项目前是什么值
const showUserChoice = ref(false);//是否显示其他输入框
const websiteSurveyData = ref([]);//投票结果

//3.2获得投票列表
let voteList = ref([]);
async function getVoteList() {
    const voteData = await requestHome('/web/getWebsiteSurvey', { method: 'GET', query: { 'art_id': articleId } });
    console.log(778899)
    console.log(voteData)
    if (voteData.code == 200) {
        voteList.value = voteData.data;
        console.log(voteList.value)
        //判断显示单选还是多选
        //survey_type 0是单选 1是多选
        if (voteData.data[0].survey_type == 0) {
            isRadio.value = true;
            console.log("1111")
        } else {
            isRadio.value = false;
        }
        //把最后一个的值拿出来 用于判断用户是否选择了其他
        for (let item of voteData.data) {
            //如果含有其他
            if (item.is_other == 1) {
                userIsChoice.value = item.id;
            }
        }
        //用户投票属于哪一篇文章
        userSurId.value = voteData.data[0].sur_id;

    } else {
        console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
        console.log("错误位置：首页投票")
        console.log("后端错误反馈：", voteData.message)
        console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
    }
}


//3.2当用户选择了选项，判断是否展示其他输入框
const handleRadioChange = (value) => {
    if (value == userIsChoice.value) {
        showUserChoice.value = true;
    } else {
        showUserChoice.value = false;
    }
}

const handleCheckboxChange = (value) => {
    if (value.includes(userIsChoice.value)) {
        showUserChoice.value = true;
    } else {
        showUserChoice.value = false;
    }
}

//3.2发起投票
async function addWebsiteSurvey() {
    //判断当前是单选还是多选
    console.log(isRadio.value)
    if (isRadio.value) {
        console.log("用户单选！")
        if (radio1.value != '') {
            //先判断一下是否使用了其他选项
            if (showUserChoice.value) {
                if (userChoice.value != '') {
                    //文章id
                    // console.log(userSurId.value)
                    // 用户输入的值
                    // console.log(userChoice.value)
                    //如果使用了其他，其他的选项需要增加进去
                    const ChoiceData = await requestHome('/web/addWebsiteSurveyOption', {
                        method: 'GET',
                        query: {
                            'sur_id': userSurId.value,//投票的新闻id
                            'choice_name': userChoice.value,//投票的选项id
                        }
                    });
                    if (ChoiceData.code == 200) {
                        //提交完其他选项以后，再正式发起投票
                        const mkData = await requestHome('/web/addWebsiteSurveyVote', {
                            method: 'GET',
                            query: {
                                'sur_id': userSurId.value,
                                'choice_id': ChoiceData.data
                            }
                        });
                        if (mkData.code == 200) {
                            ElMessage.success('投票成功！')
                            //把投票结果显示到页面上 禁用投票按钮
                            isDisabled.value = true;
                            websiteSurveyData.value = mkData.data;
                            //遍历一下，把用户选中的那个设置status为1
                            let data = mkData.data;
                            //遍历一下，把用户选中的那个设置status为1
                            for (let item of data.data) {
                                for (let i of data.choice) {
                                    if (item.id == i) {
                                        console.log(item.id)
                                        item.status = 1;
                                    }
                                }
                            }
                            websiteSurveyData.value = data;
                        } else {
                            ElMessage.error(mkData.message)
                        }
                    } else {
                        ElMessage.error('其他投票失败！')
                    }
                } else {
                    ElMessage.error('请输入选项内容！')
                }
            } else {
                //如果没选择其他，直接提交选择的内容
                const mkData = await requestHome('/web/addWebsiteSurveyVote', {
                    method: 'GET',
                    query: {
                        'sur_id': userSurId.value,
                        'choice_id': radio1.value
                    }
                });
                if (mkData.code == 200) {
                    ElMessage.success('投票成功！')
                    //把投票结果显示到页面上 禁用投票按钮
                    isDisabled.value = true;
                    let data = mkData.data;
                    //遍历一下，把用户选中的那个设置status为1
                    for (let item of data.data) {
                        for (let i of data.choice) {
                            if (item.id == i) {
                                item.status = 1;
                            }
                        }
                    }
                    websiteSurveyData.value = data;
                } else {
                    ElMessage.error('投票失败！')
                }
            }
        } else {
            ElMessage.error('请选择一个选项')
        }
    } else {
        console.log("多选！")
        //多选
        if (check1.value != []) {
            //先判断一下是否使用了其他选项
            if (showUserChoice.value) {
                if (userChoice.value != '') {
                    //判断用户是否只选择了一个其他
                    if (check1.value.length == 1) {
                        const ChoiceData = await requestDataPromise('/web/addWebsiteSurveyOption', {
                            method: 'GET',
                            query: {
                                'sur_id': userSurId.value,//投票的新闻id
                                'choice_name': userChoice.value,//用户输入的其他选项文字
                            }
                        });
                        if (ChoiceData.code == 200) {
                            //提交完其他选项以后，再正式发起投票
                            const mkData = await requestDataPromise('/web/addWebsiteSurveyVote', {
                                method: 'GET',
                                query: {
                                    'sur_id': userSurId.value,
                                    'choice_id': ChoiceData.data
                                }
                            });
                            if (mkData.code == 200) {
                                ElMessage.success('投票成功！')
                                //把投票结果显示到页面上 禁用投票按钮
                                isDisabled.value = true;
                                websiteSurveyData.value = mkData.data;
                                //遍历一下，把用户选中的那个设置status为1
                                let data = mkData.data;
                                //遍历一下，把用户选中的那个设置status为1
                                for (let item of data.data) {
                                    for (let i of data.choice) {
                                        if (item.id == i) {
                                            console.log(item.id)
                                            item.status = 1;
                                        }
                                    }
                                }
                                websiteSurveyData.value = data;
                            } else {
                                ElMessage.error(mkData.message)
                            }
                        } else {
                            ElMessage.error('其他投票失败！')
                        }

                    } else {
                        //用户选择了除了其他以外，还包括别的选项
                        const ChoiceData = await requestDataPromise('/web/addWebsiteSurveyOption', {
                            method: 'GET',
                            query: {
                                'sur_id': userSurId.value,//投票的新闻id
                                'choice_name': userChoice.value,//用户输入的其他选项文字
                            }
                        });
                        if (ChoiceData.code == 200) {
                            let data = check1.value;
                            //找到多选的数组，把其他默认值给替换掉
                            for (let i = 0; i < data.length; i++) {
                                if (data[i] == userIsChoice.value) {
                                    data[i] = ChoiceData.data;
                                }
                            }
                            let jsonArray = JSON.stringify(data);
                            //提交完其他选项以后，再正式发起投票
                            const mkData = await requestDataPromise('/web/addWebsiteSurveyVote', {
                                method: 'GET',
                                query: {
                                    'sur_id': userSurId.value,
                                    'choice_id': jsonArray
                                }
                            });

                            if (mkData.code == 200) {
                                ElMessage.success('投票成功！')
                                //把投票结果显示到页面上 禁用投票按钮
                                isDisabled.value = true;
                                websiteSurveyData.value = mkData.data;
                                //遍历一下，把用户选中的那个设置status为1
                                let data = mkData.data;
                                //遍历一下，把用户选中的那个设置status为1
                                for (let item of data.data) {
                                    for (let i of data.choice) {
                                        if (item.id == i) {
                                            //console.log(item.id)
                                            item.status = 1;
                                        }
                                    }
                                }
                                websiteSurveyData.value = data;
                            } else {
                                ElMessage.error(mkData.message)
                            }
                        } else {
                            ElMessage.error('其他投票失败！')
                        }

                    }
                } else {
                    ElMessage.error('请输入选项内容！')
                }
            } else {
                let jsonArray = JSON.stringify(check1.value);
                //如果没选择其他，直接提交选择的内容
                const mkData = await requestDataPromise('/web/addWebsiteSurveyVote', {
                    method: 'GET',
                    query: {
                        'sur_id': userSurId.value,
                        'choice_id': jsonArray
                    }
                });
                if (mkData.code == 200) {
                    ElMessage.success('投票成功！')
                    //把投票结果显示到页面上 禁用投票按钮
                    isDisabled.value = true;
                    websiteSurveyData.value = mkData.data;
                    //遍历一下，把用户选中的那个设置status为1
                    let data = mkData.data;
                    //遍历一下，把用户选中的那个设置status为1
                    for (let item of data.data) {
                        for (let i of data.choice) {
                            if (item.id == i) {
                                console.log(item.id)
                                item.status = 1;
                            }
                        }
                    }
                    websiteSurveyData.value = data;
                } else {
                    ElMessage.error('投票失败！')
                }
            }
        } else {
            ElMessage.error('请选择一个选项')
        }
    }
}
//4.投票 end---------------------------------------->

//5.页面图片放大 start---------------------------------------->
const previewVisible = ref(false)
const selectedImage = ref(' ')

const openPreview = (event) => {
    if (event.target.tagName === 'IMG') {
        selectedImage.value = event.target.src;
        previewVisible.value = true;
    }
}
const closePreview = () => {
    previewVisible.value = false;
}
//5.页面图片放大 end---------------------------------------->
</script>

<style lang="less" scoped>
@import url('@/assets/css/detail.less');
</style>
