<template>
    <el-dialog class="map-box-bg" v-loading="dataLoadingStatus" top="2.5vh" v-model="visibleStatus" :show-close="false" :close-on-press-escape="false" :close-on-click-modal="false" style="margin-bottom: 0; max-width:calc(100vw - 40px);width:calc(100vw - 40px);">
        <template #header>
            <div class="row items-center">
                <div class="text-title col">地图创作</div>
                <el-button link type="primary" size="mini" v-if="ConfigId" @click="loadTripMap"><el-icon style="margin-right: 5px;font-size: 16px;"><Loading /></el-icon>行程渲染</el-button>
                <el-button link size="mini" @click="openThemeHandler"><IconTheme style="font-size: 16px;margin-right: 5px;" />预设主题</el-button>
                <el-button link size="mini" @click="createScriptHandler"><el-icon style="margin-right: 5px;font-size: 16px;"><MapLocation /></el-icon>行程表单</el-button>
                <el-button link size="mini" @click="readyExportHandler"><el-icon style="margin-right: 5px;font-size: 16px;"><Download /></el-icon>生成</el-button>
                <el-button link size="mini"  @click="closed"><el-icon style="margin-right: 5px;font-size: 16px;"><Close /></el-icon>退出</el-button>
            </div>
        </template>
        <div class="map-content" v-loading="loadingStatus" :class="{'clash-mouse':operaIndex==1,'line-mouse':operaIndex==2,'text-mouse':operaIndex==3,'mark-mouse':operaIndex==5 && marker!='circle','circle-mouse':operaIndex==5 && marker=='circle'}" @click="createDrawPanelHandler">
            <div ref="mapRef" class="full-height full-width"></div>
            <tools></tools>
            <map-line v-if="operaIndex==2 && createLineStatus && canOpera" :parent="mapRef" :position="mouse" @success="createLineStatus=false"></map-line>
            <map-attributes></map-attributes>
            <MapScriptForm v-if="formVisable" @close="()=>formVisable=false" @finish="(result:any)=>createScriptMap(result)"></MapScriptForm>
            <ThemeSetting v-if="themeVisable" @close="()=>themeVisable=false" @change="(playload:any)=>setTheme(playload)"></ThemeSetting>
        </div>
        
    </el-dialog>
    <el-dialog v-model="showExport" title="导出提醒">
        <main>
            <el-alert title="注意：当前地图仍然没有保存功能，导出后无法继续编辑" type="warning" :closable="false"/>
            <el-checkbox label="当前地图包含背景颜色，你是否希望导出背景" v-model="isNeedBackground" class="q-mt-lg" v-if="isHaveBg" />
        </main>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="showExport = false">取消</el-button>
                <el-button type="primary" @click="exportMapImage"> 确认导出 </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import tools from './Tools.vue'
import MapAttributes from './MapAttributes/index.vue';
import MapScriptForm from './MapScriptForm.vue'
import mapLine from './Line.vue'
import ThemeSetting from './ThemeSetting/ThemeSetting.vue'
import { onMounted, provide, ref, watch } from 'vue';
import useMap from './useMap'
import { useMapStore,useScreenStore } from '@/store/index'
import { storeToRefs } from 'pinia';
import LineService from '@/services/LineService';
import { Loading,Download,Close, MapLocation } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { result } from 'lodash';

const props = defineProps({
    visible:{
        type:Boolean,
        required:true,
        default:true
    }
})
const emit = defineEmits<{
  (event: 'update:visible', payload: boolean): void,
  (event: 'success', payload: string): void
  (event: 'closed'): void
}>()
const visibleStatus = ref(props.visible)
const mapRef = ref<any>(null)
const mouse = ref<{x:number,y:number}>({
    x:0,
    y:0
})
const formVisable = ref(false)
const themeVisable = ref(false)
const mapStore = useMapStore()
const createLineStatus = ref(false)
const loadingStatus = ref(true)
const showExport = ref(false)
const dataLoadingStatus = ref(false)
const isNeedBackground=ref(false)
const { operaIndex,canOpera,marker } = storeToRefs(mapStore)
const { ConfigId } = storeToRefs(useScreenStore())
const isHaveBg=ref(false)
const { initMap,setCountry,setMarks,setLines,disposeAll,exportPng,lineTransformSpline,splineTransformLine,changeMarkStyleToCurrent,setTheme,isHaveBackground } =useMap(mapRef,loadingStatus)
const tripInfo = ref<any>()
provide("splinetoline", splineTransformLine);
provide("linetoSpline", lineTransformSpline);
provide("changeMarkStyleToCurrent",changeMarkStyleToCurrent)

watch(() => props.visible, () => {
    visibleStatus.value = props.visible
})

watch(() => operaIndex.value, () => {
    if(operaIndex.value!=2){
        createLineStatus.value=false
    }
})

const createDrawPanelHandler = (e:MouseEvent) => {
    if(operaIndex.value==2){
        mouse.value.x=e.offsetX
        mouse.value.y=e.offsetY
        createLineStatus.value=true
    }
}

const loadTripMap = async () =>{
    disposeAll()
    initMap()
    dataLoadingStatus.value=true
    let response = await LineService.GetTripInfoAsync(ConfigId.value)
    try {
        tripInfo.value = response.data.data
        if(tripInfo.value.TripCountryList && tripInfo.value.TripCountryList.length>0){
            let countries = tripInfo.value.TripCountryList.map((x:any)=>x.MName)
            setCountry(countries)
        }
        if(tripInfo.value.TripCityList && tripInfo.value.TripCityList.length>0){
            let points:{latitude:number,longitude:number}[][] = []
            let cities = tripInfo.value.TripCityList.map((x:any,i:number)=> {
                let city = {
                    name:x.MName,
                    lat:Number(x.latitude?x.latitude:x.Lat),
                    lng:Number(x.longitude?x.longitude:x.Lng)
                }
                if(i>0){
                    let t = tripInfo.value.TripCityList[i-1]
                    //let p = [Number(t.latitude?t.latitude:t.Lat),Number(t.longitude?t.longitude:t.Lng),city.lat,city.lng]
                    let p = [
                        {
                            latitude:Number(t.latitude?t.latitude:t.Lat),
                            longitude:Number(t.longitude?t.longitude:t.Lng)
                        },
                        {
                            latitude:city.lat,
                            longitude:city.lng
                        }
                    ]
                    points.push(p)
                }
                return city
            })
            setMarks(cities)
            setLines(points)
        }
        //setCountry(['日本'])
    } catch (error) {
        
    }
    dataLoadingStatus.value=false
}

const createScriptMap = (r:any)=>{
    formVisable.value=false
    disposeAll()
    initMap()
    setTimeout(() => {
        setCountry(r.countries)
        let points:{latitude:number,longitude:number}[][] = []
        let cities = r.cities.map((x:any,i:number)=> {
            let city = {
                name:x.label,
                lat:x.data.center[1],
                lng:x.data.center[0]
            }
            if(i>0){
                let t = r.cities[i-1]
                let p = [
                    {
                        latitude: t.data.center[1],
                        longitude: t.data.center[0]
                    },
                    {
                        latitude:city.lat,
                        longitude:city.lng
                    }
                ]
                points.push(p)
            }
            return city
        })
        console.log(cities)
        setMarks(cities)
        setLines(points)
    }, 1000);
}

const createScriptHandler = ()=>{
    formVisable.value= !formVisable.value
    themeVisable.value = false
}
const openThemeHandler = ()=>{
    themeVisable.value=!themeVisable.value;
    formVisable.value=false
}

const readyExportHandler = ()=>{
    showExport.value=true
    isHaveBg.value = isHaveBackground()
}

const exportMapImage = async () => {
    showExport.value=false
    let png = await exportPng(isNeedBackground.value)
    if(png!='') emit('success',png)
    else {
        ElMessage.error({
            message: '地图导出失败，请重试',
        })
    }
}

const closed = ()=>{
    emit('closed')
}

onMounted(()=>{
    setTimeout(() => {
        initMap()
        //ConfigId.value = 9765
    }, 2000);

    // setTimeout(() => {
    //     let t=['JP', 'KR']
    // }, 4000);
    
})


</script>

<style>
.map-box-bg .el-dialog__body{
    background-color: #fff;
    background-image: linear-gradient(45deg,#ddd 25%,transparent 0),linear-gradient(45deg,transparent 75%,#ddd 0),linear-gradient(45deg,#ddd 25%,transparent 0),linear-gradient(45deg,transparent 75%,#ddd 0);
    background-position: 0 0,6px 6px,6px 6px,12px 12px;
    background-size: 12px 12px;
    padding: 0 !important;
}
.map-content{
    width: 100%;
    height: 90vh;
    position: relative;
    overflow: hidden;
}
.clash-mouse{
    cursor: url('https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1703841822000_160.png'), auto !important;
}
.line-mouse{
    cursor: crosshair !important;
}
.mark-mouse{
    cursor: url('https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1704867897000_892.png'), auto !important;
}
.circle-mouse{
    cursor: url('https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1704867897000_140.png'), auto !important;
}
.text-mouse{
    cursor: text !important;
}
</style>