<template>
  <Modal class="th-new-map" v-model="showNewForm" title="选择专题地图模板" width="1000" :styles="{ top: '60px' }" :mask-closable="false">
    <div class="templates">
      <TemplateItem :data="emptyMap" :active="emptyMap.mapId === selectedTemplateId" @on-click="selectTemplate" />
      <TemplateItem v-for="template in templates" :key="template.id" :data="template" :active="template.mapId === selectedTemplateId" @on-click="selectTemplate" />
      <li></li> <li></li> <li></li> <li></li> <li></li>
    </div>
    <template #footer>
      <Button type="primary" @click="clickSelectFileBtn" style="float: left;">从样式文件创建</Button>
      <span class="error" :title="validateFileMsg" v-if="validateFileMsg">{{validateFileMsg}}</span>
      <input id="style-upload-input" ref="mapUploadControl" type="file" accept="application/json" @change="onMapUploadChange">
      <Button color="#89B9F3" textColor="#ffffff" @click="hide">取消</Button>
      <Button type="primary" @click="onNewMap">创建</Button>
    </template>
  </Modal>
</template>

<script>
import util from '../../libs/util'
import config from '../../constants/config'
import { validate } from '@mapbox/mapbox-gl-style-spec'
import { getMapList, mapLoad,mapCreate } from '../../libs/request'
import TemplateItem from './TemplateItem.vue'
export default {
  components: {
    TemplateItem
  },
  methods: {
    show() {
      this.showNewForm = true
      this.loadTemplates()
    },
    hide() {
      this.validateFileMsg = ''
      this.selectedTemplateId = 'empty_map'
      this.showNewForm = false
    },
    selectTemplate(item) {
      this.selectedTemplateId = item.mapId
    },
    onNewMap() {
      let ownerId = config.USER
      if (this.selectedTemplateId === 'empty_map') {
        let emptyMap = {
          basemap: {
            style:{
              version: 8,
              sources: {},
              layers: [{
              id: 'background',
              type: 'background',
              paint: {
                'background-color': 'rgba(0,0,0,0)'
              }
              }]
            }
          },
          center: [0, 0],
          zoom: 1,
          pitch:0,
          bearing:0,
          name: "空模板",
          layers: []
        }
        mapCreate(ownerId, emptyMap).then(res => {
          this.$emit('on-refersh',res.data)
          this.transitionToEdit(res.data.mapId.replace('.draft', ''))
        }),
        this.hide()
      } else {
        const selectedTemplate = this.templates.find(template => template.mapId === this.selectedTemplateId)
        let { mapId, owner } = selectedTemplate
        mapLoad(owner, mapId).then(res => {
          let template = res.data
          delete template.glyphs
          mapCreate(ownerId, template).then(res => {
            this.$emit('on-refersh',res.data)
            this.transitionToEdit(res.data.mapId.replace('.draft', ''))
          }),
          this.hide()
        })
      }
    },
    clickSelectFileBtn() {
      this.$refs.mapUploadControl.click()
    },
    onMapUploadChange(e) {
      const files = e.target.files
      let file = files[0]
      // validate
      if (!file) {
        return
      }
      util.readFile(file).then(result => {
        var errors = validate(result)
        if (errors.length) {
          this.validateFileMsg = '该地图样式文件无效，无法上传。'
        } else {
          this.validateFileMsg = ''
          var mapsheet = JSON.parse(result)
          if (!mapsheet.name) {
            mapsheet.name = file.name
          }
          let ownerId = config.USER
          mapCreate(ownerId, mapsheet).then(res => {
            this.$emit('on-refersh',res.data)
            this.transitionToEdit(res.data.mapId.replace('.draft', ''))
          }),
          this.hide()
        }
        e.target.value = ''
      }).catch(error => {
        console.error(error)
        this.validateFileMsg = error.message
        e.target.value = ''
      })
    },
    transitionToEdit(mapId) {
      // let ownerId = config.USER
      let url=window.location.origin+"/vmap"
      const newMapUri = `${url}/#/${mapId}`
      window.open(newMapUri, '_blank')
    },
    async loadTemplates(){
      let {data} = await getMapList(config.PUBLIC_COUNT)
      this.templates = data.filter(d => d.mapId.indexOf('.draft') === -1)
    }
  },
  mounted() {
    this.loadTemplates()
  },
  data() {
    return {
      showNewForm: false,
      templates: [],
      selectedTemplateId: 'empty_map',
      validateFileMsg: '',
      emptyMap: {
        name: '空模板',
        mapId: 'empty_map'
      }
    }
  }
}
</script>

