<template>
  <div class="container">
    <div class="toolbar">
      <el-button
        type="primary"
        size="mini"
        @click="saveDiyComponent"
      >保存</el-button>
    </div>
    <CreationCampComponent class="right-content" />
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import CreationCampComponent from '../applet/CreationCamp/index.vue'
import Applet from '@/api/Applet'
import Custom from '@/api/Custom.js'
export default {
  components: {
    CreationCampComponent
  },
  data () {
    return {
      customParams: {
        current: 1,
        map: {},
        model: {
          config: '',
          isCustom: true,
          isDelete: 0,
          name: ''
        },
        order: 'descending',
        size: 100,
        sort: 'id'
      },
      componentTemplateId: null,
      currentId: ''
    }
  },
  computed: {
    ...mapState('creationCamp', ['diyComponents'])
  },
  beforeDestroy() {
    this.initComponents([])
  },
  created () {
    this.init()
    this.getTemplatePage()
  },
  methods: {
    ...mapMutations('creationCamp', ['initComponents', 'initTemplatePage', 'clearFooterComponents']),
    async init () {
      this.clearFooterComponents()
      this.initComponents([])
      this.currentId = this.$route.params.id
      if (!this.currentId) return false
      const res = await Applet.getCmsTemplate(this.currentId)
      const resData = res.data.data
      const componentTemplate = resData.config
      let templateParse = []
      try {
        const templateConfig = JSON.parse(componentTemplate)
        templateParse = templateConfig instanceof Array ? templateConfig : []
      } catch (e) {
        templateParse = []
      }
      this.initComponents(templateParse)
      this.componentTemplateId = resData.id
    },
    // 获取跳转路径列表
    async getTemplatePage () {
      const res = await Custom.cmsTemplatePage(this.customParams)
      const templatePage = res.data.data.records || []
      const templates = templatePage.map(item => {
        const { name, config } = item
        return {
          value: config,
          label: name
        }
      })
      this.initTemplatePage(templates)
    },
    // 保存装修
    async saveDiyComponent () {
      const diyComponentsString = JSON.stringify(this.diyComponents)
      const res = await Applet.updateTemplate({
        config: diyComponentsString,
        id: this.componentTemplateId
      })
      const resData = res.data
      const { code } = resData
      if (code === 0) {
        this.$message({
          message: this.$t('tips.saveSuccess'),
          type: 'success'
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  .toolbar {
    padding: 12px;
    text-align: right;
    border-bottom: 1px solid #eee;
  }
  .right-content {
    flex: 1;
  }
}
</style>
