<template>
  <div class="th-style-list">
    <ThCard empty="true" v-if="withCreate">
      <div class="full new" @click="showNewStyleDlg">
        <Icon name="新建"/>
        <div>新建地图</div>
      </div>
    </ThCard>
    <ThCard type="map" :size="size" v-for="item in styleList" :key="item.styleId" :info="item" :nameEditable="styleScope==='private'" @on-default-click="clickItem(item)" :class="selectedItem===item.styleId?'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="styleDuplicate(item)" v-if="styleScope==='private'"/>
          <ThMenuItem width="60" name="替换" icon="relativity" @on-click="replaceStyle(item)" v-if="styleScope==='private'"/>
          <ThMenuItem width="60" name="下载" icon="download" :disabled="!item.hasPublished" @on-click="styleDownload(item)" />
          <ThMenuItem width="60" name="撤销" icon="history" :disabled="!item.hasPublished || !item.hasDrafted" @on-click="styleBackToLastVersion(item)" v-if="styleScope==='private'"/>
          <ThMenuItem width="60" name="删除" icon="delete" color="#F65450" @on-click="deleteStyle(item)" v-if="styleScope==='private'" />
          <div class="developer">
            <div class="text">地图调用接口</div>
            <TextCopy :text="`${API}/${item.owner}/${item.styleId}`" v-if="item.hasPublished"/>
            <TextCopy text="地图尚未发布" v-else/>
          </div>
        </HoverPopup>
      </template>
    </ThCard>
    <input id="style-replace-select" ref="styleReplaceSelect" type="file" accept="application/json" @change="styleReplaceChange">
    <NewMapModal type="bmap" ref="newStyleModal" @on-refersh="refreshStyleList"/>
  </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 {styleLoad,styleReplace,spriteDuplicate,styleDelete} 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: ['styleList','size','sortBy','withCreate','styleScope'],
  components: {
    NewMapModal,
    ThCard,
    HoverPopup,
    ThMenuItem,
    TextCopy,
    DateShower
  },
  methods: {
    showNewStyleDlg() {
      this.$refs.newStyleModal.show()
    },
    refreshStyleList(){
      this.$emit('on-refersh')
    },
    clickItem(item){
      if(this.size==='small'){
        this.$emit("on-selected",item)
        this.selectedItem=item.styleId
      }else{
        this.styleEdit(item)
      }
    },
    async styleDuplicate(item) {
      this.actionStyle = item
      let {styleId, hasDrafted} = item
      let ownerId = config.USER
      let suffix = hasDrafted ? '.draft' : ''
      /*let trueId = sceneId + suffix*/
      let copyId = util.generateId() + suffix
      try {
        // 获取要复制的地图
        let { data: style } = await styleLoad(
          ownerId,
          styleId,
          hasDrafted,
          false
        )
        let copyRequest = []
        // 修改地图的名称和符号库
        style.name += '_副本'
        if (style.sprite) {
          style.sprite = `${util.getAPI('sprites')}/${ownerId}/${copyId}/sprite`
          copyRequest.push(spriteDuplicate(ownerId, copyId, styleId + suffix))
        }
        // 开始复制
        copyRequest.push(styleReplace(ownerId, copyId, style))
        await Promise.all(copyRequest)
        this.$Modal.success({
          title: "复制成功",
          content: ''
        });
        this.$emit('on-refersh')
      } catch (err) {
        console.error(err)
        this.$Modal.error({
          title: '发生错误',
          content: err.message
        });
      }
    },
    replaceStyle(item) {
      this.actionStyle = item
      this.$refs.styleReplaceSelect.click()
    },
    styleReplaceChange(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 stylesheet = JSON.parse(result)
          let ownerId = config.USER
          let styleId = this.actionStyle.styleId
          stylesheet.name = this.actionStyle.name
          styleReplace(ownerId, styleId+'.draft', stylesheet).then(() => {
            this.$emit('on-refersh')
            this.$Modal.success({
              title: "替换成功",
              content: ''
            });
          })
        }
        this.$refs.styleReplaceSelect.value = null
      }).catch(error => {
        this.$Modal.error({
          title: '发生错误',
          content: error.message
        });
        this.$refs.styleReplaceSelect.value = null
      })
    },
    deleteStyle(item) {
      this.actionStyle = item
      this.$Modal.confirm({
        title: '确定要删除吗？',
        content: '<p>该操作无法恢复，请谨慎操作！</p>',
        onOk: async() => {
          let ownerId = config.USER
          let {styleId, hasDrafted, hasPublished} = this.actionStyle
          let request = []
          if (hasDrafted) {
            request.push(styleDelete(ownerId, styleId, true))
          }
          if (hasPublished) {
            request.push(styleDelete(ownerId, styleId, false))
          }
          await Promise.all(request).then(() => {
            this.$emit('on-refersh')
          })
        }
      })
    },
    styleEdit(item) {
      let ownerId = config.USER
      window.open(`../bmap/#/studio/styles/${ownerId}/${item.styleId}/edit`)
    },
    preview(item) {
      let ownerId = config.USER
      window.open(`${util.getAPI('styles')}/${ownerId}/${item.styleId}.draft/html`)
    },
    async styleDownload(item) {
      if (!item.hasPublished) {
        return
      }
      let {owner, styleId} = item
      let {data} = await styleLoad(owner, styleId, false)
      let currStyle = JSON.stringify(data, null, 2)
      var eleLink = document.createElement('a')
      eleLink.download = (data.name || '未命名') + '.json'
      eleLink.style.display = 'none'
      var blob = new Blob([currStyle])
      eleLink.href = URL.createObjectURL(blob)
      document.body.appendChild(eleLink)
      eleLink.click()
      document.body.removeChild(eleLink)
    },
    styleBackToLastVersion(item) { // 必须既有draft版本又有publish版本才能撤销
      if (!item.hasPublished || !item.hasDrafted) {
        return
      }
      let {styleId}=item
      this.$Modal.confirm({
        title: `确定要撤销修改吗？`,
        content: '<p>该操作无法恢复，请谨慎操作！</p>',
        onOk: async() => {
          let ownerId = config.USER
          try {
            let { data: style } = await styleLoad(ownerId, styleId, false)
            styleReplace(ownerId, styleId+'.draft', style)
            .then(() => {
              this.$emit('on-refersh')
              this.$Modal.success({
                  title: "已回溯到上一个已发布的版本",
                  content: ''
              });
            })
          } catch (err) {
            console.error(err)
            this.$Modal.error({
              title: '发生错误',
              content: err.message
            });
          }
        }
      })
    },
  },
  mounted() {
  },
  data() {
    return {
      API: `${util.getAPI('styles')}`,
      selectedItem:"",
    }
  },
  computed: {
  }
} 
</script>
