<template>
  <Modal class="th-new-map" v-model="showNewForm" title="选择地图模板" width="1000" :styles="{top: '60px'}" :mask-closable="false">
    <div class="templates">
      <TemplateItem :data="emptyStyle" :active="emptyStyle.styleId === selectedTemplateId" @on-click="selectTemplate" />
      <TemplateItem v-for="template in templates" :key="template.id" :data="template" :active="template.styleId === 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="styleUploadControl" type="file" accept="application/json" @change="onStyleUploadChange">
      <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 { getStyleList, styleLoad ,styleCreate} 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.styleId
    },
    onNewMap() {
      let ownerId = config.USER
      if (this.selectedTemplateId === 'empty_map') {
        let emptyStyle = {
          name: '空模板',
          version: 8,
          center: [0, 0],
          zoom: 1,
          sources: {},
          layers: [{
            id: 'background',
            type: 'background',
            paint: {
              'background-color': 'rgba(0,0,0,0)'
            }
          }]
        }
        styleCreate(ownerId, emptyStyle).then(res => {
          this.$emit('on-refersh',res.data)
          this.transitionToEdit(res.data.styleId.replace('.draft', ''))
        }),
        this.hide()
      } else {
        const selectedTemplate = this.templates.find(template => template.styleId === this.selectedTemplateId)
        let { styleId, owner } = selectedTemplate
        styleLoad(owner, styleId).then(res => {
          let template = res.data
          delete template.glyphs
          styleCreate(ownerId, template).then(res => {
            this.$emit('on-refersh',res.data)
            this.transitionToEdit(res.data.styleId.replace('.draft', ''))
          }),
          this.hide()
        })
      }
    },
    clickSelectFileBtn() {
      this.$refs.styleUploadControl.click()
    },
    onStyleUploadChange(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 stylesheet = JSON.parse(result)
          if (!stylesheet.name) {
            stylesheet.name = file.name
          }
          let ownerId = config.USER
          styleCreate(ownerId, stylesheet).then(res => {
            this.$emit('on-refersh')
            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(styleId) {
      let ownerId = config.USER
      const newStyleUri = `../bmap/#/styles/${ownerId}/${styleId}/edit`
      window.open(newStyleUri, '_blank')
    },
    async loadTemplates(){
      let {data} = await getStyleList(config.PUBLIC_COUNT)
      this.templates = data.filter(d => d.styleId.indexOf('.draft') === -1)
    }
  },
  mounted() {
    this.loadTemplates()
  },
  data() {
    return {
      showNewForm: false,
      templates: [],
      selectedTemplateId: 'empty_map',
      validateFileMsg: '',
      emptyStyle: {
        name: '空模板',
        styleId: 'empty_map'
      }
    }
  }
}
</script>
