<template>
  <div class="head">
    <div class="head_actions head_left">
      <div class="head_btn"
           :class="{'head_btn--active':contain.menuShow}"
           @click="handleFlag('menuShow')">
        <el-tooltip effect="dark"
                    content="图层"
                    placement="top">
          <el-icon>
            <el-icon-operation></el-icon-operation>
          </el-icon>
        </el-tooltip>
      </div>
      <div class="head_btn"
           :class="{'head_btn--active':contain.paramsShow}"
           @click="handleFlag('paramsShow')">
        <el-tooltip effect="dark"
                    content="操作"
                    placement="top">
          <el-icon>
            <el-icon-setting></el-icon-setting>
          </el-icon>
        </el-tooltip>
      </div>
      <!-- 主题切换器 -->
      <div class="head_btn">
        <ThemeSwitcher />
      </div>
    </div>
    <div class="head_info">
      <el-icon>
        <el-icon-data-analysis></el-icon-data-analysis>
      </el-icon>
      <span>Learun-{{contain.config.title}}</span>
    </div>
    <div class="head_actions">
      <div class="head_btn"
           @click="contain.$refs.excel.handleOpen()">
        <el-tooltip effect="dark"
                    content="excel解析"
                    placement="top">
          <svg-icon icon-class="excel" />
        </el-tooltip>
      </div>
      <div class="head_btn">
        <el-tooltip effect="dark"
                    content="保存"
                    placement="top">
          <el-popconfirm title="是否保存缩略图?"
                         confirm-button-text="是"
                         cancel-button-text="否"
                         @confirm="handleSave(true)"
                         @cancel="handleSave(false)">
            <template #reference>
              <i class="iconfont icon-save"></i>
            </template>
          </el-popconfirm>
        </el-tooltip>
      </div>
      <div class="head_btn">
        <el-tooltip effect="dark"
                    content="清空画布"
                    :width="200"
                    placement="top">
          <el-popconfirm title="是否清空当前画布?"
                         @confirm="handleClear()">
            <template #reference>
              <el-icon>
                <el-icon-delete></el-icon-delete>
              </el-icon>
            </template>
          </el-popconfirm>

        </el-tooltip>
      </div>
      <div class="head_btn"
           @click="handleKeys">
        <el-tooltip effect="dark"
                    content="快捷键"
                    placement="top">
          <i class="iconfont icon-ele"></i>
        </el-tooltip>
      </div>
      <div class="head_btn">
        <el-tooltip effect="dark"
                    content="导出大屏截图"
                    placement="top">
          <el-popconfirm title="是否导出大屏当前截图?"
                         :width="200"
                         @confirm="handleImg()">
            <template #reference>
              <el-icon>
                <el-icon-camera></el-icon-camera>
              </el-icon>
            </template>
          </el-popconfirm>

        </el-tooltip>
      </div>
      <div class="head_btn"
           @click="handleView"
           v-show="contain.menuFlag">
        <el-tooltip effect="dark"
                    content="预览"
                    placement="top">
          <i class="iconfont icon-view"></i>
        </el-tooltip>
      </div>
      <div class="head_btn"
           @click="handleReset"
           v-show="!contain.menuFlag">
        <el-tooltip effect="dark"
                    content="还原"
                    placement="top">
          <i class="iconfont icon-reset"></i>
        </el-tooltip>
      </div>
      <div class="head_btn"
           @click="$refs.result.show=true">
        <el-tooltip effect="dark"
                    content="导入导出"
                    placement="top">
          <el-icon>
            <el-icon-download></el-icon-download>
          </el-icon>
        </el-tooltip>
      </div>
      <div class="head_btn"
           @click="handleShare">
        <el-tooltip effect="dark"
                    content="发布"
                    placement="top">
          <el-icon>
            <el-icon-share></el-icon-share>
          </el-icon>
        </el-tooltip>
      </div>

      <div class="head_btn"
           @click="handleGoIndex">
        <el-tooltip effect="dark"
                    content="主页"
                    placement="top">
          <el-icon>
            <el-icon-home-filled></el-icon-home-filled>
          </el-icon>
        </el-tooltip>
      </div>
    </div>
    <result ref="result"></result>
    <share ref="share"></share>
    <keys ref="keys"></keys>

  </div>
</template>

<script>
import { dataURLtoFile } from '@/utils/utils'
import result from './result.vue';
import { uploadImg, updateComponent } from '@/api/visual'
import share from './share.vue'
import keys from './keys.vue'
import ThemeSwitcher from '../components/ThemeSwitcher.vue'

export default {
  inject: ["contain"],
  data () {
    return {
      loading: null,
      minWidth: 0,
      maxWidth: 0,
      selectDialog: {
        visible: false,
        id: ''
      }
    }
  },
  components: {
    result,
    share,
    keys,
    ThemeSwitcher
  },
  created () {
    if (this.$website.autoSave) {
      setInterval(() => {
        this.handleBuild({ tip: false });
      }, this.$website.autoSaveTime)
    }

  },
  methods: {
    handleGoIndex () {
      this.$router.push({ path: '/' })
    },
    handleClear () {
      this.contain.nav = []
      this.$message.success('画布清空成功')
    },
    handleKeys () {
      this.$refs.keys.show = true;
    },
    handleReset () {
      this.contain.menuFlag = true;
      this.handleSet()
    },
    handleFlag (name) {
      this.contain[name] = !this.contain[name]
      this.handleSet()
    },
    handleView () {
      this.contain.menuFlag = false;
      this.handleSet()
    },
    handleSet (select = true) {
      this.$nextTick(() => {
        if (select) this.contain.handleInitActive();
        const screensRect = this.contain.$refs.screensRef.getBoundingClientRect();
        this.contain.setScale(screensRect.width);
      })
    },
    handleSave (flag) {
      if (!flag) {
        return this.handleBuild()
      }
      this.loading = this.$loading({
        lock: true,
        text: '正在保存配置，请稍后',
        spinner: 'el-icon-loading',
        background: 'var(--color-overlay)'
      });
      this.exportImg().then(canvas => {
        var file = dataURLtoFile(canvas.toDataURL('image/jpeg', 0.1), this.contain.config.title + '.jpg');
        var formdata = new FormData();
        formdata.append('file', file)
        uploadImg(formdata).then(res => {
          const data = res.data.data;
          const url = data.link;
          this.handleBuild({ url })
        })
      })
    },
    handleBuild (params = {}) {
      const { fn, tip = true, init = false, url } = params
      if (init) this.contain.handleInitActive();
      if (tip) {
        this.loading = this.$loading({
          lock: true,
          text: '正在保存配置，请稍后',
          spinner: 'el-icon-loading',
          background: 'var(--color-overlay)'
        });
      }
      const formdata = {
        visual: {
          id: this.contain.id,
          version: this.contain.config.version,
          backgroundUrl: url || this.contain.config.backgroundUrl
        },
        config: {
          id: this.contain.visualId,
          visualId: this.contain.id,
          detail: JSON.stringify(this.contain.config),
          component: JSON.stringify(this.contain.nav),
        },
      }
      updateComponent(formdata).then(() => {
        if (fn && typeof (fn) === 'function') {
          fn && fn()
        } else if (tip) {
          this.$message.success('大屏配置保存成功');
        }
      }).catch(err => {
        console.log(err)
        this.$message.error('大屏配置保存失败')
      }).finally(() => {
        this.loading && this.loading.close();
      });

    },
    exportImg () {
      return new Promise((resolve, reject) => {
        html2canvas(document.querySelector('.canvas'), {
          useCORS: true,
          backgroundColor: null,
          logging: false,
          allowTaint: true
        }).then(canvas => {
          resolve(canvas)
        }).catch(err => {
          reject(err)
        })
      })
    },
    handleImg () {
      this.exportImg().then(canvas => {
        this.downFile(canvas.toDataURL("image/jpeg", 0.8), this.contain.config.title + '.jpg');
        this.$message.success('图片导出成功')
      }).catch(() => {
        this.$message.error('图片导出失败')
      });
    },
    handleShare () {
      this.$refs.share.handleShow()
    }
  }
}
</script>

<style lang="scss">
.head {
  position: relative;
  height: 41px;
  padding-right: 8px;
  display: flex;
  z-index: 100;
  align-items: center;
  user-select: none;
  color: var(--datav-gui-font-color-base);
  border-bottom: var(--datav-border-dark);
  background: var(--bg-color-secondary);
  &_actions {
    position: absolute;
    top: 0;
    right: 8px;
    width: 300px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    height: 40px;
  }
  &_left {
    left: 8px;
    justify-content: flex-start;
  }
  &_btn {
    margin-left: 4px;
    width: 40px;
    height: 24px;
    line-height: 26px;
    text-align: center;
    cursor: pointer;
    background: var(--bg-color-tertiary);
    transition: 0.2s;
    i {
      color: var(--text-color-primary);
    }
    &--active {
      background-color: var(--primary-color);
    }
  }
  &_info {
    position: absolute;
    left: 50%;
    top: 0;
    transform: translateX(-50%);
    text-align: center;
    cursor: default;
    font-size: 14px;
    max-width: 500px;
    font-weight: bold;
    color: var(--text-color-primary);
    line-height: 40px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: flex;
    align-items: center;
    i {
      margin-right: 8px;
      font-size: 20px;
    }
  }
}
</style>