<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&&userInfo.isp">
            <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>
            <div style="position: relative;height: 34px;">
                <p class="q-mt-md row flex-between items-center">
                    <div class="row items-center">
                        <span class="Required q-mr-md">*</span>选择颜色：
                    </div>
                    <el-button v-if="searchData.isTeamManage" size="small" 
                    class="button-new-tag q-ml-md ml-1" 
                    @click="setColorsShow">
                        + 颜色
                    </el-button>
                </p>
                <div v-if="datas.addColorsShow" 
                    class="ColorsShowBox" @click= "stopPropagation">
                        <p class="q-mt-md row flex-between">
                            <span>新增颜色：</span>
                            <span>
                                <el-button class="button-new-tag ml-1"
                                size="small" @click.stop="CancelAddColor()">
                                    取消
                                </el-button>
                                <el-button class="button-new-tag ml-1 q-ml-xs"
                                :loading="datas.addColorLoading"
                                type="primary"
                                size="small" @click="setColor()">
                                    提交
                                </el-button>
                            </span>
                        </p>
                        <div class="row q-mt-md items-center">
                            <span class="Required q-mr-xs">*</span>
                            <el-select class="q-ml-sm" v-model="datas.addColor.Code" placeholder="请选择分类">
                                    <el-option
                                        key=""
                                        label="不限"
                                        value=""
                                    />
                                    <el-option
                                        v-for="item in ColorList"
                                        :key="item.ID"
                                        :label="`${item.Name}`"
                                        :value="item.ID"
                                    />
                            </el-select>
                        </div>
                        <div class="row q-mt-md items-center">
                            <span class="Required q-mr-xs">*</span>
                            <el-input
                                placeholder="颜色名称"
                                v-model="datas.addColor.Name"
                                class="ml-1 w-20 q-ml-sm"
                                size="small"
                            />
                            <span class="Required q-mr-xs q-ml-sm">*</span>
                            <el-input
                                placeholder="例：#e5e3da"
                                v-model="datas.addColor.Content"
                                class="ml-1 w-20 q-ml-sm"
                                size="small"
                            />
                            
                        </div>
                </div>
            </div>
            
            <div class="row q-mt-md">
                <el-select v-model="queryColor.Code" placeholder="请选择分类"
                @change="getColor(2)">
                    <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, onMounted, onBeforeUnmount } 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'
  import { useUserStore } from "@/store/user";

    const { userInfo } = storeToRefs(useUserStore());

    const datas = reactive({
        addEditCountry: {
            CountryId: '',
            CountryName: '',
        },
        addEditColor: {
            ColorId: '',
            ColorValue: '',
            ColorName: '',
        },
        addColor: {
            ID: 0,
            DictKey: 'Trip_Template_Color',
            Name: '',
            Content: '',
            Code: '',
            SNO: 0,
            // ColorValue: '',
            // ColorName: '',
            // Code: ''
        },
        addColorsShow: false,
        addColorLoading: false,
        ColorList: [],
        EditAddType: 0,//0新增 1编辑
        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 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: '私有',}
    ])

    const ParentObj = reactive({
      DictKey: 'Trip_Template_Color',
      Name: queryObj.value.ColorStr
    })

    const stopPropagation = (event) => {
        event.stopPropagation()
    }

    const setColorsShow = (event) => {
        event.stopPropagation()
        datas.addColorsShow=!datas.addColorsShow
    }

    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 CancelAddColor = () =>{
        datas.addColorsShow = false
        datas.addColor = {
            ID: 0,
            DictKey: 'Trip_Template_Color',
            Name: '',
            Content: '',
            Code: '',
            SNO: 0,
        }
    }

    const setColor = async () => {
        if(!datas.addColor.Content||!datas.addColor.Name){
            ElMessage({
                showClose: true,
                message: '请完善颜色的名称及颜色16进制',
                type: 'warning',
            }) 
            return
        }
        if(datas.addColor.Content.indexOf('#')==-1){
            ElMessage({
                showClose: true,
                message: "色号需要在最前面加 # 号",
                type: 'warning',
            }) 
            return
        }
        try {
            datas.addColorLoading = true
            let dataRes = await ConfigService.SetTemplateConfigData(datas.addColor)
            if (dataRes.data.resultCode == 1) {
                ElMessage({
                    showClose: true,
                    message: '新增颜色成功',
                    type: 'success',
                })
                getColor(0)
                CancelAddColor()
            }else {
                ElMessage({
                    showClose: true,
                    message: '新增颜色失败',
                    type: 'warning',
                }) 
            }
            datas.addColorLoading = 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 ConfigService.GetTemplateQueryAsync()
            if (response.data.resultCode == 1) {
                dispositionObj.value = response.data.data;
                getCountryId()
            }
            
        } catch (error) {
        }
    }
    const getColor = async (type:Number) => {
        if(type==2) {
            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) {
                ColorList.value = response.data.data
                if(!queryObj.value.SubColor){
                   if(ParentObj.Name) await querySearchHandler(1)
                }else{
                    let Colors = ColorList.value.filter(x=>x.Content==queryObj.value.SubColor)
                    if(Colors&&Colors.length>0) queryColor.value.Code = Colors[0].ID
                }
                if(!queryColor.value.Code) datas.ColorList = response.data.data
            }
            else {
                if(response.data.data.length>0) {
                    datas.ColorList = response.data.data
                }else{
                    datas.ColorList = ColorList.value.filter(x=> x.ID==queryColor.value.Code)
                    if(datas.ColorList.length>0&&datas.ColorList.length==1) {
                        queryObj.value.ColorName = datas.ColorList[0].Name
                        queryObj.value.ColorStr = datas.ColorList[0].Content
                    }
                }
            }
        }
        
    }

    // 根据子颜色获取父级code
    const querySearchHandler = async (type:any) => {
      try {
          let response = await ConfigService.GetTemplateQueryAsync(ParentObj)
          if (response.data.resultCode == 1&&response.data.data.ColorList.length>0) {
            queryColor.value.Code = response.data.data.ColorList[0].ID
            queryObj.value.SubColor = response.data.data.ColorList[0].ColorValue
            getColor(type)
          }
      } catch (error) {
      }
  }
    // 获取所有颜色
    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()
    
    onMounted( () => {
        document.addEventListener('click', (e) => {
            if (datas.addColorsShow) {
                CancelAddColor()
            }
        });
    })
    onBeforeUnmount(() => {
        document.removeEventListener('click', () => {});
    })
  </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;
    }
    .ColorsShowBox{
        position: absolute;
        right: 0px;
        bottom: 34px;
        width: 224px;
        padding: 0px 10px 10px 10px;
        background: #FFF;
        border-radius: 3px;
        z-index: 999;
        box-shadow: 2px 2px 10px 2px #EEE;
    }
    .ColorsShowBox::after{
        content: '';
        width: 0;
        height: 0;
        position: absolute;
        right: 25px;
        bottom: -8px;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-top: 10px solid #FFF;
    }
  </style>