<template>
    <div class="attr-box"  @click.stop="(e:MouseEvent)=>e.stopImmediatePropagation()">
        <div class="box-header">
            <div class="row items-center attr-header">
                <img class="drag-icon"
                    src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1704767732000_329.webp"
                    alt="">
                <div class="title col">标记设置</div>
                <IconDelete class="btn" style="font-size: 12px;" @click="removeMark" />
            </div>
        </div>
        <div class="text-right">
            <el-checkbox v-model="updateStatus">同步更新</el-checkbox>
        </div>
        <div class="attr-items flex items-center q-mt-lg">
            <div style="font-size: 11px;width:50px;">定位</div>
            <el-select v-model="attrs.selectObj" filterable size="mini" remote reserve-keyword placeholder="输入关键字" @change="setLocationHandler" :remote-method="searchPoiInfoHandler"  :loading="searchLoading">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
        </div>
        <div class="attr-items flex items-center q-mt-lg">
            <div style="font-size: 11px;width:50px;">边框</div>
            <div class="col flex">
                <IconMinus class="handler-item viewport-size q-mr-md pointer" @click="AddSubtract('-',0)"/>
                <Slider class="filter-slider" :max="10" :min="0" :step="1" :value="attrs.strokeWidth"
                @update:value="value => updateFilter(0, value as number)" />
                <IconPlus class="handler-item viewport-size q-ml-md pointer" @click="AddSubtract('+',0)"/>
            </div>
        </div>
        <div class="attr-items flex items-center q-mt-lg">
            <div style="font-size: 11px;width:50px;">大小</div>
            <div class="col flex">
                <IconMinus class="handler-item viewport-size q-mr-md pointer" @click="AddSubtract('-',1)"/>
                <Slider class="filter-slider grow" :max="5" :min="0.1" :step="0.1" :value="attrs.scale"
                @update:value="value => updateFilter(1, value as number)" />
                <IconPlus class="handler-item viewport-size q-ml-md pointer" @click="AddSubtract('+',1)"/>
            </div>
        </div>
        <div class="attr-items flex items-center q-mt-lg grey-bg">
            <div style="font-size: 11px; " class="col">文字</div>
            <Switch :value="attrs.textEnable"  @update:value="value => changeLabelStatus(value)"  />
        </div>
        <div v-if="attrs.textEnable" class="grey-bg"  style="border-top: 1px solid rgba(204, 204, 204, .3);border-bottom:  1px solid rgba(204, 204, 204, .3);">
            <div class="attr-items q-mt-md grey-bg">
                <el-input input-style="border: none !important; background: none !important;" v-model="attrs.fontText" :rows="3" @input="setLabelTextHandler" type="textarea" placeholder="文字..." />
            </div>
            <div class="attr-items flex items-center grey-bg">
                <div style="font-size: 11px;width:50px;">大小</div>
                <div class="col flex">
                    <IconMinus class="handler-item viewport-size q-mr-md pointer" @click="AddSubtract('-',2)"/>
                    <Slider class="filter-slider grow" :max="72" :min="12" :step="1" :value="attrs.fontSize" 
                    @update:value="value => {updateLabFontSizeHandler(value as number),attrs.fontSize=value}" />
                    <IconPlus class="handler-item viewport-size q-ml-md pointer" @click="AddSubtract('+',2)"/>
                </div>
            </div>
            <div class="attr-items flex items-center grey-bg q-mt-lg">
                <div style="font-size: 11px;width:50px;">加粗</div>
                <div class="col flex">
                    <IconMinus class="handler-item viewport-size q-mr-md pointer" @click="AddSubtract('-',3)"/>
                    <Slider class="filter-slider grow" :max="800" :min="400" :step="200" :value="attrs.fontWeight" 
                    @update:value="value => {updateLabFontSizeHandler(value as number),attrs.fontWeight=value}" />
                    <IconPlus class="handler-item viewport-size q-ml-md pointer" @click="AddSubtract('+',3)"/>
                </div>
            </div>
            
            <div class="attr-items flex items-center q-mt-md">
                <div style="font-size: 11px;width:50px;">字体</div>
                <el-select size="mini" v-model="attrs.fontFamily" filterable @change="val=>updateLabFontFamilyHandler(val as number)" placeholder="请选择">
                    <el-option v-for="item in formatFonts" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
            <div class="attr-items flex items-center q-mt-md">
                <div style="font-size: 11px;width:50px;">对齐</div>
                <el-select size="mini" v-model="attrs.fontAlign" @change="val=>setAlignChangeHandler(val as number)" placeholder="请选择">
                    <el-option v-for="item in positions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
            <div class="attr-items flex items-center q-mt-md">
                <div class="color-box  q-mr-lg">
                    <Popover trigger="mouseenter" class="full-height full-width">
                        <template #content>
                            <ColorPicker :modelValue="attrs.fontColor" @update:modelValue="value => setLabelColorHandler(value)"/>
                        </template>
                        <div class="full-height full-width" style="border:1px solid #EEE;" :style="{backgroundColor:attrs.fontColor}"></div>
                    </Popover>
                </div>
                <div style="font-size: 11px; color: grey;">文字颜色：{{ attrs.fontColor }}</div>
            </div>

        </div>
        <div class="attr-items flex items-center q-mt-lg">
            <div class="color-box  q-mr-lg">
                <Popover trigger="mouseenter" class="full-height full-width">
                    <template #content>
                        <ColorPicker :modelValue="attrs.stroke" @update:modelValue="value => updateStrokeHandler(value)"/>
                    </template>
                    <div class="full-height full-width" style="border:1px solid #EEE;" :style="{backgroundColor:attrs.stroke}"></div>
                </Popover>
            </div>
            <div style="font-size: 11px; color: grey;">边框颜色：{{ attrs.stroke }}</div>
        </div>
        <div class="attr-items flex items-center q-mt-md q-mb-md">
            <div class="color-box  q-mr-lg">
                <Popover trigger="mouseenter" class="full-height full-width">
                    <template #content>
                        <ColorPicker :modelValue="attrs.fill" @update:modelValue="value => updateFillHandler(value)"/>
                    </template>
                    <div class="full-height full-width" style="border:1px solid #EEE;" :style="{backgroundColor:attrs.fill}"></div>
                </Popover>
            </div>
            <div style="font-size: 11px; color: grey;">填充颜色：{{ attrs.fill }}</div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { useMapStore } from '@/store/index'
import { storeToRefs } from 'pinia';
import { inject, reactive, ref } from 'vue';
import tinycolor from 'tinycolor2';
import { color as am4coreColor,Label} from "@amcharts/amcharts4/core";
import { watch } from 'vue';
import MapService from '@/services/MapService';
import { useFontStore } from '@/store'
const mapStore = useMapStore()
const { current,fillColor } = storeToRefs(mapStore)
const { formatFonts } = storeToRefs(useFontStore())
const attrs = reactive({
    arrow:-1,
    textEnable:false,
    fontSize:12,
    fontWeight:400,
    fontFamily: '',
    fontAlign:0,
    fontText:'',
    fontColor:'#000',
    selectObj:''
} as any)
const options = ref<{label:string,value:string,center:number[]}[]>([])
const changeMarkStyleToCurrent = inject("changeMarkStyleToCurrent",()=>{})
const updateStatus = ref(false)
const searchLoading = ref(false)
const icons = ref<string[]>(['icon-arrow-left','icon-arrow-right','icon-arrow-leftright','icon-arrow-middle'])
const positions = ref<{label:string,value:number}[]>([{label:'底部',value:0},{label:'顶部',value:1},{label:'靠右',value:2},{label:'靠左',value:3}])

const AddSubtract = (symbol: string,val: number) => {
    let value
    if(val==0){
        if(symbol=='-'&&attrs.strokeWidth>0){
            attrs.strokeWidth--
        }if(symbol=='+'&&attrs.strokeWidth<10){
            attrs.strokeWidth++
        }
        value =  attrs.strokeWidth
        updateFilter(0, value as number)
    }if(val==1){
        if(symbol=='-'&&attrs.scale>0.1){
            let scale = (attrs.scale*100)-(0.1*100)
            attrs.scale = scale/100
        }if(symbol=='+'&&attrs.scale<5){
            attrs.scale = attrs.scale+0.1
        }
        value =  attrs.scale
        updateFilter(1, value as number)
    }if(val==2){
        if(symbol=='-'&&attrs.fontSize>12){
            attrs.fontSize--
        }if(symbol=='+'&&attrs.fontSize<72){
            attrs.fontSize++
        }
        value =  attrs.fontSize
        updateLabFontSizeHandler(value as number)
    }if(val==3){
        if(symbol=='-'&&attrs.fontWeight>400){
            attrs.fontWeight = attrs.fontWeight-200
        }if(symbol=='+'&&attrs.fontWeight<800){
            attrs.fontWeight = attrs.fontWeight+200
        }
        value =  attrs.fontWeight
        updateLabFontWeightHandler(value as number)
    }
}
const updateFilter = (t: number, val: number) => {
    switch (t) {
        case 0:
            attrs.strokeWidth = val
            break;
        case 1:
            attrs.scale = val
            setTimeout(() => {
                calcLabelLocal(undefined,-1)
            }, 500);
            break;
        default:
            break;
    }
    updateLineStyle(current.value)
}
const updateFillHandler = (val:any) =>{
    attrs.fill = val
    attrs.fillOpacity = tinycolor(val).getAlpha()
    updateLineStyle(current.value)
}
const updateStrokeHandler = (val:any) =>{
    attrs.stroke = val
    attrs.strokeOpacity = tinycolor(val).getAlpha()
    updateLineStyle(current.value)
}
const updateLineStyle = (lineObj:any)=>{
    let chi =  lineObj.mapImages.getIndex(0).children.getIndex(0)
    let tempChi = lineObj.mapImages.template.children.getIndex(0)
    chi.strokeWidth= attrs.strokeWidth
    chi.strokeOpacity = attrs.strokeOpacity
    chi.stroke = am4coreColor(tinycolor(attrs.stroke).toHexString())
    chi.scale = attrs.scale
    chi.fillOpacity = attrs.fillOpacity
    chi.fill = am4coreColor(tinycolor(attrs.fill).toHexString())

    tempChi.strokeWidth= attrs.strokeWidth
    tempChi.strokeOpacity = attrs.strokeOpacity
    tempChi.stroke = am4coreColor(tinycolor(attrs.stroke).toHexString())
    tempChi.scale = attrs.scale
    tempChi.fillOpacity = attrs.fillOpacity
    tempChi.fill = am4coreColor(tinycolor(attrs.fill).toHexString())
    asyncAllMarkHandler()
}

const createLabel = ()=>{
    let labelChildren = current.value!.mapImages.create();
    labelChildren.latitude = current.value.data[0].latitude;
    labelChildren.longitude = current.value.data[0].longitude;

    let label = labelChildren.createChild(Label)
    label.horizontalCenter = "middle";
    // label.verticalCenter = "top";
    label.fontSize = 13;
    label.fontFamily = 'pingfangr'
    label.fill = am4coreColor(fillColor.value.realColor)
    label.text= '文字内容'
    //label.fontWeight = 'bold'

    attrs.fontSize = 13
    attrs.fontWeight = 400
    attrs.fontFamily = 'Microsoft Yahei'
    attrs.fill = fillColor.value.realColor
    attrs.text = '文字内容'
    attrs.fontAlign = 0
    labelChildren.children.getIndex(0).hide()
    calcLabelLocal(label,0)
}

const calcLabelLocal = (label?:Label,align:number=0) =>{
    if(!label){
        label = getCurrentLabel()
        align = align==-1 && label ? label!.marginBottom as number:align
    }
    
    if(label){
        let scale = current.value.mapImages.template.children.getIndex(0).scale
        let radius = current.value.mapImages.template.children.getIndex(0).radius
        radius = radius==10?10:35
        let temp = radius*scale
        let increment = radius==10?10:0
        if(align==0){
            label.y = temp
            label.paddingLeft = temp
            label.x = 0 - (increment*.5)
        } else if(align==1){
            label.y = -(label.fontSize*1.33) - increment
            label.paddingLeft = temp
            label.x = 0 - (increment*.5)
        } else if(align==2){
            label.y = ((temp-label.fontSize - increment)/2)-(label.fontSize*0.2)
            label.x = ((label.fontSize*label.text.length)/2)+temp+(increment*.5)
            label.paddingLeft = 0
        } else if(align==3){
            label.y = ((temp-label.fontSize - increment)/2)-(label.fontSize*0.2)
            label.x = (-label.fontSize*label.text.length)/2 - (increment*1.5)
            label.paddingLeft = 0
        }
        label.marginBottom=align
    }
    
}

const searchPoiInfoHandler = async (val:string)=>{
    if(val=='') return
    searchLoading.value = true
    let response = await MapService.queryPlaceInfoAsync(val)
    options.value = response
    searchLoading.value=false
}

const setLocationHandler = (value:string)=>{
    if(value!='' && options.value && options.value.length>0){
        let temp = options.value.find(x=>x.value==value)
        if(temp){
            current.value.data = [{
                longitude:temp.center[0],
                latitude:temp.center[1]
            }]
        }
    }
}

const changeLabelStatus = (val:boolean)=>{
    attrs.textEnable=val
    if(val) {
        createLabel()
    } else {
        current.value.mapImages.removeIndex(1)
    }
    asyncAllMarkHandler()
}
const updateLabFontSizeHandler = (val:number) =>{
    let lab = getCurrentLabel()
    if(lab){
        lab.fontSize=val
        setTimeout(() => {
            calcLabelLocal(undefined,-1)
            asyncAllMarkHandler()
        }, 500);
    }
}
const updateLabFontWeightHandler = (val:number) =>{
    let lab = getCurrentLabel()
    if(lab){
        lab.fontWeight=val
        setTimeout(() => {
            asyncAllMarkHandler()
        }, 500);
    }
}
const updateLabFontFamilyHandler = (val:number) =>{
    let lab = getCurrentLabel()
    if(lab){
        lab.fontFamily=val
        setTimeout(() => {
            asyncAllMarkHandler()
        }, 500);
    }
}
const setLabelTextHandler = (val:string)=>{
    let lab = getCurrentLabel()
    if(lab){
        lab.text=val
        calcLabelLocal(lab,lab.marginBottom)
        asyncAllMarkHandler()
    }
}
const setAlignChangeHandler = (val:number)=>{
    calcLabelLocal(undefined,val)
    asyncAllMarkHandler()
}
const setLabelColorHandler = (val:string)=>{
    let lab = getCurrentLabel()
    if(lab){
        lab.fill = am4coreColor(tinycolor(val).toHex8String())
        attrs.fontColor = tinycolor(val).toHex8String()
        asyncAllMarkHandler()
    }
}

const getCurrentLabel = ()=>{
    let c = current.value
    if(c.mapImages.length>1 && c.mapImages.getIndex(1).children.length>1){
        return c.mapImages.getIndex(1).children.getIndex(1)
    }
    return null
}
const setAttribute = ()=>{
    let c = current.value
    let chi = c.mapImages.template.children.getIndex(0)
    attrs.strokeWidth=chi.strokeWidth
    attrs.stroke=tinycolor(chi.stroke.hex).setAlpha(chi.strokeOpacity).toHex8String()
    attrs.strokeOpacity=chi.strokeOpacity
    attrs.scale=chi.scale
    attrs.fill=tinycolor(chi.fill.hex).setAlpha(chi.fillOpacity).toHex8String()
    attrs.fillOpacity=chi.fillOpacity
    let lab = getCurrentLabel()
    if(lab){
        attrs.textEnable = true
        attrs.fontText = lab.text
        attrs.fontSize = lab.fontSize??15
        attrs.fontWeight = lab.fontWeight??400
        attrs.fontFamily = lab.fontFamily??'Microsoft Yahei'
        attrs.fontAlign = lab.marginBottom
        attrs.fontColor = tinycolor(lab.fill?.hex??'#000000').toHex8String()
        //attrs.fontSize = 
    }else{
        attrs.textEnable = false
    }
    
}
const removeMark = ()=>{
    mapStore.setRemoveMark(current.value)
}

const asyncAllMarkHandler = ()=>{
    if(updateStatus.value){
        changeMarkStyleToCurrent()
    }
}
setAttribute()

watch(()=>current.value,()=>{
    setAttribute()
})
</script>