<template>
    <div ref="marketRef" style="background: #f3f6fb;height:100vh;overflow: auto;">
        <div style="padding: 30px; max-width:1440px; margin:0 auto;">
            <el-row justify="space-between">
                <el-col :span="6">
                    <h1 class="aliMarketfont" style="font-size:20px;">智慧设计平台</h1>
                </el-col>
                <el-col :span="6">
                    <el-input v-model="queryObj.Title" placeholder="输入模板关键字快速查找" class="input-with-select">
                        <template #append>
                            <el-button type="primary" @click="queryTemplateBySearchHandler">搜索</el-button>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="6" style="text-align: right;">
                    <el-button v-if="userInfo.IsEditTripTemplate==1&&model" 
                    v-tooltip="'添加模版'" type="danger" 
                    size="small" icon="Plus"
                    @click="addTemplate()" style="color: #ffff;"></el-button>
                </el-col>
            </el-row>
            <div class="q-mt-lg bg-white rounded text-nowrap" style="padding: 20px 20px 0 20px;">
                <div class="row text-small items-center wrap">
                    <span style="margin-right: 50px;">适用线路：</span>
                    <el-check-tag :checked="queryObj.LineId == 0" @change="onLineChangeHandler(0)"
                        class="text-small q-mr-md">全部</el-check-tag>
                    <el-check-tag :checked="queryObj.LineId == x.LineID" @change="onLineChangeHandler(x.LineID)"
                        class="text-small q-mr-md" v-for="x in lines" :key="x.LineID">{{x.LineName}}</el-check-tag>
                </div>
                <el-divider style="margin:12px 0;border-top-color:#f3f6fb;"></el-divider>
                <div class="row wrap q-pb-md">
                    <div class="q-pb-md">
                        <div class="row text-small items-center wrap">
                            <span style="margin-right: 50px;">适用国家：</span>
                            <el-check-tag :checked="queryObj.CountryName == ''" @change="onCountryNameChangeHandler('')"
                                class="text-small q-mr-md">通用</el-check-tag>
                            <el-check-tag :checked="queryObj.CountryName == x.CountryName"
                                @change="onCountryNameChangeHandler(x.CountryName)" class="text-small q-mr-md"
                                v-for="(x,i) in countries" :key="i">{{x.CountryName}}</el-check-tag>
                        </div>
                    </div>
                    <div class="q-pb-md">
                        <div class="MarketVerticalLine">&nbsp;</div>
                    </div>
                    <div class="q-pb-md">
                        <div class="row text-small items-center wrap">
                            <span style="margin-right: 50px;">季节：</span>
                            <el-check-tag :checked="queryObj.SeasonName == ''" @change="onSeasonNameChangeHandler('')"
                                class="text-small q-mr-md">通用</el-check-tag>
                            <el-check-tag :checked="queryObj.SeasonName == x.SeasonName" @change="onSeasonNameChangeHandler(x.SeasonName)"
                                class="text-small q-mr-md" v-for="(x,i) in seasonArr" :key="i">{{x.SeasonName}}</el-check-tag>
                        </div>
                    </div>
                    <div class="q-pb-md">
                        <div class="MarketVerticalLine">&nbsp;</div>
                    </div>
                    <div class="q-pb-md">
                        <div class="row text-small items-center wrap">
                            <span style="margin-right: 50px;">颜色：</span>
                            <el-check-tag :checked="queryObj.ColorName == ''" @change="onColorNameChangeHandler('')"
                                class="text-small q-mr-md">通用</el-check-tag>
                            <el-check-tag :checked="queryObj.ColorName == x.ColorName" @change="onColorNameChangeHandler(x.ColorName)"
                                class="text-small q-mr-md" v-for="(x,i) in colorArr" :key="i">{{x.ColorName}}</el-check-tag>
                        </div>
                    </div>
                </div>
            </div>
            <div style="margin-top: 20px;">
                <div v-if="dataList.length>0" class="q-mt-lg row wrap rounded">
                    <template v-for="(item,index) in dataList">
                        <div class="MarketIndexListBox bg-white rounded">
                            <div class="MarketIndexList-Hover">
                                <div>
                                    <el-button type="primary"
                                     style="color: #ffff;"
                                    @click="getTemplate(item)">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;详情&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button>
                                </div>
                                <div class="q-mt-lg">
                                    <el-button type="primary"
                                    style="color: #ffff;"
                                    @click="goToTemplate(item)">选择该模版</el-button>
                                </div>
                            </div>
                            <div class="MarketIndexList-img">
                                <img :src="item.CoverImg" class="rounded" />
                            </div>
                            <div class="MarketIndexList-text">{{item.Title}}</div>
                        </div>
                        
                    </template>
                </div>
                <div v-else-if="dataList.length == 0 && !loading" class="q-mt-lg bg-white rounded" style="padding: 30px 10px 30px 10px;text-align: center;color: #909399;">暂无数据</div>
                <el-divider class="no-bg q-mt-lg" v-if='queryObj.pageCount == queryObj.pageIndex && !loading'>
                    <span class="text-samll" style="background: #f3f6fb;padding: 0 10px;color:#a3a3a3">已加载完成所有数据</span>
                </el-divider>
                <div style="height:40px;" class="q-mt-md no-bg" background="transparent" v-loading="loading"  element-loading-text="正在加载中"></div>
            </div>
        </div>
    </div>
    <el-dialog v-model="datas.DetailsVisible" :show-close="true" :close-on-press-escape="false" 
    :close-on-click-modal="true" style="width: 650px;">
        <template #header>
            <div class="text-title">{{datas.TemplateRow.Title}} 模版详情</div>
        </template>
        <div class="MarketDetails-LayoutPool" v-loading="datas.loading">
            <LayoutPool style="width: 100%;"/>
        </div>
        <div class="q-mt-lg row items-center">
            <div class="col">
                
            </div>
            <div>
                <el-button v-if="ConfigId||model" class="q-ml-lg" 
                @click="datas.DetailsVisible=false,datas.TemplateRow={}">关闭</el-button>

                <el-button v-if="ConfigId||model" type="primary" class="q-ml-lg" 
                @click="goToTemplate(datas.TemplateRow)">选择该模版</el-button>
            </div>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
    import { reactive, ref, inject, watch, onMounted} from "vue";
    import LineService from '@/services/LineService'
    import ConfigService from '@/services/ConfigService'
    import { userStore } from "@/store/user";
    import { useSlidesStore } from '@/store'
    import { useScreenStore } from "@/store/screen";
    import { storeToRefs } from "pinia";
    import { injectKeyTemplate } from '@/types/injectKey'

    import LayoutPool from './LayoutPool.vue'

    const {
        userInfo
    } = storeToRefs(userStore())
    const lines = ref([] as Array < any > ) //线路
    const countries = ref(['日本', '韩国', '老挝', '法国', '意大利'] as Array < any > ) //国家
    const colorArr = ref([] as Array < any > ); //颜色
    const seasonArr = ref([] as Array < any > ); //季节
    const dataList = ref([] as Array < any > ); //模板数据列表
    const marketRef = ref<any>()

    const currentPage = ref(1 as Number);
    const datas = reactive({
        TemplateRow: {},
        DetailsVisible: false,
        loading: false,
    })
    const queryObj = reactive({
        pageIndex: 1,
        pageSize: 20,
        LineId: 0, //线路Id
        Title: '', //模板名称
        CountryName: '', //国家名称
        SeasonName: '', //季节名称
        ColorName: '', //颜色名称
        pageCount: 0, //总页数
    })

    const loading = ref(false as any)
    const searchData = ref({} as any)
    searchData.value = inject(injectKeyTemplate)
    const marketStore = useScreenStore()
    const isModelStore = useScreenStore()
    const layoutsStore = useSlidesStore()
    const TempIdStore = useScreenStore()
    const { screening, market, model, isModel, ConfigId, TempId} = storeToRefs(useScreenStore())

    const addTemplate = () =>{
        marketStore.setMarket(!market)
        searchData.value.TempId = 0
    }

    // 查看所有子模版
    const getTemplate = async (item) => {
        datas.DetailsVisible = true
        datas.TemplateRow = JSON.parse(JSON.stringify(item))
        datas.loading = true
        layoutsStore.setLayouts([])
        try {
        let queryMsg = {
            TempId: item.TempId
        }
        let dataRes = await ConfigService.GetTripTemplateSlide(queryMsg);
        if (dataRes.data.resultCode == 1) {
            let SlidesData = JSON.parse(dataRes.data.data.TempData)
            let newSlides = []
            if(typeof SlidesData=='object'&&!SlidesData.length){
                let obj = {
                    pageType: 1,
                    ...SlidesData
                }
                newSlides.push(obj)          
            }else if(SlidesData.length>0){
                newSlides = SlidesData
            }
            layoutsStore.setLayouts(JSON.parse(JSON.stringify(newSlides)))
        }
            datas.loading = false
        } catch (error) {
            console.log("GetTripTemplateSlide", error);
            datas.loading = false
        }
    }

    /**
     * 页面跳转
     */
    const goToTemplate = (item: any) => {
        if(!ConfigId.value&&!model.value) return
        datas.DetailsVisible = false
        searchData.value.TempId = item.TempId
        marketStore.setMarket(!market)
        datas.TemplateRow = {}
        // console.log("item", item.TempId);
    }

    /***
     * 获取模板市场分页列表
     */
    const queryTemplateBySearchHandler = async () => {
        loading.value = true
        try {
            if(queryObj.pageIndex == 1) dataList.value =[]
            let pageRes = await ConfigService.GetTemplagePageAsync(queryObj);
            if (pageRes.data.resultCode == 1) {
                dataList.value = dataList.value.concat(pageRes.data.data.pageData);
                queryObj.pageCount = pageRes.data.data.pageCount;
            }
            loading.value = false
        } catch (error) {
            loading.value = false
        }
    }

    //线路切换
    const onLineChangeHandler = (lineId: number) => {
        queryObj.LineId = lineId;
        queryObj.pageIndex = 1
        queryTemplateBySearchHandler();
    }
    //国家切换
    const onCountryNameChangeHandler = (CountryName: string) => {
        queryObj.CountryName = CountryName;
        queryObj.pageIndex = 1
        queryTemplateBySearchHandler();
    }

    //季节切换
    const onSeasonNameChangeHandler = (SeasonName: string) => {
        queryObj.SeasonName = SeasonName;
        queryObj.pageIndex = 1
        queryTemplateBySearchHandler();
    }

    //颜色切换
    const onColorNameChangeHandler = (ColorName: string) => {
        queryObj.ColorName = ColorName;
        queryObj.pageIndex = 1
        queryTemplateBySearchHandler();
    }

    /**
     * 获取线路列表
     */
    const getLinesHandler = async () => {
        try {
            let response = await LineService.GetLineListAsync()
            if (response.data.resultCode == 1) {
                lines.value = response.data.data;
            }
        } catch (error) {
            console.log("getLinesHandler", error);
        }
    }

    /**
     * 获取模板市场查询条件
     */
    const getTemplateQuery = async () => {
        try {
            let res = await ConfigService.GetTemplateQueryAsync();
            if (res.data.resultCode == 1) {
                var tempData = res.data.data;
                //国家
                if (tempData && tempData.CountryList) {
                    countries.value = tempData.CountryList;
                }
                //颜色
                if (tempData && tempData.ColorList) {
                    colorArr.value = tempData.ColorList;
                }
                //季节
                if (tempData && tempData.SeasonList) {
                    seasonArr.value = tempData.SeasonList;
                }
            }
        } catch (error) {
            console.log("getTemplateQuery", error);
        }
    }
    const scrollingHandler = () =>{
        if(marketRef.value && !loading.value){
            let maxHeight = marketRef.value.scrollHeight - marketRef.value.offsetHeight
            let scrollTop = marketRef.value.scrollTop
            if(maxHeight - scrollTop==0 && queryObj.pageCount > queryObj.pageIndex) {
                queryObj.pageIndex++
                queryTemplateBySearchHandler()
                //console.log('应该加载第二页了')
            }
        }
        
    }
    getLinesHandler();
    getTemplateQuery();
    queryTemplateBySearchHandler();

    onMounted(()=>{
        marketRef.value.addEventListener("scroll", scrollingHandler);
    })
</script>

<style lang="scss" scoped>
    @import url('../../assets/styles/common.css');

    @font-face {
        font-family: "aliMarketfont";
        font-weight: 400;
        src: url("//at.alicdn.com/wf/webfont/MQHUV6e56ce5/285OveHVCHM7.woff2") format("woff2"),
            url("//at.alicdn.com/wf/webfont/MQHUV6e56ce5/pz3etdXOpfWP.woff") format("woff");
        font-display: swap;
    }

    .aliMarketfont {
        font-family: aliMarketfont;
    }

    .el-check-tag {
        background: #FFF;
        font-weight: 500 !important;
        font-size: 12px !important;
    }
    .MarketIndexListBox{
        width:calc(20% - 10px);
        margin: 10px 10px 0 0; 
        padding:5px;
        position: relative;
        overflow: hidden;
        box-shadow: 0px 0px 20px 0px rgba(76,87,125,0.2)!important;
    }
    .MarketIndexList{
        width: 100%;
        position: relative;
        overflow: hidden;
    }
    
    .MarketIndexList-Hover{
        z-index: 1;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(23,23,23,0.5);
        opacity: 0;
        transition: opacity 0.5s ease;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: $themeHoverColor;
    }
    .MarketIndexListBox:hover .MarketIndexList-Hover{
        opacity: 1;
    }
    .MarketIndexList-Hover div span{
        display: inline-block;
        background: #fff;
        border-radius: 4px;
        padding: 0 10px 3px 10px;
    }
    .MarketIndexListBox:hover{
        top: -5px;
        
    }
    .MarketIndexListBox:hover .MarketIndexList{
       
    }
    .MarketIndexList-img{
        width: 100%;
        height: 0;
        position: relative;
        padding-bottom: 56.25%;
    }
    .MarketIndexList-img img{
        /* position: absolute;
        top: 0;
        left: 0;
        height: 100%; */
        width: 100%;
        height: 100%;
        position: absolute;
        object-fit: cover;
    }
    .MarketIndexList-text{
        font-size: 14px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        padding: 10px;
        padding-bottom: 5px;
    }
    .MarketVerticalLine{
        width: 1px;
        height: 80%;
        background: #dcdfe6;
        margin-right: 30px;
        margin-top: 5px;
    }
    .layout-item{
        width: 180px;
    }
</style>