<template>
  <div v-loading="templatLoading" class="activity-template">
    <div class="operation-but">
      <el-select
        v-model="selectedLang"
        size="mini"
        style="width: 100px"
      >
        <el-option v-for="item in langs" :key="item.value" :label="item.name" :value="item.value" />
      </el-select>
      <el-button size="mini" type="primary" :loading="formSubmitLoading" :disabled="formSubmitLoading" @click="clickSubmit">保存</el-button>
      <el-button size="mini" type="danger" @click="clickExit">退出</el-button>
    </div>
    <el-row style="height: 100%;">
      <el-col class="activity-layout flex-c" :md="14" :xs="24">
        <div class="workspace">
          <page-editor :key="pageIndex" :index-data="treeMap" :select-el-id="selectElId" :lang="selectedLang" />
        </div>
      </el-col>
      <el-col class="activity-layout flex-c" :md="4" :xs="24">
        <div class="in-stock">
          <el-tree
            :data="templateTreeIndexs"
            default-expand-all
            highlight-current
            :expand-on-click-node="false"
            @node-click="clickTreeindexNode"
          />
        </div>
      </el-col>
      <el-col class="activity-conf" :md="6" :xs="24">
        <attr-editor :form="selectedIndexNode" @attr-change="attrChange" />
      </el-col>
    </el-row>

  </div>
</template>

<script>
import PageEditor from './page-editor'
import AttrEditor from './attr-editor'
import { mobile } from '@/utils/device'
import { giftRankingTreeIndexs, langs } from '@/constant/activity-template'
import { getTemplateById } from '@/api/sys'
import { updateTemplate } from '@/api/sys'

export default {
  name: 'ActivityTemplateForm',
  components: { PageEditor, AttrEditor },
  props: {
    templateId: {
      type: String,
      require: true,
      default: ''
    }
  },
  data() {
    return {
      mobile: mobile(),
      formSubmitLoading: false,
      pageIndex: 1,
      selectedLang: 'zh',
      selectElId: '',
      selectedIndexNode: {},
      langs,
      treeMap: {},
      templatLoading: false,
      template: {},
      templateTreeIndexs: giftRankingTreeIndexs,
      destroy: null
    }
  },
  watch: {
    templateId: {
      handler(newVal) {
        if (!newVal) {
          return
        }
        this.loadTemplate()
      },
      immediate: true
    }
  },
  created() {
    const that = this
    if (that.mobile) {
      that.$message('建议您使用PC电脑进行编辑!')
    }
  },
  mounted() {
    this.destroy = this.stopWindowClosing(true)
  },
  destroyed() {
    if (this.destroy) {
      this.destroy()
    }
  },
  methods: {
    stopWindowClosing(unsaved) {
      const handler = (e) => {
        if (unsaved) {
          e.preventDefault()
          e.returnValue = ''
          return ''
        }
      }
      window.addEventListener('beforeunload', handler)
      return () => {
        window.removeEventListener('beforeunload', handler)
      }
    },
    loadTemplate() {
      const that = this
      that.templatLoading = true
      getTemplateById(that.templateId).then(res => {
        that.templatLoading = false
        that.template = res.body || {}
        that.templateTreeIndexs = that.template.indexTree && that.template.indexTree.length > 0 ? that.template.indexTree : giftRankingTreeIndexs
        that.treeMap = that.toTreeIndexsMap()
        that.switchSelectedIndexData(that.templateTreeIndexs[0])
      }).catch(er => {
        that.templatLoading = false
      })
    },
    toTreeIndexsMap() {
      const that = this
      const resultMap = {}
      forEachTree(that.templateTreeIndexs)

      function forEachTree(tree) {
        if (!tree) {
          return
        }
        tree.forEach(item => {
          if (!item.editor) {
            resultMap[item.id] = {
              attr: {
                id: item.id,
                label: item.label
              }
            }
          } else {
            item.editor.attr.id = item.id
            item.editor.attr.label = item.label
            resultMap[item.id] = item.editor
          }
          if (item.children && item.children.length > 0) {
            forEachTree(item.children)
          }
        })
      }
      return resultMap
    },
    clickTreeindexNode(data, node, thisComponent) {
      this.switchSelectedIndexData(data)
      this.pageIndex += 1
    },
    switchSelectedIndexData(data) {
      this.selectElId = data.id
      if (!data.editor) {
        this.selectedIndexNode = {
          attr: {
            id: data.id,
            label: data.label
          }
        }
        return
      }
      this.selectedIndexNode = data.editor
      this.selectedIndexNode.attr.id = data.id
      this.selectedIndexNode.attr.label = data.label
    },
    attrChange(form) {
      if (form.attr.id.startsWith('ACTIVITY_BODY_REWARD_CARD')) {
        this.pageIndex += 1
      }
    },
    clickSubmit() {
      const that = this
      if (this.formSubmitLoading || !that.template) {
        return
      }
      that.formSubmitLoading = true
      that.template.indexTree = that.templateTreeIndexs || []
      // that.template.rewardLadders = that.treeMap['ACTIVITY_BODY_REWARD'].attr.rewards || []
      updateTemplate(that.template).then(res => {
        that.formSubmitLoading = false
      }).catch(er => {
        console.loe(er)
        that.formSubmitLoading = false
      })
    },
    clickExit() {
      if (this.destroy) {
        this.destroy()
      }
      this.clickSubmit()
      this.$emit('close')
    },
    startCallBack() {
      this.$refs.luckyWheel.play()
      setTimeout(() => {
        this.$refs.luckyWheel.stop(Math.random() * 8 >> 0)
      }, 3000)
    }
  }
}
</script>

<style scoped lang="scss">
.activity-template {
  position: absolute;
  overflow: auto;
  left: 0;
  top: 40px;
  right: 0px;
  bottom: 0px;
  .operation-but{
    background-color: rgba(231,236,236,.418);
    position: fixed;
    top: 50px;
    bottom: 0px;
    right: 0px;
    left: 0px;
     z-index: 100;
    padding: 5px 20px;
    text-align: right;
    height: 40px;
    border-bottom: 1px solid #dee4ec;
  }
  .form {
    height: 100%;
    overflow: auto;
  }
  .in-stock {
    width: 100%;
    height: 100%;
    overflow: auto;
    position:absolute;
    top: 0px;
  }
  .activity-layout{
    height: 100%;
    position: relative;
    background-color: rgba(231, 236, 236, 0.418);
    .workspace {
      width: 540px;
      max-width: 100%;
      height: 100%;
      overflow: auto;
      position: relative;
    }
    .luck-conf {
      margin: auto;
    }
  }

  .activity-conf {
    position: relative;
    height: 100%;
    overflow: auto;
  }
}

</style>
