<template>
    <div class="script-form bg-white rounded  light-shadow">
        <div class="q-pa-md">
            <div class="text-h6">行程表单</div>
            <div class="text-small q-mt-lg">你需要的国家：</div>
            <el-select class="full-width" size="large" collapse-tags multiple filterable v-model="attrs.selectedCountries"
                placeholder="请选择">
                <el-option :label="item.label" :value="item.value" v-for="(item, index) in attrs.countriesData"
                    :key="index" />
            </el-select>
            <div class="text-small q-mt-lg">你需要的城市：</div>
        </div>
        <el-scrollbar class="q-pa-md full-width" max-height="50vh">
            <el-autocomplete v-for="(x, i) in attrs.cities" v-model="x.label" size="large" class="full-width q-mb-md"
                label="label" value-key="label" :fetch-suggestions="querySearchAsync" placeholder="请输入城市名称"
                @select="(item: Record<string, any>) => citySelectHandler(item, i)">
                <template #suffix>
                    <div class="row items-center">
                        <el-icon class="el-input__icon cusor-pointer" size="20px" title="上移" v-if="i > 0"
                            @click.stop="() => changePoiHandler(i, 'up')">
                            <Top />
                        </el-icon>
                        <el-icon class="el-input__icon cusor-pointer" size="18px" title="下移"
                            v-if="i < attrs.cities.length - 1" @click.stop="() => changePoiHandler(i, 'down')">
                            <Bottom />
                        </el-icon>
                        <el-icon class="el-input__icon cusor-pointer" color="#409eff" size="16px" title="新增"
                            @click.stop="() => createNewCity(i + 1)">
                            <Plus />
                        </el-icon>
                        <el-icon class="el-input__icon cusor-pointer" color="#d14424" size="16px" title="删除"
                            @click.stop="() => removeHandler(i)" v-if="attrs.cities.length > 1">
                            <Delete />
                        </el-icon>
                    </div>
                </template>

                <template #prefix>
                    <div class="text-small">{{ i + 1 }}</div>
                </template>
            </el-autocomplete>
        </el-scrollbar>
        <div class="q-pa-md q-mt-lg text-right">
            <el-button link size="small" class="q-mr-md" @click="closeHandler">取消</el-button>
            <el-button type="primary" size="small" :loading="loading" @click="()=>finishHandler()">开始创建</el-button>
        </div>
    </div>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue";
import { useMapStore } from "@/store/index";
import { storeToRefs } from "pinia";
import MapService from "@/services/MapService";
import { Plus, Top, Bottom, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

const attrs = reactive({
    selectedCountries: [],
    countriesData: [] as any[],
    cities: [] as { label: string; data: any }[],
} as any);

const emit = defineEmits<{
  (event: 'close'): void,
  (event: 'finish',playload:any): void
}>()

const mapStore = useMapStore();
const { allCountries } = storeToRefs(mapStore);
const loading = ref(false)
const resolveCountries = () => {
    attrs.countriesData = [];
    if (allCountries.value) {
        Object.keys(allCountries.value).forEach(function (key: string) {
            attrs.countriesData.push({
                value: key,
                label: allCountries.value![key],
            });
        });
    }
};
const querySearchAsync = async (
    queryString: string,
    cb: (arg: any) => void
) => {
    let response = await MapService.queryPlaceInfoAsync(queryString);

    cb(response);
};
const citySelectHandler = (item: Record<string, any>, i: number) => {
    attrs.cities[i].data = item;
};
const createNewCity = (index = -1) => {
    let city = {
        label: "",
        data: null,
    };
    if (index == -1) {
        attrs.cities.push(city);
    } else {
        attrs.cities.splice(index, 0, city);
    }
};
const removeHandler = (index: number) => {
    attrs.cities.splice(index, 1);
};
const changePoiHandler = (index: number, align: string) => {
    let targetIndex = align == "up" ? index - 1 : index + 1;
    let tempData = JSON.parse(JSON.stringify(attrs.cities[targetIndex]));
    attrs.cities[targetIndex] = JSON.parse(JSON.stringify(attrs.cities[index]));
    attrs.cities[index] = tempData;
};
const closeHandler= ()=>{
    emit('close')
}
const finishHandler = ()=>{
    if(!loading.value){
        loading.value=true
        let msg = ''
        if(!attrs.selectedCountries||attrs.selectedCountries.length==0){
            msg = '至少应该选择一个国家'
        } else {
            let index = attrs.cities.findIndex((x:any)=>x.label=='' || !x.data)
            msg = index==-1?'':`请完善或删除第${index+1}个城市`
        }
        if(msg!=''){
            ElMessage.error({
                message: msg,
            })
        }else{
            let r = {
                countries:attrs.selectedCountries,
                cities:attrs.cities
            }
            emit('finish',r)
        }
        loading.value=false
    }
}
createNewCity();
resolveCountries();
</script>
<style>
.script-form {
    position: absolute;
    z-index: 9;
    top: 5px;
    right: 5px;
    width: 320px;
    max-height: 80vh;
    overflow-y: auto;
}

.cusor-pointer {
    cursor: pointer;
}
</style>
