<template> 
    <div class="q-mt-xs bg-white q-pa-xs rounded ElementTemplateData">
        <div class="column text-mdall">
            <div class="column">
                <template v-if="CoverImg&&!isCoverImg">
                    <p>封面图：</p>
                    <div
                    class="origin-image q-mt-md"
                    :style="{ backgroundImage: `url(${CoverImg})` }"
                    ></div>
                </template>
                <div class="row">
                    <Button v-loading="isCoverImg" style="flex: 1;" @click="setDialogForExport('image')">
                        <span class="Required" v-if="!CoverImg">*</span>
                        {{CoverImg?'重新生成封面图':'生成封面图'}}
                    </Button>
                </div>
            </div>
            <template v-if="searchData.TemplateType!=2">
            <div class="row q-mt-md">
                <Button style="flex: 1;" @click="AllDataSource()">
                    <!-- <span class="Required">*</span> -->
                    数据源
                </Button>
            </div>
            </template>
            <p class="q-mt-md"><span class="Required q-mr-md">*</span>模版权限：</p>
            <div class="row wrap q-mt-md">
                <el-select v-model="queryObj.AuthType" class="m-2" 
                    placeholder="请选择权限类型">
                        <el-option
                            v-for="item in TemplateAuthType"
                            :key="item.Type"
                            :label="item.Name"
                            :value="item.Type"
                        />
                </el-select>
            </div>
            <template v-if="searchData.TemplateType!=2">
            <p class="q-mt-md"><span class="Required q-mr-md">*</span>页面类型：</p>
            <div class="row wrap q-mt-md">
                <el-select v-model="datas.DataSource.pageType" class="m-2" 
                    placeholder="请选择页面类型" @change="getPageType()">
                        <el-option
                            v-for="item in TemplateType"
                            :key="item.FiledType"
                            :label="item.Name"
                            :value="item.FiledType"
                        />
                </el-select>
            </div>
            </template>
            
            <p class="q-mt-md"><span class="Required q-mr-md">*</span>{{searchData.TemplateType!=2?'模版名称':'广告名称'}}：</p>
            <div class="row wrap q-mt-md">
                <el-input v-model="titleValue" @blur="handleUpdateTitle()"
                :placeholder="searchData.TemplateType!=2?'输入模板名称':'输入广告名称'"></el-input>
            </div>
            <p class="q-mt-md row flex-between items-center">
                <div><span class="Required q-mr-md">*</span>国家：</div>
            </p>
            <div class="row q-mt-md">
                <el-select v-model="queryObj.CountryName" filterable class="m-2" placeholder="请选择国家"
                @change="getCountryId">
                        <el-option label="不限" value=""/>
                        <el-option
                            v-for="item in dispositionObj.CountryList"
                            :key="item.CountryValue"
                            :label="item.CountryName"
                            :value="item.CountryValue"
                        />
                </el-select>
            </div>
            <template v-if="false">
                <p class="q-mt-md"><span class="Required q-mr-md">*</span>选择线路：</p>
                <div class="row wrap q-mt-md">
                    <el-select v-model="queryObj.LineId" class="m-2" 
                        filterable placeholder="请选择线路"
                        @change="onLineChangeHandler(1)">
                            <el-option
                                v-for="item in lines"
                                :key="item.LineID"
                                :label="item.LineName"
                                :value="item.LineID"
                            />
                    </el-select>
                </div>
            
            <template v-if="Series.length>0">
                <p class="q-mt-md"><span class="Required q-mr-md"></span>选择系列：</p>
                <div class="row wrap q-mt-md">
                    <el-select v-model="queryObj.LtId" class="m-2" 
                    filterable placeholder="请选择系列">
                            <el-option
                                v-for="item in Series"
                                :key="item.LtID"
                                :label="item.LtName"
                                :value="item.LtID"
                            />
                    </el-select>
                </div>
            </template>
            </template>
            <p class="q-mt-md"><span class="Required q-mr-md"></span>标签：</p>
            <div class="row wrap q-mt-md">
                <el-tag
                    v-for="tag in dynamicTags"
                    :key="tag"
                    class="mx-1 q-mr-md q-mb-md"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)">
                    {{ tag }}
                </el-tag>
                <el-input
                    v-if="inputVisible"
                    ref="InputRef"
                    v-model="inputValue"
                    class="ml-1 w-20"
                    size="small"
                    @keyup.enter="handleInputConfirm"
                    @blur="handleInputConfirm"
                />
                <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">
                    + 添加标签
                </el-button>
            </div>
            <p class="q-mt-md row flex-between items-center">
                <div><span class="Required q-mr-md">*</span>选择颜色：</div>
            </p>
            <div class="row q-mt-md">
                <el-select v-model="queryColor.Code" placeholder="请选择分类"
                @change="getColor(1)">
                    <el-option
                        key=""
                        label="不限"
                        value=""
                    />
                    <el-option
                        v-for="item in ColorList"
                        :key="item.ID"
                        :label="`${item.Name}`"
                        :value="item.ID"
                    />
                </el-select>
                <el-select class="q-pl-sm" v-model="queryObj.ColorStr" filterable placeholder="请选择颜色"
                    @change="setCountryValue">
                    <el-option
                        v-for="item in datas.ColorList"
                        :key="item.Content"
                        :label="`${item.Content}`"
                        :value="item.Content"
                        
                    >
                    <template #default>
                        <el-tag
                        :color="item.Content"
                        effect="dark" class="q-mr-md"></el-tag>
                        <span>{{item.Name}}</span>
                        <span class="q-ml-md">{{item.Content}}</span>
                    </template>
                    </el-option>
                </el-select>
            </div>
            <p class="q-mt-md"><span class="Required q-mr-md">*</span>选择季节：</p>
            <div class="row wrap q-mt-md">
                <el-select v-model="queryObj.SeasonName" class="m-2" placeholder="请选择季节">
                    <el-option
                            key="不限"
                            label="不限"
                            value="不限"
                        />
                        <el-option
                            v-for="item in dispositionObj.SeasonList"
                            :key="item.SeasonValue"
                            :label="item.SeasonName"
                            :value="item.SeasonValue"
                        />
                </el-select>
            </div>
        </div>
    </div>

    <!-- 生成封面图 -->
    <div style="opacity: 0;position: fixed;left: 100px;top: 0;overflow: auto;z-index: -1;" 
    v-if="model==1&&slideIndex>=0">
        <div class="export-img-dialog">
          <div class="thumbnails-view">
            <div class="thumbnails FeatureImgRef" ref="FeatureImgRef">
              <ThumbnailSlide 
                class="thumbnail" 
                :key="slides[slideIndex].id" 
                :slide="slides[slideIndex]" 
                :size="viewportRatio<1 ? VIEWPORT_SIZE.Value : VIEWPORT_VER_SIZE.Value" 
              />
            </div>
          </div>
        </div>
    </div>
  </template>
  
  <script lang="ts" setup>
  
  import { computed, ref, reactive, watch, inject, nextTick } from 'vue'
  import { storeToRefs } from 'pinia'
  import { ElInput } from 'element-plus'
  import { useMainStore, useSlidesStore, useScreenStore } from '@/store'
  import LineService from '@/services/LineService'
  import ConfigService from '@/services/ConfigService'
  import { injectKeyDataSource, injectKeyTemplate } from '@/types/injectKey'
  import { getHtmlPlainText } from '@/utils/common'
  import useExport from '@/hooks/useExport'
  import ThumbnailSlide from '@/views/components/ThumbnailSlide/index.vue'
  import AliyunUpload from '@/utils/upload/aliyun'
  import useEditor from '@/utils/Editor/index'
  import { VIEWPORT_SIZE, VIEWPORT_VER_SIZE } from '@/configs/canvas'

    const datas = reactive({
        addEditCountry: {
            CountryId: '',
            CountryName: '',
        },
        addEditColor: {
            ColorId: '',
            ColorValue: '',
            ColorName: '',
        },
        ColorList: [],
        EditAddType: 0,//0新增 1编辑
        addEditLoading: false,
        EditAddCountryShow: false,
        DataSource:{},
        CountryValue: null,
    })
    const dispositionObj = ref({} as any)
    const queryObj = ref({} as any)
    const queryColor = ref({
        DictKey: 'Trip_Template_Color',
        Code: '',
    })
    const queryColors = ref({
        DictKey: 'Trip_Template_Color',
        Name: queryObj.value.ColorName,
    })
    const searchData = ref({} as any)
    datas.DataSource = inject(injectKeyDataSource)
    queryObj.value = inject(injectKeyDataSource).queryObj
    searchData.value = inject(injectKeyTemplate)
    const lines = ref([] as Array < any > ) //线路
    const Series = ref([] as Array < any > ) //系列
    const ColorList = ref([] as Array < any > ) 

    const cursors = [] as Array<any>

    const inputValue = ref('')
    const dynamicTags = ref([])
    const inputVisible = ref(false)
    const InputRef = ref<InstanceType<typeof ElInput>>()
    if(queryObj.value.TagJsonStr!=''){
        dynamicTags.value = queryObj.value.TagJsonStr.split(',')
    }
   
    const slidesStore = useSlidesStore()
    const { title, slides, slideIndex, viewportRatio } = storeToRefs(slidesStore)
    const titleValue = ref('')
    titleValue.value = title.value
    const coverImgStore = useScreenStore()
    const isCoverImgStore = useScreenStore()
    const { model, ConfigId, TemplateDataSource, TemplateType, CoverImg, isCoverImg, TempId, SourceLoading } = storeToRefs(useScreenStore())

    const mainStore = useMainStore()
    const mainMenuVisible = ref(false)

    const FeatureImgRef = ref(null)
    const { exportFeatureImg } = useExport()
    const { setNewDatasList } = useEditor()

    const TemplateAuthType = ref([
        {Type: 0,Name: '免费',},
        {Type: 1,Name: 'VIP',},
        {Type: 2,Name: '私有',}
    ])

    watch(() => datas.DataSource.pageType, (n,o) => {
        
    })

    const handleUpdateTitle = () => {
        slidesStore.setTitle(titleValue.value)
        queryObj.value.Title = titleValue.value
    }

    const getCountryId = () => {
        let obj = dispositionObj.value.CountryList.filter(x=>{
            return x.CountryName==queryObj.value.CountryName
        })
    }

    const getPageType = () => {
        let TemplateList = TemplateDataSource.value.filter(x=>{
            return x.FiledType==datas.DataSource.pageType
        })
        const newSlides = slides.value
        newSlides.forEach((slide,indexs)=>{
            if(slideIndex.value==indexs){
                slide.pageType = datas.DataSource.pageType
                datas.DataSource.DataSourceList = []
                slide.elements.forEach(item=>{
                    if(item.type=="text"||item.type=="image") {
                        item.TemplateList = JSON.parse(JSON.stringify(TemplateList))
                        item.TemplateDataSource = {
                            Content: item.TemplateDataSource&&item.TemplateDataSource.Content?item.TemplateDataSource.Content:'',
                            Name: item.TemplateDataSource&&item.TemplateDataSource.Name?item.TemplateDataSource.Name:'',
                            Id: item.TemplateDataSource&&item.TemplateDataSource.Id?item.TemplateDataSource.Id: null as Number,
                            index: item.TemplateDataSource&&item.TemplateDataSource.index>=0?item.TemplateDataSource.index:null as Number,
                        }
                        if(datas.DataSource.pageType!=1){
                            let index = item.TemplateDataSource&&item.TemplateDataSource.index>=0?item.TemplateDataSource.index:null as Number
                            Reflect.set(item.TemplateDataSource, 'index', index)
                        }
                        let contentStr
                        if(item.type=="text") contentStr = getHtmlPlainText(item.content)
                        if(item.type=="image") contentStr = item.src
                    
                        let Obj = {}
                        Obj = {
                            ...item,
                            contentStr: contentStr,
                            TemplateList: TemplateList,
                        }
                        if(Obj) datas.DataSource.DataSourceList.push(Obj)
                    }
                })
                
            }
        })
        slidesStore.setSlides(JSON.parse(JSON.stringify(newSlides)))
    }
    const showInput = () => {
        inputVisible.value = true
        nextTick(() => {
            InputRef.value.input.focus()
        })
    }

    const handleClose = (tag: string) => {
        dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
        queryObj.value.TagJsonStr = dynamicTags.value.join(',')
    }

    const handleInputConfirm = () => {
        if (inputValue.value) {
            dynamicTags.value.push(inputValue.value)
        }
        queryObj.value.TagJsonStr = dynamicTags.value.join(',')
        inputVisible.value = false
        inputValue.value = ''
    }

    const dataURLtoFile = (dataurl:string, filename:string) => {
        let arr = dataurl.split(",")
        let mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, { type: mime });
    }

    const setDialogForExport = async (type: DialogForExportTypes) => {
        // mainStore.setDialogForExport(type)
        let CoverImgPath = CoverImg.value.split('/')
        let namePath = ''
        let namePaths = ''
        queryObj.value.CoverImg = ''
        mainMenuVisible.value = false
        isCoverImgStore.setIsCoverImg(true)
        let datas = await exportFeatureImg(FeatureImgRef.value, 'jpeg', 1, false,0)
        if(datas){
            let t =new Date().getTime()
            let name = new Date().getTime()+".jpeg"
            const file = dataURLtoFile(datas, name)
            let url = ''
            if(CoverImgPath[CoverImgPath.length-1].indexOf('CoverImg_')==-1){
                namePath = `CoverImg_${name}`
            }else {
                namePaths = CoverImgPath[CoverImgPath.length-1]
                namePath = namePaths.split('?')[0]
            }
            url = await AliyunUpload.UploadAsync(file,`Feature/${namePath}`)
            coverImgStore.setCoverImg(url+`?t=${t}`)
            isCoverImgStore.setIsCoverImg(false)
            queryObj.value.CoverImg = url+`?t=${t}`
        }
    }

    const setCountryValue = () =>{
        let obj = dispositionObj.value.ColorList.find(x=>{
            return x.ColorValue == queryObj.value.ColorStr
        })
        queryObj.value.ColorName = obj?obj.ColorName:''
    }

    let pageObj = slides.value.find((slide,indexs) => {
            return slideIndex.value==indexs
    })
    
    // 所有数据源
    const AllDataSource = () => {
        if(SourceLoading.value) setNewDatasList(datas.DataSource)
        getPageType()
        datas.DataSource.DataSourceOverlay = !datas.DataSource.DataSourceOverlay
    }


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

    /**
     * 获取系列列表
     */
    const onLineChangeHandler = async (type) =>{
        let obj = lines.value.find(x=>{
            return x.LineID == queryObj.value.LineId
        })
        if(type){
            queryObj.value.LtId = null
        }
        if(obj&&obj.LineName) queryObj.value.LineName = obj.LineName
        try {
            let queryMsg = {
                lineID: queryObj.value.LineId,
                placeID: 0,
                isTOOP: 1
            }
            let response = await LineService.GetSeriesListAsync(queryMsg)
            if (response.data.resultCode == 1) {
                Series.value = response.data.data;
            }
        } catch (error) {
        }
    }

    /**
     * 获取配置项数据(颜色、国家、季节)
     */
     const GetTemplateConfigDatas = async () => {
        try {
            let response = await ConfigService.GetTemplateQueryAsync()
            if (response.data.resultCode == 1) {
                dispositionObj.value = response.data.data;
                getCountryId()
            }
            
        } catch (error) {
        }
    }
    const getColor = async (type:Number) => {
        if(type==1&&!queryColor.value.Code) {
            queryObj.value.ColorName = ''
            queryObj.value.ColorStr = ''
            let Colors = ColorList.value.filter(x=>x.ID==queryColor.value.Code)
            if(Colors.length>0)queryObj.value.SubColor = Colors[0].Content
        }
        let response = await LineService.GetParentColor(queryColor.value)
        if (response.data.resultCode == 1) {
            if(type==0) {
                ColorList.value = response.data.data
                let Colors = ColorList.value.filter(x=>x.Content==queryColor.value.SubColor)
                if(Colors&&Colors.length>0) queryColor.value.Code = Colors[0].ID
                if(!queryColor.value.Code) datas.ColorList = response.data.data
            }
            else datas.ColorList = response.data.data;
            
        }
    }
    const GetTemplateColors = async () => {
        let pageRes = await LineService.GetTemplateConfigDataList(queryColors.value);
        let colorArr = pageRes.data.data
        if(colorArr.length>0){
            for(let i=0;i<colorArr.length;i++){
                if(colorArr[i].Content==queryObj.value.SubColor) {
                    queryColor.value.Code = Number(colorArr[i].Code)
                    getColor()
                }
            }
        }
    }
    GetTemplateConfigDatas()
    getLinesHandler()
    getColor(0)
    GetTemplateColors()
  </script>
  
  <style lang="scss" scoped>
    ::v-deep(.el-button--small){
        border-radius: 2px;
    }
    ::v-deep(.el-input__wrapper){
    border-radius: 2px;
    font-size: 14px;
  }
    .EditAddElement{
        box-shadow: 0px 1px 1px #f6f6f6;
        background: #f6f6f6; 
        padding: 0 5px 10px 5px;
        margin-top: 5px;
    }
    .origin-image {
        height: 100px;
        background-size: contain;
        background-repeat: no-repeat;
        background-position: center;
        background-color: $lightGray;
        margin-bottom: 10px;
    }
    .ElementTemplateData{
        /* min-height: 500px; */
    }
    .el-select{
        width: 100%;
    }
    .Required{
        color: red;
    }
  </style>