<template>
    <div class="page_title" v-if="showTitle">
        {{category}}
    </div>
    <transition name="fade">
      <div class="hmpicks_content">
        <div 
            v-if="showPrompt && articles.length == 0"
            class="default_text"
        >
            暂时没有{{range ? range + '品牌的' : ''}}相关数据
        </div>
        <Isotope 
            :initialize="isoRefresh" 
            :activated="!isMobile"
            :_style="isMobile?'width:100%':''"
            :columnWidth="250"
            v-if="!['最佳新酒店-设计'].includes(category)"
        >
            <div 
                :class="{news_block_hmpicks:true, news_block_hmpicks_mobile:isMobile}" 
                v-for="(n, i) in articles.filter(xc => String(xc.title) != 'undefined')"
                :key="i"
            >
                <div class="news_title">{{n.title}}</div>
                <div class="picks_children">
                    <div 
                    :class="{
                        picks_child:true, 
                        default_text:true, 
                    }"
                    v-for="(c, cind) in n.children.filter(xc => String(xc.title) != 'undefined')"
                    :key="cind"
                    >
                        <span
                        :class="{
                            clickable:!!c.agencyLink
                        }"
                        @click="onClickLink(c.agencyLink)"
                        >
                            {{c.title}}
                        </span>
                        <span v-if="c.children && c.children.filter(x=>x['酒店名称']).length > 0">
                        （
                        </span>
                        <span 
                            v-for="(c1, c1ind) in (c.children ? c.children.filter(x=>x['酒店名称']) : [])"
                            :key="c1ind"
                        :class="{
                            clickable:!!(c1['官网'] || c1['酒店官网'])
                        }"
                        @click="onClickLink(c1['官网'] || c1['酒店官网'])"
                        >
                            {{c1['酒店名称']}}
                        </span>
                        <span v-if="c.children && c.children.filter(x=>x['酒店名称']).length > 0">
                        ）
                        </span>

                    </div>
                </div>

            </div>

        </Isotope>

        <Isotope 
            :initialize="isoRefresh" 
            :activated="!isMobile"
            :_style="isMobile?'width:100%':''"
            :columnWidth="250"
            v-if="['最佳新酒店-设计'].includes(category)"
        >
        <!-- {{articles}} -->
            <div 
                :class="{news_block_hmpicks:true, news_block_hmpicks_mobile:isMobile}" 
                v-for="(n, i) in articles"
                :key="i"
            >

            <div style="width:100%"
                v-for="(nItem, nind) in Array.isArray(n) ? n : []"
                :key="nind"
            >
                    <div class="news_title">{{nItem.title}}</div>

                    <div class="picks_children"
                        :style="(nind == n.length-1) ? '' : 'margin-bottom:42px;'"
                    >
                        <div 
                        :class="{
                            picks_child:true, 
                            default_text:true, 
                        }"
                        v-for="(c, cind) in nItem.children"
                        :title="renderTitle(c.title, cind) +'（' + c.children.map(x=>x['酒店名称']).join('、') + '）'"
                        :key="cind"
                        >
                            <span
                            :class="{
                                clickable:!!c.agencyLink
                            }"
                            @click="onClickLink(c.agencyLink)"
                            >
                                {{c.title}}
                            </span>
                            （<span 
                                v-for="(c1, c1ind) in c.children"
                                :key="c1ind"
                            :class="{
                                clickable:!!c1['官网']
                            }"
                            @click="onClickLink(c1['官网'])"
                            >
                                {{c1['酒店名称']}}
                            </span>）
                        <!-- {{renderTitle(c.title, cind)}}（{{c.children.map(x=>x['酒店名称']).join('、')}}） -->
                            
                        </div>
                    </div> 

            </div>

            <div style="width:100%"
                v-if="!Array.isArray(n)"
            >
                <div class="news_title">{{n.title}}</div>

                <div class="picks_children">
                    <div 
                    :class="{
                        picks_child:true, 
                        default_text:true, 
                        clickable:n.links && n.links[cind],
                    }"
                        v-for="(c, cind) in n.children"
                        :title="renderTitle(c.title, cind) +'（' + c.children.map(x=>x['酒店名称']).join('、') + '）'"
                        @click="onClickLink(n.links ? n.links[cind] : '')"
                        :key="cind"
                    >
                    {{renderTitle(c.title, cind)}}（{{c.children.map(x=>x['酒店名称']).join('、')}}）
                        
                    </div>
                </div> 
            </div>

            </div>

        </Isotope>
      </div>
    </transition>
</template>

<script lang="ts">
import { defineComponent, nextTick, ref,watch, onMounted } from 'vue'
import {axiosInstance} from './data/axiosInstance'

import {getBidData} from './data/getBidData'
import itemRanking1 from './data/itemRanking1' 
import itemRanking2 from './data/itemRanking2' 
import y1Data from './data/y1Data'  

export default defineComponent({
    name:"HmPicks",
    props: {
        industry:{
            default:false
        },
        showPrompt:{
            default:true
        },
        jwt:{
            default:''
        },
        showTitle:{
            default:false
        },
        searchCandidates:{
            default:[]
        },
        isMobile:{
            default:false
        },
        filter:{
            default:'' as any
        },
        category:{
            default:'' as string
        },
        range:{
            default:'' as any
        },
        currPageTranslate:{
            default:'' as any
        },
        backEndURL:{
            default:'' as any
        },
    },
    setup(props){

        const articles = ref([] as any[])

        const getCurrPage = () => {
            if(props.category.includes('设计')) return 'design'
            else if(props.category.includes('采购')) return 'purchase'
            else return ''
        }

        const getValue = (item:any) => {
            return item["设计公司"] || item["设计公司（中）"] || item["设计公司（英）"]
        }
        const isoRefresh = ref(0)
        setInterval(()=>{
            isoRefresh.value ++
        }, 500)
        const refresh = ()=>{
            if(!props.category) return
            if(props.category == '近一年新开-采购'){
                articles.value = y1Data
                isoRefresh.value ++
                // getBidData(props.range, props.jwt).then((res:any)=>{
                //     console.log('got res', res)
                // }).catch(err=>{
                //     console.log('hmpicks error:', err)
                // })
            }else if(props.category == '最佳新酒店-设计'){
                axiosInstance.get('https://c.huamei2001.com/static/hmPicks/最佳新酒店-设计.json')
                .then(res=>{
                    const aoo = res.data
                    const temp = {} as any

                    for(let item of aoo){
                        if(!item['设计类型']){
                        }
                        if(temp[item['设计类型']] && temp[item['设计类型']][item['酒店类型']]){
                            if(Array.isArray(temp[item['设计类型']][item['酒店类型']][getValue(item)])){
                                temp[item['设计类型']][item['酒店类型']][getValue(item)].push(item)
                            }else{
                                temp[item['设计类型']][item['酒店类型']][getValue(item)] = [item]
                            }
                        }else if(temp[item['设计类型']]){
                            temp[item['设计类型']][item['酒店类型']] = {} as any
                            temp[item['设计类型']][item['酒店类型']][getValue(item)] = [item]
                        }else{
                            temp[item['设计类型']] = {} as any
                            temp[item['设计类型']][item['酒店类型']] = {} as any
                            temp[item['设计类型']][item['酒店类型']][getValue(item)] = [item]
                        }
                    }
                    const out = Object.keys(temp)
                    .filter(k=>{
                        return Object.keys(temp[k]).length > 0
                    }).map(k=>{
                        const hotelTypes = Object.keys(temp[k])
                        const children = hotelTypes
                                        .filter(hotelType=>{
                                            return Object.keys(temp[k][hotelType]).length > 0
                                        })
                                        .sort((a:any,b:any)=>{
                                            return a.localeCompare(b)
                                        })
                                        .map(hotelType=>{
                                            const typeChidren = Object.keys(temp[k][hotelType])
                                                            .filter(designer=>temp[k][hotelType][designer].length > 0)
                                                            .map(designer=>{
                                                                return temp[k][hotelType][designer]
                                                            })
                                            const designers = [] as any
                                            const designerCNActive = {} as any
                                            for(let c of typeChidren){
                                                const designer = getValue(c[0])
                                                const cnMatch = c.find(x=>!x['酒店名称'].match(/^[A-Za-z0-9 ]+$/))
                                                designerCNActive[designer] = !!cnMatch
                                                designers.push(
                                                    ...c
                                                    .sort((a:any,b:any)=>a['酒店名称'].localeCompare(b['酒店名称']))
                                                    .map((cc:any) => {return {
                                                        title: getValue(c[0]),
                                                        agencyLink:c[0]['设计公司官网'],
                                                        children:[cc]
                                                    }})
                                                )
                                            }
                                            designers.sort((a,b)=>{
                                                const aCN = designerCNActive[a.title]
                                                const bCN = designerCNActive[b.title]
                                                let res = 0
                                                if(aCN && !bCN){
                                                    res = -1
                                                }else if(bCN && !aCN){
                                                    res = 1
                                                }
                                                else{
                                                    res = a.title.localeCompare(b.title)
                                                }
                                                return res
                                            })
                                            const typeHotels = designers.map(d=>{
                                                                    return d.children.map(x=>x['酒店名称'] || '')
                                                                })
                                            const typeLinks =  designers.map(d=>{
                                                                    const foundLinkChild = d.children.find(x=>x['官网'])
                                                                    if(foundLinkChild){
                                                                        return foundLinkChild['官网']
                                                                    }else{
                                                                        return ''
                                                                    }
                                                                })
                                            return {
                                                title:hotelType,
                                                children: designers,
                                                hotels:typeHotels,
                                                links:typeLinks,
                                                items:designers
                                            }
                                        })
                        return {
                            title:k,
                            lookUpMajor:'',
                            children,
                                        // .map(x=>x + temp[k][x])
                        }
                    }).sort((a,b)=>{
                        const aInd2 = itemRanking2.indexOf(a.title)
                        const bInd2 = itemRanking2.indexOf(b.title)
                        if((aInd2 > -1) && (bInd2 > -1)){ return aInd2 - bInd2}
                        else{
                            const aInd1 = itemRanking1.indexOf(a.lookUpMajor)
                            const bInd1 = itemRanking1.indexOf(b.lookUpMajor)
                            if(aInd1 != bInd1){ return aInd1 - bInd1}
                            else{
                                if((aInd2 > -1)){
                                    return -1
                                }else if (bInd2 > -1){
                                    return 1
                                }else{
                                    return a.title.localeCompare(b.title)
                                }
                            }
                        }
                    })

                    const out2 = [] as any[]

                    for(let out1 of out){
                        const curr = [] as any[]
                        for(let c of out1.children){
                            curr.push(
                                {
                                    ...c,
                                    title:out1.title + ' - ' + c.title,
                                }
                            )
                        }
                        out2.push(curr)
                    }

                    articles.value = out2
                    isoRefresh.value ++
                }).catch(err=>{
                    console.log('hmpicks error:', err)
                })
            }else{
                axiosInstance.get('https://c.huamei2001.com/static/hmPicks/' + props.category + '.json')
                .then(res=>{
                    const sameBrand = res.data
                                        .filter(x=>(
                                            ['最佳新酒店-设计', '最佳新酒店-采购'].includes(props.category)) 
                                            || x["管理品牌"] == props.range
                                        )
                    const lookUpKey = getCurrPage() == 'design' ? '设计类型' : '小类'
                    const lookUpKeyMajor = getCurrPage() == 'design' ? '设计类型' : '大类'
                    const getValue = (item) => {
                        if(
                            getCurrPage() == 'design' 
                        ){
                            return item["设计公司"] || item["设计公司（中）"] || item["设计公司（英）"]
                        }else{
                            return item["物品品牌"]
                        }
                    }
                    const temp = {} as any

                    for(let item of sameBrand){
                        if(!item[lookUpKey]){
                        }
                        if(temp[item[lookUpKey]]){
                            if(Array.isArray(temp[item[lookUpKey]][getValue(item)])){
                                temp[item[lookUpKey]][getValue(item)].push(item)
                            }else{
                                temp[item[lookUpKey]][getValue(item)] = [item]
                            }
                        }else{
                            temp[item[lookUpKey]] = {} as any
                            temp[item[lookUpKey]][getValue(item)] = [item]
                        }
                    }
                    const out = Object.keys(temp)
                    .filter(k=>{
                        return Object.keys(temp[k]).length > 0
                    })
                    .map(k=>{
                        const children1 = Object.keys(temp[k])
                                            .sort((a:any,b:any)=>{
                                                if(temp[k][a].length != temp[k][b].length){
                                                    return temp[k][a].length - temp[k][b].length
                                                }else{
                                                    return a.localeCompare(b)
                                                }
                                            })
                        const children = children1.map(a=>{
                                                return {
                                                    title:a,
                                                    children:temp[k][a],
                                                    agencyLink: temp[k][a][0]['供应商官网'] || temp[k][a][0]['设计公司官网'] || ''
                                                }
                                            })
                                            .sort((a,b)=>{
                                                const aCN = a.children.find(x=>!x['酒店名称'].match(/^[A-Za-z0-9 ]+$/))
                                                const bCN = b.children.find(x=>!x['酒店名称'].match(/^[A-Za-z0-9 ]+$/))
                                                let res = 0
                                                if(aCN && !bCN){
                                                    res = -1
                                                }else if(bCN && !aCN){
                                                    res = 1
                                                }
                                                else{
                                                    res = a.title.localeCompare(b.title)
                                                }
                                                return res
                                            })
                                            // .reduce((a,b)=>{
                                            //     return [...a, ...b.children.map(bc=>{
                                            //         return {
                                            //             title:b.title,
                                            //             chilren:[bc],
                                            //             agencyLink: b.agencyLink
                                            //         }
                                            //     })]
                                            // }, [] as any[])
                        return {
                            title:k,
                            lookUpMajor:children.length > 0 ? temp[k][children[0].title][0][lookUpKeyMajor] : '',
                            children,
                                        // .map(x=>x + temp[k][x])
                        }
                    }).sort((a,b)=>{
                        const aInd2 = itemRanking2.indexOf(a.title)
                        const bInd2 = itemRanking2.indexOf(b.title)
                        if((aInd2 > -1) && (bInd2 > -1)){ return aInd2 - bInd2}
                        else{
                            const aInd1 = itemRanking1.indexOf(a.lookUpMajor)
                            const bInd1 = itemRanking1.indexOf(b.lookUpMajor)
                            if(aInd1 != bInd1){ return aInd1 - bInd1}
                            else{
                                if((aInd2 > -1)){
                                    return -1
                                }else if (bInd2 > -1){
                                    return 1
                                }else{
                                    return a.title.localeCompare(b.title)
                                }
                            }
                        }
                    })
                    articles.value = out
                    isoRefresh.value ++
                }).catch(err=>{
                    console.error('hmpicks Error',err)
                })
            }
            isoRefresh.value ++
        }

        onMounted(refresh)
        watch(()=>props.category + props.range + getCurrPage(), refresh)


        // display 
        const displayText = (text:string) => {

            if(typeof text != typeof 'string') {
                return ''
            }
            if(text=='') {
                return ''
            }

            const searchString = props.filter + ' ' + props.range

            if(!searchString) {
                return text
            }
            let out = text || ''
            for(let s of searchString.split(' ')){
                if(s=='')continue
                if(text.includes(s)){
                    // const delim = `<span class="red">${s}</span>`
                    const delim = `<span class="">${s}</span>`
                    out = out.split(s).join(delim)
                }
            }
            return out || ''
        }

        const convertDate = (dateString:string) => {
            if(!dateString) return ''
            const dSplit = dateString.split('-')
            return dSplit[0] + '年' + dSplit[1] + '月' + dSplit[2] + '日'
        }

        const renderTitle = (block: ({children:string[], hotels:string[]} | string), ind:string) => {
            if(typeof block == 'string'){
                return block.trim()
                    .replace(/股份有限公司$/,"")
                    .replace(/有限公司$/,"")
                    .replace(/顾问公司$/,"")
                    .replace(/事务所$/,"")
                    .replace(/Limited$/,"")
                    .replace(/Ltd$/,"")
            }
            try{
                let out = block.children[ind].trim()
                        .replace(/股份有限公司$/,"")
                        .replace(/有限公司$/,"")
                        .replace(/顾问公司$/,"")
                        .replace(/事务所$/,"")
                        .replace(/Limited$/,"")
                        .replace(/Ltd$/,"")
                const hotelString = block.hotels[ind]
                                    .filter(x=>x && x.trim().length > 0)
                                    .join('、').trim()
                if(hotelString.length > 0){
                    out += '（'
                            + hotelString
                            + '）'
                }
                return out
            }catch(e){
                return ''
            }
        }

        const onClickLink = (link:string) => {
            if(link.match(/^https/)){
                window.open(link)
            }else if(link.match(/^http:/)){
                window.open(link)
            }else{
                window.open('http://'+link)
            }
        }

        return {
            itemRanking1,
            itemRanking2,
            articles,
            isoRefresh,
            displayText,
            window,
            renderTitle,
            onClickLink,
            getValue
        }
    }
})
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease-in-out;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

._container {
  width: 100%;
  /* min-width:500px; */
  position:relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  /* min-height: 101vh; */
  padding-bottom: 50px;

  --animation-time:0.3s;
  --label-height:35px;
  --control-panel-padding:5px;

  --elast-initial-width:40%;
}
.control{
  width: 100%;
  padding-left:2%;
  padding-right:2%;
  pointer-events: none;
  /* background-color: rgba(255, 255, 255, 0.6); */
  z-index: 10;
  display:flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.3s ease-in-out;
  position:sticky;
  top:-1px;
}
.hmpicks_content{
    width: 100%;
    position: relative;
    display:flex;
    flex-direction: column;
    display:flex;
    flex-direction:column;
    align-items: center;
}
.news_block_hmpicks{
    width: 230px;
    border: 1px solid #ddd;
    background-color:white;
    border-radius: 5px;
    padding: 15px;
    margin: 0px 10px 30px 5px;
    font-size: 14px;
    font-weight: 300;
    transition: all 0.3s ease-in-out;
    cursor: pointer;
    box-sizing: border-box;
}
.news_block_hmpicks_mobile{
    width: 100%;
}
.news_title{
    text-align:left;
    font-size: 18px;
    font-weight: 300;
    line-height:36px;
    margin-bottom: 10px;
}
.news_datesource{
    display: flex;
    flex-direction: row;
    align-items:center;
    text-align:left;
    font-size: 14px;
    line-height:14px;
    margin-top: 28px;
}
.news_datesource>div{
    margin-right: 10px;
    color: gray;
}
.news_content{
    margin-top: 28px;
    white-space: pre-wrap;
    color: gray;
    text-align: justify;
}
.edit_title{
    width: 80%;
    text-align: left;
}
.edit_panel{
    display: flex;
    flex-direction: column;
    align-items: center;
}
.input_box{
    width: 80%;
    margin-top: 10px;
    margin-bottom: 10px;
}

._confirm{
    margin-bottom: 10px;
    width: 80%;
    text-align: center;
}
.comment_section{
    margin-top: 0px;
    border-top: 1px solid #ddd;
    padding-top: 10px;
}
.news_comments{
    margin-bottom: 10px;
}
.comment_button{
    margin-top: 40px;
    padding-top: 10px;
}

.xiangguanlianjie{
    color: black;
    font-weight: 400;
}




.snapshot{
  position:relative;
  max-height:20px;
  max-width:20px;
  opacity:0.5;
  margin-left:5px;
  padding:2px 3px 2px 0px;
  cursor:pointer;
  display:flex;
  justify-content:center;
  align-items:center;
}
.snapshot:hover{
  opacity:0.8;
}
.snapshot>img{
  width:13px;
  height:15px;
  object-fit:contain;
}

.link_title_wrap{
    margin-top:10px;
}

.text_truncate{
    display:flex;
    flex-direction: row;
}
.news_datesource{
    display: flex;
    flex-direction: row;
    align-items:center;
    text-align:left;
    font-size: 14px;
    line-height:28px;
    margin-top: 18px;
}
.news_datesource>div{
    margin-right: 10px;
    color: gray;
}
.news_content{
    margin-top: 18px;
    white-space: pre-wrap;
    color: gray;
    text-align: justify;
}

.picks_children{
    width: 100%;
    text-align: left;
    overflow: hidden;
    white-space: pre-wrap;
    text-overflow: ellipsis;
}
.picks_child{
    width: 100%;
    text-align: left;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    line-height: 28px;
}

.design_type_title{
    font-size:18px;
    font-weight: 300;
    margin-top: 14px;
    margin-bottom: 7px;
}



.clickable{
	color:#1680FF;
	cursor: pointer;
	transition: color 0.2s linear;
    user-select: none;
}
.clickable:hover, .clickable.active{
	color:#334250
}

.page_title{
    font-size: 28px;
    font-weight: 300;
    margin-bottom: 20px;
    width: 100%;
    text-align:center
}
</style>