<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>
            <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?'输入模板名称':'输入广告名称'" class="input-with-select"></el-input>
            </div>
            <p class="q-mt-md row flex-between items-center">
                <div><span class="Required q-mr-md">*</span>国家：</div>
                <!-- <el-button v-if="!datas.EditAddCountryShow" class="button-new-tag ml-1" 
                style="width: 56px;"
                size="small"
                @click="EditAddDatas(0,0)">
                    + 国家
                </el-button> -->
            </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>
                <!-- <el-button v-if="!datas.EditAddCountryShow" class="button-new-tag q-ml-md ml-1" 
                @click="EditAddDatas(1,0)">
                    编辑
                </el-button> -->
            </div>
            <div class="EditAddElement" v-if="datas.EditAddCountryShow">
                <p class="q-mt-md row flex-between">
                    <span>{{datas.EditAddType==1?'编辑':'新增'}}国家：</span>
                    <span>
                        <el-button class="button-new-tag ml-1"
                        size="small" @click="CancelEditAdd(0)">
                            取消
                        </el-button>
                        <el-button class="button-new-tag ml-1 q-ml-xs"
                        :loading="datas.addEditLoading"
                        type="danger"
                        size="small" @click="setEditAdd(0)">
                            提交
                        </el-button>
                    </span>
                </p>
                <div class="row q-mt-md">
                    <span class="Required q-ma-xs">*</span>
                    <el-input
                        placeholder="国家名称"
                        v-model="datas.addEditCountry.CountryName"
                        class="ml-1 w-20 q-ml-sm"
                        size="small"
                    />
                </div>
            </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>
                <!-- <el-button v-if="!datas.EditAddShow" class="button-new-tag ml-1" 
                style="width: 56px;"
                size="small"
                @click="EditAddDatas(0,1)">
                    + 色值
                </el-button> -->
            </p>
            <div class="row q-mt-md">
                <el-select v-model="queryObj.ColorId" placeholder="请选择分类">
                    <el-option
                        key=""
                        label="不限"
                        value=""
                    />
                    <el-option
                        v-for="item in ColorList"
                        :key="item.Id"
                        :label="`${item.ColorName}`"
                        :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 dispositionObj.ColorList"
                        :key="item.ColorValue"
                        :label="`${item.ColorName}${item.ColorValue}`"
                        :value="item.ColorValue"
                        
                    >
                    <template #default>
                        <el-tag
                        :color="item.ColorValue"
                        effect="dark" class="q-mr-md">
                        {{ item.label }}
                        </el-tag>
                        <span>{{item.ColorName}}</span>
                        <span class="q-ml-md">{{item.ColorValue}}</span>
                    </template>
                    </el-option>
                </el-select>
                <!-- <el-button v-if="!datas.EditAddShow" class="button-new-tag q-ml-md ml-1" 
                @click="EditAddDatas(1,1)">
                    编辑
                </el-button> -->
            </div>
            <div class="EditAddElement" v-if="datas.EditAddShow">
                <p class="q-mt-md row flex-between">
                    <span>{{datas.EditAddType==1?'编辑':'新增'}}色值：</span>
                    <span>
                        <el-button class="button-new-tag ml-1"
                        size="small" @click="CancelEditAdd(1)">
                            取消
                        </el-button>
                        <el-button class="button-new-tag ml-1 q-ml-xs"
                        :loading="datas.addEditLoading"
                        type="danger"
                        size="small" @click="setEditAdd(1)">
                            提交
                        </el-button>
                    </span>
                </p>
                <div class="row q-mt-md">
                    <el-select v-model="datas.addEditColor.ColorId" 
                    class="ml-1 w-20"
                    placeholder="分类"
                    size="small">
                        <el-option
                            key=""
                            label="不限"
                            value=""
                        />
                        <el-option
                            v-for="item in ColorList"
                            :key="item.Id"
                            :label="`${item.ColorName}`"
                            :value="item.Id"
                        />
                    </el-select>
                    <span class="Required q-ma-xs">*</span>
                    <el-input
                        placeholder="色值名称"
                        v-model="datas.addEditColor.ColorName"
                        class="ml-1 w-20 q-ml-sm"
                        size="small"
                    />
                    <span class="Required q-mr-xs q-ml-sm">*</span>
                    <el-input
                        :disabled="datas.EditAddType==1"
                        placeholder="#e5e3da"
                        v-model="datas.addEditColor.ColorValue"
                        class="ml-1 w-20 q-ml-sm"
                        size="small"
                    />
                    
                </div>
            </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,DominantColour } 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: '',
        },
        EditAddType: 0,//0新增 1编辑
        addEditLoading: false,
        EditAddShow: false,
        EditAddCountryShow: false,
        DataSource:{},
        CountryValue: null,
    })
    const dispositionObj = ref({} as any)
    const queryObj = ref({} as any)
    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 = DominantColour()

    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()

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

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

    const EditAddDatas = (type:Number,num:Number) => {
        datas.EditAddType = type
        if(!num) {
            datas.EditAddCountryShow=!datas.EditAddCountryShow 
            datas.EditAddShow=false
            if(type) datas.addEditCountry = {
                CountryId: '',
                CountryName: queryObj.value.CountryName,
            }
        }
        else {
            datas.EditAddShow=!datas.EditAddShow
            datas.EditAddCountryShow=false
            if(type) datas.addEditColor = {
                ColorId: queryObj.value.ColorId,
                ColorValue: queryObj.value.ColorStr,
                ColorName: queryObj.value.ColorName,
            }
        }
    }
    const getCountryId = () => {
        let obj = dispositionObj.value.CountryList.filter(x=>{
            return x.CountryName==queryObj.value.CountryName
        })
    }
    const CancelEditAdd = (num:Number) =>{
        if(!num){
            datas.EditAddCountryShow = false
            datas.addEditCountry = {
                CountryId: '',
                CountryName: '',
            }
        }else{
            datas.EditAddShow = false
            datas.addEditColor = {
                ColorId: '',
                ColorValue: '',
                ColorName: '',
            }
        }
    }

    const setEditAdd = async (num:Number) => {
        if(!num){
            await setCountry()
        }else{
            await setColor()
        }
    }
    const setCountry = async () => {
        if(!datas.addEditCountry.CountryName){
            ElMessage({
                showClose: true,
                message: '请完善国家名称',
                type: 'warning',
            }) 
            return
        }
        try {
            datas.addEditLoading = true
            let params = {
                ID: 0,
                Code: '',
                Content: datas.addEditCountry.CountryName,
                DictKey: 'Trip_Template_Country'
            }
            let dataRes = await ConfigService.SetTemplateCountryData(params)
            if (dataRes.data.resultCode == 1) {
                ElMessage({
                    showClose: true,
                    message: '新增国家成功',
                    type: 'success',
                })
                GetTemplateConfigDatas()
                CancelEditAdd(0)
            }else {
                ElMessage({
                    showClose: true,
                    message: '新增国家失败',
                    type: 'warning',
                }) 
            }
            datas.addEditLoading = false
        } catch (error) {}
    }
    
    const setColor = async () => {
        if(!datas.addEditColor.ColorValue||!datas.addEditColor.ColorName){
            ElMessage({
                showClose: true,
                message: '请完善颜色的名称及颜色16进制',
                type: 'warning',
            }) 
            return
        }
        if(datas.addEditColor.ColorValue.indexOf('#')==-1){
            ElMessage({
                showClose: true,
                message: "色号需要在最前面加 # 号",
                type: 'warning',
            }) 
            return
        }
        try {
            datas.addEditLoading = true
            let dataRes = await ConfigService.SetTemplateConfigData(datas.addEditColor)
            if (dataRes.data.resultCode == 1) {
                ElMessage({
                    showClose: true,
                    message: '新增颜色成功',
                    type: 'success',
                })
                GetTemplateConfigDatas()
                CancelEditAdd(1)
            }else {
                ElMessage({
                    showClose: true,
                    message: '新增颜色失败',
                    type: 'warning',
                }) 
            }
            datas.addEditLoading = false
        } catch (error) {}
    }
    
    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 LineService.GetTemplateConfigData()
            if (response.data.resultCode == 1) {
                dispositionObj.value = response.data.data;
                getCountryId()
            }
        } catch (error) {
        }
    }
    GetTemplateConfigDatas()
    getLinesHandler()
  </script>
  
  <style lang="scss" scoped>
    .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>