<template>
  <div class="th-map-list">
    <ThCard empty="true" v-if="withCreate">
      <div class="full new" @click="showNewMapDlg">
        <Icon name="新建"/>
        <div>新建专题地图</div>
      </div>
    </ThCard>
    <ThCard type="map" :size="size" v-for="item in mapList" :key="item.mapId" :info="item" :nameEditable="mapScope==='private'" @on-default-click="clickItem(item)" :class="selectedItem===item.mapId?'activeStyle':''">
      <template #action>
        <Icon class="cursor" title="预览" custom="iconfont icon-play" size="20" @click.stop="preview(item)"></Icon>
        <HoverPopup width="120">
          <ThMenuItem width="60" name="复制" icon="copy" @on-click="mapDuplicate(item)" v-if="mapScope==='private'"/>
          <ThMenuItem width="60" name="替换" icon="relativity" @on-click="replaceMap(item)" v-if="mapScope==='private'"/>
          <ThMenuItem width="60" name="下载" icon="download" :disabled="!item.hasPublished" @on-click="mapDownload(item)" />
          <ThMenuItem width="60" name="撤销" icon="history" :disabled="!item.hasPublished || !item.hasDrafted" @on-click="mapBackToLastVersion(item)" v-if="mapScope==='private'"/>
          <ThMenuItem width="60" name="删除" icon="delete" color="#F65450" @on-click="mapDelete(item)" v-if="mapScope==='private'"/>
          <div class="developer">
            <div class="text">地图调用接口</div>
            <TextCopy :text="`${API}/${item.owner}/${item.mapId}`" v-if="item.hasPublished"/>
            <TextCopy text="地图尚未发布" v-else/>
          </div>
        </HoverPopup>
      </template>
    </ThCard>
    <li :class="size==='small'?'small-li':''"></li><li :class="size==='small'?'small-li':''"></li><li :class="size==='small'?'small-li':''"></li><li :class="size==='small'?'small-li':''"></li><li :class="size==='small'?'small-li':''"></li><li :class="size==='small'?'small-li':''"></li>
    <input id="map-replace-select" ref="mapReplaceSelect" type="file" accept="application/json" @change="mapReplaceChange">
    <NewMapModal type="vmap" ref="NewMapModal" @on-refersh="refreshMapList"/>
  </div>
</template>

<script>
import config from '../../constants/config'
import { validate } from '@mapbox/mapbox-gl-style-spec'
import NewMapModal from '../new-map-modal'
import util from '../../libs/util'
import {mapLoad,spriteDuplicate,mapReplace,mapDelete} from '../../libs/request'
import ThCard from '../th-card'
import HoverPopup from '../hover-popup'
import ThMenuItem from '../th-menu-item'
import TextCopy from '../text-copy'
import DateShower from '../date-shower'
export default {
  props: ['mapList', 'mode','size','sortBy','withCreate','mapScope'],
  components: {
    NewMapModal,
    ThCard,
    HoverPopup,
    ThMenuItem,
    DateShower,
    TextCopy
  },
  methods: {
    showNewMapDlg() {
      this.$refs.NewMapModal.show()
    },
    refreshMapList() {
      this.$emit('on-refersh')
    },
    clickItem(item){
      if(this.size==='small'){        
        this.selectedItem=item.mapId
        this.$emit("on-selected",item)
      }else{
        this.mapEdit(item)
      }
    },
    async mapDuplicate(item) {
      this.actionMap = item
      let {mapId, hasDrafted} = item
      let ownerId = config.USER
      let suffix = hasDrafted ? '.draft' : ''
      /*let trueId = sceneId + suffix*/
      let copyId = util.generateId() + suffix
      try {
        // 获取要复制的地图
        let { data: map } = await mapLoad(
          ownerId,
          mapId,
          hasDrafted,
          false
        )
        let copyRequest = []
        // 修改地图的名称和符号库
        map.name += '_副本'
        if (map.sprite) {
          map.sprite = `${util.getAPI('sprites')}/${ownerId}/${copyId}/sprite`
          copyRequest.push(spriteDuplicate(ownerId, copyId, mapId + suffix))
        }
        // 开始复制
        copyRequest.push(mapReplace(ownerId, copyId, map))
        await Promise.all(copyRequest)
        this.$emit('on-refersh')
      } catch (err) {
        console.error(err)
        this.$Modal.error({
          title: '发生错误',
          content: err.message
        });
      }
    },
    replaceMap(item) {
      this.actionMap = item
      this.$refs.mapReplaceSelect.click()
    },
    mapReplaceChange(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.$Modal.error({
            title: '发生错误',
            content: errors[0]
        });
        } else {
          var mapsheet = JSON.parse(result)
          let ownerId = config.USER
          let mapId = this.actionMap.mapId
          mapsheet.name = this.actionMap.name
          mapReplace(ownerId, mapId+'.draft', mapsheet).then(() => {
            this.$emit('on-refersh')
            this.$Modal.success({
              title: "替换成功",
              content: ''
            });
          })
        }
        this.$refs.mapReplaceSelect.value = null
      }).catch(error => {
        this.$Modal.error({
          title: '发生错误',
          content: error.message
        });
        this.$refs.mapReplaceSelect.value = null
      })
    },
    mapDelete(item) {
      this.actionMap = item
      this.$Modal.confirm({
        title: '确定要删除吗？',
        content: '<p>该操作无法恢复，请谨慎操作！</p>',
        onOk: async() => {
          let ownerId = config.USER
          let {mapId, hasDrafted, hasPublished} = this.actionMap
          let request = []
          if (hasDrafted) {
            request.push(mapDelete(ownerId, mapId, true))
          }
          if (hasPublished) {
            request.push(mapDelete(ownerId, mapId, false))
          }
          await Promise.all(request).then(() => {
            this.$emit('on-refersh')
          })
        }
      })
    },
    mapEdit(item) {
      // let ownerId = config.USER
      let url=window.location.origin+"/vmap"
      window.open(`${url}/#/${item.mapId}`)
    },
    preview(item) {
      //let ownerId = config.USER
      let url=window.location.origin+"/vmap"
      window.open(`${url}/#/${item.mapId}`)
    },
    async mapDownload(item) {
      if (!item.hasPublished) {
        return
      }
      let {owner, mapId} = item
      let {data} = await mapLoad(owner, mapId, false)
      let currMap = JSON.stringify(data, null, 2)
      var eleLink = document.createElement('a')
      eleLink.download = (data.name || '未命名') + '.json'
      eleLink.style.display = 'none'
      var blob = new Blob([currMap])
      eleLink.href = URL.createObjectURL(blob)
      document.body.appendChild(eleLink)
      eleLink.click()
      document.body.removeChild(eleLink)
    },
    mapBackToLastVersion(item) { // 必须既有draft版本又有publish版本才能撤销
      if (!item.hasPublished || !item.hasDrafted) {
        return
      }
      let {mapId} = item
      this.$Modal.confirm({
        title: `确定要撤销修改吗？`,
        content: '<p>该操作无法恢复，请谨慎操作！</p>',
        onOk: async() => {
          let ownerId = config.USER
          try {
            let { data: map } = await mapLoad(ownerId, mapId, false)
            mapReplace(ownerId, mapId+'.draft', map)
            .then(() => {
              this.$emit('on-refersh')
              this.$Modal.success({
                  title: "已回溯到上一个已发布的版本",
                  content: ''
              });
            })
          } catch (err) {
            console.error(err)
            this.$Modal.error({
              title: '发生错误',
              content: err.message
            });
          }
        }
      })
    }
  },
  data() {
    return {
      API: `${util.getAPI('maps')}`,
      selectedItem:""
    }
  },
  computed: {
  },
} 
</script>
