<template>
  <div class="th-tileset-list">
    <ThCard empty="true" v-if="withCreate">
      <div class="full new" @click="showNewTilesetDlg">
        <div class="th-icon th-icon-create inline"></div>
        <div>新建瓦片</div>
      </div>
    </ThCard>
    <ThCard type="vector" :size="size" v-for="item in tilesetList" :key="item.tilesetId" :info="item" @on-name-change="nameChange($event, item)" @on-default-click="preview(item)">
      <template #action>
        <Icon class="cursor" title="预览" custom="iconfont icon-play" size="20" @click.stop="preview(item)"></Icon>
        <HoverPopup>
          <ThMenuItem width="60" name="替换" icon="relativity" @on-click="tilesetReplace(item)" />
          <ThMenuItem width="60" name="删除" icon="delete" color="#F65450" @on-click="tilesetDelete(item)" />
          <div class="developer">
            <div class="text">瓦片调用接口</div>
            <TextCopy :text="`${API}/${item.owner}/${item.tilesetId}/tilejson`"/>
          </div>
        </HoverPopup>
      </template>
    </ThCard>
    <li></li><li></li><li></li><li></li><li></li>
    <input id="tileset-select" ref="tilesetSelect" type="file" accept=".mbtiles" @change="tilesetSelectChange">
    <Loading :show="showLoading"/>
  </div>
</template>

<script>
import config from '../../constants/config'
import util from '../../libs/util'
import ThCard from '../th-card'
import HoverPopup from '../hover-popup'
import ThMenuItem from '../th-menu-item'
import TextCopy from '../text-copy'
import Loading from '../loading'
import {tilesetUpdate, tilesetDelete, tilesetCreate} from '../../libs/request'
export default {
  props: ['tilesetList','withCreate','size','sortBy'],
  components:{
    Loading,
    ThCard,
    HoverPopup,
    ThMenuItem,
    TextCopy
  },
  methods: {
    showNewTilesetDlg() {
      this.actionTileset = null
      this.$nextTick(() => { // 等待dom更新完成
        this.$refs.tilesetSelect.click()
      })
    },
    tilesetReplace(item) {
      this.actionTileset = item
      this.$nextTick(() => { // 等待dom更新完成
        this.$refs.tilesetSelect.click()
      })
    },
    tilesetSelectChange(e) {
      const files = e.target.files
      if (!files.length) {
        return
      }
      if (this.actionTileset) { // 替换
        let {owner, name, tilesetId} = this.actionTileset
        this.showLoading = true
        tilesetCreate(owner, tilesetId, files[0], name).then(() => {
          this.showLoading = false
          this.$emit('on-refersh')
          this.$Modal.success({
            title: "替换成功",
            content: ''
          });
        }).catch(err => {
          this.showLoading = false
          this.$Modal.error({
            title: "替换失败",
            content: err.message
          });
        })
      } else { // 新建
        let request = []
        for(let i = 0; i < files.length; i++) {
          let ownerId = config.USER
          let nameArray = files[i].name.split('.')
          let name = nameArray[0].replace(/\s+/g,"_")
          let tilesetId = `${name}-${util.generateId()}`
          request.push(tilesetCreate(ownerId, tilesetId, files[i], name))
        }
        this.showLoading = true
        Promise.all(request).then(() => {
          this.showLoading = false
          this.$emit('on-refersh')
          this.$Modal.success({
            title: "上传成功",
            content: ''
          });
        }).catch(err => {
          this.showLoading = false
          this.$Modal.error({
            title: "上传失败",
            content: err.message
          });
        })
      }
      this.$refs.tilesetSelect.value = null
    },
    tilesetDelete(item) {
      this.actionTileset = item
      this.$Modal.confirm({
        title: '确定要删除吗？',
        content: '<p>该操作无法恢复，请谨慎操作！</p>',
        onOk: () => {
          let ownerId = config.USER
          tilesetDelete(ownerId, this.actionTileset.tilesetId).then(res => {
            this.$Message.success('删除成功')
          })
        }
      })
    },
    preview(item) {
      let ownerId = config.USER
      window.open(`${util.getAPI('tilesets')}/${ownerId}/${item.tilesetId}/html`)
    },
    nameChange: function(name, item) {
      let ownerId = config.USER
      let {tilesetId} = item
      tilesetUpdate(ownerId,tilesetId,{ name }).then(res => {
        this.$emit('on-update', {tilesetId, data: res.data})
      })
    }
  },
  data() {
    return {
      actionTileset: null,
      multiple: true, // 文件是否支持多选
      API: `${util.getAPI('tilesets')}`,
      showLoading: false
    }
  },
  computed: {
  }
} 
</script>
