<script setup name="WarResearchReport">
import {computed, nextTick, onMounted, reactive,ref} from 'vue'
import apiReport from '@/api/report'
import {reportExternalInterface} from '@/api/reportExternal'
import moment from 'moment'
import _ from 'lodash'
import { showToast,showDialog,Dialog } from 'vant';
import { useRouter,useRoute } from 'vue-router';

const router = useRouter()
const route = useRoute()


const isReportWarResearch = computed(() => {
    return route.path === '/war_research_report/list'
})
//睿思
const isRise = computed(()=> {
    return isReportWarResearch.value && listState.reportType===2
})
//是否显示一键清空选项
const showCleanFilterBox=computed(()=>{
    if(isClickClose.value) return false
    if(
        listState.classifys.length||
        listState.permissions.length
    ) return true
})


const isClickClose=ref(false)//是否点击过关闭一键清空模块
function handleCleanFilter(){
    listState.classifys=[]
    listState.permissions=[]

    listState.keyWord=''
    showMoreFilter.value = false
    refreshList()
}



const classifyOptions = ref([])
const permissionOptions = ref([])
async function getClassify(type='') {

    const res = await reportExternalInterface.getClasssify()
    if (res.Ret !== 200) return 

    classifyOptions.value = res.Data||[];
    filterEmpty(classifyOptions.value)

    if(type === 'init') {
        // listState.classifys = collectClassifyOpts.value.length ? collectClassifyOpts.value.map(_ => _.Id) : [];
        getList()
        handleShowFilter()
    }
}
getClassify('init')
function filterEmpty(arr) {
    arr.length && arr.forEach(item => {
        item.Children.length && filterEmpty(item.Children)
        if(!item.Children.length) {
            item.Children = null
        }
    })
}
async function getPermissionList() {
    const res = await reportExternalInterface.getPermission()

    if(res.Ret !== 200) return
    permissionOptions.value = res.Data || []
    filterEmpty(permissionOptions.value)
}
getPermissionList()


//收藏分类 只用在战研报告
const collectClassifyOpts = computed(() => {
    return isReportWarResearch.value ? findCollectItem(classifyOptions.value) : []
})

function findCollectItem(arr) {
    let collectArr = []
    function traverse(node) {
        if (node.IsCollect === 1&&!node.Children?.length) {
            collectArr.push(node);
        }
        if (node.Children && node.Children.length) {
            node.Children.forEach(child => traverse(child));
        }
    }

    arr.forEach(item => traverse(item));

    return collectArr
}


const listState = reactive({
    reportType: 1,
    classifys: [],   
    permissions:[],
    keyWord:'',
    list:[],
    page:1,
    pageSize:20,
    finished:false,
    loading:false
})
async function getList(){
    const res = isRise.value
        ? await reportExternalInterface.getRiseReportList({
            ChartPermissionIdList: listState.permissions.join(','),
            Keyword: listState.keyWord,
            PageSize: listState.pageSize,
            CurrentIndex: listState.page,
            ClassifyIdList:  listState.classifys.join(','),
            OrderField: '',
            OrderType: ''
          })
        : await reportExternalInterface.getDocList({
            DocumentType: isReportWarResearch.value ? 2 : 1,
            ChartPermissionIdList: listState.permissions.join(','),
            ClassifyIdList:  listState.classifys.join(','),
            Keyword: listState.keyWord,
            PageSize: listState.pageSize,
            CurrentIndex: listState.page,
            OrderField: '',
            OrderType: ''
          })

        if(res.Ret !== 200) return 
        listState.loading=false
        if(!res.Data){
            listState.finished=true
            return
        }
        
        listState.finished=res.Data.Paging.IsEnd
        const arr=res.Data.List||[]
        listState.list= listState.page < 2 ? arr : [...listState.list,...arr]
}
function onLoad(){
    listState.page++
    getList()
}
function refreshList(){
    document.documentElement.scrollTop=0
    listState.page=1
    listState.list=[]
    listState.finished=false
    getList()
}
function handleReportChange() {
    listState.keyWord = '';
    listState.loading = true;
    // listState.permissions = [];
    showMoreFilter.value = false
    refreshList()
}


//筛选项弹窗
const showMoreFilter=ref(false)
const permissionDropMenuIns = ref(null)
const clasifyDropMenuIns = ref(null)
function handleShowFilter() {
    if(showMoreFilter.value) return 
    selectPermissionVal.value=_.cloneDeep(listState.permissions)
    selectClassifyVal.value=_.cloneDeep(listState.classifys)
    showMoreFilter.value=true
    nextTick(()=>{
        setTimeout(() => {
            permissionDropMenuIns.value?.toggle(true)
        }, 100);
    })
}

const selectPermissionVal = ref([])
function handleChangeSelectPermission(item) {
    selectPermissionVal.value.includes(item.chart_permission_id) 
        ? selectPermissionVal.value.splice(selectPermissionVal.value.findIndex(_ => _===item.chart_permission_id),1)
        : selectPermissionVal.value.push(item.chart_permission_id)

}
function handleConfirmFilter() {
    console.log(selectClassifyVal.value)
    listState.classifys = selectClassifyVal.value;
    listState.permissions = selectPermissionVal.value;
    refreshList()
    showMoreFilter.value=false
}


const selectClassifyVal = ref([])
function handleChangeClassify(item) {
    if(item.Children?.length) {
        item.isSlide = !item.isSlide 
    }else {
        selectClassifyVal.value.includes(item.Id) 
        ? selectClassifyVal.value.splice(selectClassifyVal.value.findIndex(_ => _===item.Id),1)
        : selectClassifyVal.value.push(item.Id)

    }
}
async function handleChangeCollect(item) {
    const res = await reportExternalInterface.collectClassify({
        ClassifyId: item.Id
    })

    if(res.Ret !== 200) return
    item.IsCollect = item.IsCollect?0:1
    showToast(item.IsCollect===1?'收藏成功':'取消收藏成功')
}

//报告收藏是报告分类收藏 神奇的设计
async function handleChangeReportClassifyCollect(item) {

    item.IsCollect === 1 && await showDialog({
        title: '提示',
        message: '确认取消收藏该报告分类吗？',
        showCancelButton:true
    })

    let ClassifyId = isRise.value ? (item.ClassifyIdThird||item.ClassifyIdSecond||item.ClassifyIdFirst) : item.ClassifyId;
    const res = await reportExternalInterface.collectClassify({
        ClassifyId
    })

    if(res.Ret !== 200) return
    item.IsCollect = item.IsCollect?0:1
    
    listState.list.forEach(_ => {
        let reportClssifyId = isRise.value ? (_.ClassifyIdThird||_.ClassifyIdSecond||_.ClassifyIdFirst) : _.ClassifyId;
        if(ClassifyId===reportClssifyId) {
            _.IsCollect = item.IsCollect;
        }
    })
    showToast(item.IsCollect===1?'收藏报告分类成功':'取消收藏成功')
    getClassify()
}



// 跳转详情
function goDetail(item){
    console.log(item);
    if(isRise.value) { //普通报告预览
        router.push({
            path:"/report/preview",
            query:{
                id:item.Id
            }
        })
    }else {
        router.push({
            path:"/external_report/preview",
            query:{
                id:item.OutsideReportId
            }
        })
    }
}

</script>

<template>
    <div class="report-list-page">
        <div class="sticky-box">
            <div class="clear-filter-box" v-if="showCleanFilterBox">
                <span>想要清空所有筛选项？试试</span>
                <span @click="handleCleanFilter" style="display:flex;align-items:center">
                    <span style="color:#0052D9">一键清空</span>
                    <img class="rocket" src="@/assets/imgs/icon_rocket.png" alt="">
                </span>
                <van-icon name="cross" class="close-icon" @click="isClickClose=true"/>
            </div>

            <van-tabs 
                v-if="isReportWarResearch"
                v-model:active="listState.reportType" 
                type="card"
                border
                @change="handleReportChange"
            >
                <van-tab title="PCI研报" :name="1"/>
                <van-tab title="睿思研报" :name="2"/>
            </van-tabs>

            <div class="top-box">
                <van-search
                    v-model="listState.keyWord"
                    style="flex:1"
                    shape="round"
                    placeholder="请输入报告标题或创建人"
                    @search="refreshList"
                />

                <div
                    :class="['menu-icon',{
                        'active': listState.MsgIsSend||listState.publishStatus
                    }]" 
                    @click="handleShowFilter"
                >
                    <svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M30.283 23.977L40.824 9.5685C41.3719 8.81954 41.6002 7.88381 41.459 6.96667C41.3177 6.04952 40.8184 5.22589 40.0705 4.6765C39.4715 4.23699 38.7479 4 38.005 4H9.995C8.065 4 6.5 5.567 6.5 7.5C6.5 8.244 6.7365 8.9685 7.1755 9.5685L17.717 23.977V42.5C17.717 43.3285 18.3875 44 19.215 44C19.6125 43.9996 19.9935 43.8414 20.2743 43.5601C20.5552 43.2788 20.7128 42.8975 20.7125 42.5V23.486C20.7125 23.1675 20.611 22.857 20.423 22.5995L9.592 7.7955C9.53761 7.72096 9.50489 7.63283 9.49745 7.54085C9.49001 7.44887 9.50814 7.35663 9.54984 7.27431C9.59155 7.192 9.65519 7.12281 9.73375 7.0744C9.81231 7.02599 9.90272 7.00024 9.995 7H38.005C38.0973 7.00015 38.1878 7.02586 38.2664 7.07427C38.345 7.12268 38.4086 7.1919 38.4503 7.27426C38.492 7.35663 38.51 7.44892 38.5025 7.54092C38.4949 7.63292 38.4621 7.72104 38.4075 7.7955L27.5765 22.5995C27.3884 22.8568 27.287 23.1673 27.287 23.486V38.271C27.287 39.0995 27.9575 39.771 28.785 39.771C28.9819 39.7709 29.1768 39.732 29.3586 39.6565C29.5404 39.5811 29.7056 39.4705 29.8447 39.3312C29.9838 39.192 30.0941 39.0266 30.1693 38.8447C30.2445 38.6628 30.2831 38.4678 30.283 38.271V23.977Z" fill="currentColor"/>
                    </svg>
                </div>
            </div>

            <template v-if="showMoreFilter">
                <van-dropdown-menu :close-on-click-overlay="false" :close-on-click-outside="false">
                    <van-dropdown-item title="品种标签" ref="permissionDropMenuIns">
                        <div class="drop-opt-box">
                            <ul class="list">
                                <li 
                                    :class="['item',selectPermissionVal.includes(item.chart_permission_id)?'active':'']" 
                                    v-for="item in permissionOptions" 
                                    :key="item.chart_permission_id"
                                    @click="item.isSlide = !item.isSlide"
                                >
                                    <div class="list-top">
                                        <h4>{{item.permission_name}}</h4>
                                        <van-icon 
                                            v-if="item.Children" 
                                            :name="!item.isSlide?'arrow-up':'arrow-down'" 
                                        />
                                    </div>
                                    <ul class="sub-list" v-if="item.Children&&!item.isSlide">
                                        <li 
                                            :class="['sub-item',{'active':selectPermissionVal.includes(subItem.chart_permission_id)}]" 
                                            v-for="subItem in item.Children"
                                            :key="subItem.chart_permission_id"
                                            @click.stop="handleChangeSelectPermission(subItem)"
                                        >{{subItem.permission_name}}</li> 
                                    </ul>
                                </li>
                                <li class="item" style="height:0"></li>
                            </ul>
                            <div class="bot-btn-box">
                                <div class="btn cancel-btn" @click="showMoreFilter=false">取消</div>
                                <div class="btn confirm-btn" @click="handleConfirmFilter">确定</div>
                            </div>
                        </div>
                    </van-dropdown-item>
                    <van-dropdown-item title="全部分类" ref="clasifyDropMenuIns">
                        <div class="drop-opt-box classify-box">
                            <ul class="list">
                                <li 
                                    :class="['item',
                                        {'active':selectClassifyVal.includes(item.Id)&&!item.Children?.length},
                                    ]" 
                                    v-for="item in classifyOptions" 
                                    :key="item.Id"
                                    @click="handleChangeClassify(item)"
                                >
                                    <div class="list-top">
                                        <h4>{{item.ClassifyName}}</h4>
                                        <van-icon 
                                            v-if="item.Children" 
                                            :name="item.isSlide?'arrow-up':'arrow-down'" 
                                        />
                                        
                                        <svg-icon
                                            v-else-if="!item.Children&&isReportWarResearch"
                                            :name="item.IsCollect?'collect_ico':'cancel_collect_ico'"
                                            size="20px"
                                            @click.stop="handleChangeCollect(item)"
                                        />
                                        
                                    </div>
                                    <ul class="classify-sub-list" v-if="item.Children&&item.isSlide">
                                        <li 
                                            :class="['sub-item',
                                                {'active':selectClassifyVal.includes(subItem.Id)&&!subItem.Children?.length}
                                            ]" 
                                            v-for="subItem in item.Children"
                                            :key="subItem.Id"
                                            @click.stop="handleChangeClassify(subItem)"
                                        >

                                            <div class="list-top">
                                                <span>{{subItem.ClassifyName}}</span>
                                                <van-icon 
                                                    v-if="subItem.Children" 
                                                    :name="subItem.isSlide?'arrow-up':'arrow-down'" 
                                                />
                                                
                                                <svg-icon
                                                    v-else-if="!subItem.Children&&isReportWarResearch"
                                                    :name="subItem.IsCollect?'collect_ico':'cancel_collect_ico'"
                                                    size="20px"
                                                    @click.stop="handleChangeCollect(subItem)"
                                                />
                                                
                                            </div>

                                            <ul class="classify-sub-list" v-if="subItem.Children&&subItem.isSlide">
                                                <li 
                                                    :class="['sub-item',
                                                        {'active':selectClassifyVal.includes(thirdItem.Id)}
                                                    ]" 
                                                    v-for="thirdItem in subItem.Children"
                                                    :key="thirdItem.Id"
                                                    @click.stop="handleChangeClassify(thirdItem)"
                                                >

                                                    <div class="list-top">
                                                        <span>{{thirdItem.ClassifyName}}</span>
                                                        <van-icon 
                                                            v-if="thirdItem.Children" 
                                                            :name="thirdItem.isSlide?'arrow-up':'arrow-down'" 
                                                        />
                                                        
                                                        <svg-icon
                                                            v-else-if="!thirdItem.Children&&isReportWarResearch"
                                                            :name="thirdItem.IsCollect?'collect_ico':'cancel_collect_ico'"
                                                            size="20px"
                                                            @click.stop="handleChangeCollect(thirdItem)"
                                                        />
                                                        
                                                    </div>
                                                </li> 
                                            </ul>
                                        </li> 
                                    </ul>
                                </li>
                            </ul>
                            
                            <div class="bot-btn-box">
                                <div class="btn cancel-btn" @click="showMoreFilter=false">取消</div>
                                <div class="btn confirm-btn" @click="handleConfirmFilter">确定</div>
                            </div>
                        </div>
                    </van-dropdown-item>
                    <van-dropdown-item title="收藏分类" ref="collectDropMenuIns" v-if="isReportWarResearch">
                        <div class="drop-opt-box classify-box">
                            <ul class="list" v-if="collectClassifyOpts.length">
                                <li 
                                    :class="['item',
                                        {'active':selectClassifyVal.includes(item.Id)},
                                    ]" 
                                    v-for="item in collectClassifyOpts" 
                                    :key="item.Id"
                                    @click="handleChangeClassify(item)"
                                >
                                    <div class="list-top">
                                        <h4>{{item.ClassifyName}}</h4>

                                        <svg-icon
                                            :name="item.IsCollect?'collect_ico':'cancel_collect_ico'"
                                            size="20px"
                                            @click.stop="handleChangeCollect(item)"
                                        />
                                        
                                    </div>
                                </li>
                            </ul>

                            <div class="no-list" v-else>
                                暂无收藏
                            </div>         
                            
                            <div class="bot-btn-box">
                                <div class="btn cancel-btn" @click="showMoreFilter=false">取消</div>
                                <div class="btn confirm-btn" @click="handleConfirmFilter">确定</div>
                            </div>
                        </div>
                    </van-dropdown-item>
                </van-dropdown-menu>
            </template>

        </div>
        <van-list
            v-model:loading="listState.loading"
            :finished="listState.finished"
            :offset="100"
            :finished-text="listState.list.length>0?'没有更多了':'暂无相关报告'"
            @load="onLoad"
            :immediate-check="false"
        >   
            <img v-if="listState.list.length==0&&listState.finished" class="list-empty-img" src="https://hzstatic.hzinsights.com/static/ETA_mobile/empty_img.png" alt="">
            <ul class="list-wrap">
                <li
                    v-for="item in listState.list" 
                    :key="item.Id"
                    class="select-text-disabled item"
                    @click="goDetail(item)"
                >   
                    <div class="list-top">
                        <h2 class="van-ellipsis title">
                            {{item.Title}}
                            <template v-if="isRise">
                                ({{ moment(item.MsgSendTime||item.PublishTime||item.CreateTime).format('MMDD')}})
                            </template>
                            <template v-else>
                                ({{ moment(item.ReportUpdateTime).format('MMDD') }})
                            </template>

                            <svg-icon
                                v-if="isReportWarResearch"
                                class="handle-icon"
                                :name="item.IsCollect?'collect_ico':'cancel_collect_ico'"
                                size="20px"
                                @click.stop="handleChangeReportClassifyCollect(item)"
                            />
                        </h2>
                    </div>
                    <p class="van-multi-ellipsis--l2 des">{{item.Abstract}}</p>
                    <div class="bot-info">
                        <div class="time">
                            <span style="margin-right:2px">{{moment(item.ModifyTime).format('YYYY-MM-DD')}}</span>
                        </div>
                        <span class="author van-ellipsis">{{item.SysUserName}}</span>
                    </div>
                </li>
            </ul>
        </van-list>
    </div>

</template>

<style lang="scss" scoped>
.sticky-box{
    position: sticky;
    top: 0;
    z-index: 99;
    border-bottom: 1px solid #E7E7E7;
    background: #fff;
    :deep(.van-dropdown-menu__bar){
        box-shadow: none;
        border-bottom: 1px solid $border-color;
    }
    :deep(.van-tabs) {
        padding-top: 20px;
    }
    .bot-btn-box{
        border-top: 1px solid $border-color;
        padding: 32px;
        display: flex;
        justify-content: space-between;
        .btn{
            width: 327px;
            height: 80px;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 12px;
            font-size: 32px;
            font-weight: 600;
        }
        .cancel-btn{
            background-color: #F2F3FF;
            color: $theme-color;
        }
        .confirm-btn{
            background-color: $theme-color;
            color: #fff;
        }
    }

    .clear-filter-box{
        padding: 0 34px;
        height: 84px;
        background-color: #F2F3FF;
        display: flex;
        align-items: center;
        font-size: 28px;
        position: relative;
        .rocket{
            width: 48px;
            height: 48px;
        }
        .close-icon{
            position: absolute;
            right: 34px;
            top: 50%;
            transform: translateY(-50%);
        }
    }

}
.top-box{
    padding: 30px 34px;
    background-color: #fff;
    display: flex;
    align-items: center;
    .menu-icon{
        width: 70px;
        height: 70px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #F2F6FA;
        margin-left: 20px;
        border-radius: 50%;
        &.active{
            color: $theme-color;
        }
        svg{
            width: 48px;
            height: 48px;
        }
    }
    :deep(.van-search){
        padding: 0;
    }
}


.list-wrap{
    padding: 30px 34px;
    .item{
        padding: 20px;
        margin-bottom: 20px;
        border: 1px solid $border-color;
        box-shadow: 0px 3px 12px rgba(52, 75, 120, 0.08);
        border-radius: 8px;
        .list-top {
            display: flex;
            justify-content: space-between;
            .status {
                flex-shrink: 0;
            }
        }
        .title{
            width: 100%;
            font-size: 32px;
            line-height: 44px;
            margin: 0;
            padding-right: 50px;
            position: relative;
            .handle-icon {
                position: absolute;
                right: 0;
                top: 0;
            }
        }
        .inline-title{
            margin-left: -14px;
        }
        .des{
            margin-top: 10px;
            margin-bottom: 20px;
            font-size: 28px;
            color: $font-grey;
            min-height: 60px;
        }
        .bot-info{
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: $font-grey;
            font-size: 28px;
            .time{
                flex-shrink: 0;
            }
            .author  {
                flex: 1;
                margin-left: 15px;
                text-align: right;
            }
        }
    }
}

.drop-opt-box {
    /* padding: 0 30px; */
    .list {
        padding: 0 40px 40px 60px;
        max-height: 40vh;
        overflow: auto;
    }
    .list-top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 40px 0;
        h4 {
            margin: 0;
        }
    }
    .sub-list {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        .sub-item {
            padding: 6px 20px;
            background-color: #F8F8FA;
            &.active {
                color: $theme-color;
                background-color: #F2F3FF;
            }
        }
    }
}
.classify-box {
    .classify-sub-list {
        .sub-item {
            margin-left: 40px;
        }
    }
    .active {
        color: $theme-color;
        position: relative;
        &::after {
            content: '';
            display: block;
            width: 36px;
            height: 36px;
            background-image: url('@/assets/imgs/icon_select2.png');
            background-size: cover;
            background-repeat: no-repeat;
            position: absolute;
            left: -40px;
            top: 0;
        }
    }

    .no-list {
        text-align: center;
        padding: 50px 0;
    }
}

@media screen and (min-width:$media-width){
    .sticky-box{
        top: 60px;
        .bot-btn-box{
            padding: 32px;
            justify-content: flex-end;
            .btn{
                width: 120px;
                height: 40px;
                border-radius: 6px;
                font-size: 16px;
                margin-left: 20px;
            }
        }
        .clear-filter-box{
            padding: 0 17px;
            height: 42px;
            font-size: 14px;
            .rocket{
                width: 24px;
                height: 24px;
            }
            .close-icon{
                right: 17px;
            }
        }

    }
    .top-box{
        padding: 15px;
        .menu-icon{
            width: 40px;
            height: 40px;
            svg{
                width: 28px;
                height: 28px;
            }
        }
    }

    .list-wrap{
        padding: 30px;
        .item{
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 4px;
            .title{
                font-size: 16px;
                line-height: 22px;
                .tag{
                    width: 50px;
                    height: 22px;
                    line-height: 22px;
                    font-size: 14px;
                    border-radius: 2px;
                }
            }
            .inline-title{
                margin-left: -14px;
            }
            .des{
                margin-top: 5px;
                margin-bottom: 10px;
                font-size: 14px;
                min-height: 30px;
            }
            .bot-info{
                font-size: 14px;
            }
        }
    }

    .drop-opt-box {
        /* padding: 0 30px; */
        .list {
            padding: 0 40px;
            max-height: 40vh;
            overflow: auto;
        }
        .list-top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 40px 0;
            h4 {
                margin: 0;
            }
        }
        .sub-list {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            .sub-item {
                padding: 6px 20px;
                background-color: #F8F8FA;
                &.active {
                    color: $theme-color;
                    background-color: #F2F3FF;
                }
            }
        }
    }

    .bot-btns{
        bottom: 24px;
    }
}
</style>