<template>
  <avue-form-design
    style="height: 100vh"
    :show-github-star="false"
    :storage="false"
    :options="options"
    :attrs="allAttrs"
    ref="formDesign"
    :toolbar="toolbar"
    model="list"
    :includeFields="includeFields"
    :customFields="customFields"
    aside-left-width="270px">
    <template slot="toolbar-left">
      <span style="margin-right:10px">树形控件:</span>
      <el-switch
        v-model="showTree">
      </el-switch>
      <el-button
        style="margin-left:10px"
        type="text"
        icon="el-icon-success"
        @click="handleSaveData">保存数据</el-button>
    </template>
    <template slot="toolbar">
      <el-button
        style="margin-left:10px"
        type="text"
        icon="el-icon-files"
        @click="handlePublic">发布</el-button>
    </template>
  </avue-form-design>
</template>

<script type="text/ecmascript-6">
import { getAttrs, saveTableData, getTbaleModel } from '@/api/model/genenrteTable'
import { updateModel } from '@/api/model/modelManger'

export default {
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.from = from
    })
  },
  beforeRouteLeave(to, from, next) {
    // 销毁组件，避免通过vue-router再次进入时，仍是上次的history缓存的状态
    this.$destroy(true)
    next()
  },
  data() {
    return {
      attrs: [],
      showTree: true,
      options: {
        column: [
          {
            type: 'trees',
            label: '',
            span: 8,
            display: true,
            dicData: [],
            parent: true,
            cascaderItem: [],
            props: { label: 'label', value: 'value' },
            prop: 'a16424135317574993',
            dicProp: { model: '', modelid: '', modelpid: '', modelname: '' },
            dicOption: 'remote'
          },
          {
            type: 'dynamic',
            label: '',
            span: 16,
            display: true,
            children: {
              align: 'center',
              headerAlign: 'center',
              index: false,
              addBtn: true,
              delBtn: true,
              column: []
            },
            prop: '1642398752094_92175'
          }
        ],
        labelPosition: 'left',
        labelSuffix: '：',
        labelWidth: 100,
        gutter: 0,
        menuBtn: true,
        submitBtn: false,
        submitText: '提交',
        emptyBtn: false,
        emptyText: '清空',
        menuPosition: 'center'
      },
      toolbar: ['generate', 'preview'],
      optionsSession: {},
      includeFields: [],
      allAttrs: [],
      customFields: []
    }
  },
  computed: {
    tableTata() {
      return this.$store.state.table.tableTata
    },
    table_tree_id() {
      return this.$store.state.table.table_tree_id
    }
  },
  watch: {
    showTree: {
      immediate: true,
      handler(val) {
        this.$store.dispatch('setShowTree', val)
        if (val) {
          this.$set(this.options.column[0], 'span', 16)
          this.options.column.unshift({
            type: 'trees',
            label: '',
            span: 8,
            display: true,
            dicData: [],
            parent: true,
            cascaderItem: [],
            props: { label: 'label', value: 'value' },
            prop: 'a16424135317574993',
            dicProp: { model: '', modelid: '', modelpid: '', modelname: '' },
            table_tree_id: this.table_tree_id,
            dicOption: 'remote'
          })
        } else {
          this.$set(this.options.column.filter((item) => item.type === 'dynamic')[0], 'span', 24)
          this.options.column.length > 1 && this.options.column.splice(0, 1)
        }
      }
    },
    tableTata: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        this.customFields = this.allAttrs.filter((attr) => !newVal.some(val => val.prop === attr.prop))
      }
    }
  },
  beforeMount() {
    Object.assign(this.$data, this.$options.data())
  },
  mounted() {
    this.getModelId()
  },
  methods: {
    getModelId() {
      const id = this.$route.query.id
      this.getTbaleModel(id)
      this.getAttrs(id)
    },
    getTbaleModel(modelId) {
      getTbaleModel({ modelId }).then(res => {
        if (res.code === 200) {
          const { data } = res
          const hasData = Object.keys(data).length >= 0
          if (hasData) {
            this.showTree = data.column.filter(item => item.type === 'trees').length > 0
            if (this.showTree) {
              data.column.filter(item => item.type === 'trees')[0].span = 8
              data.column.filter(item => item.type === 'dynamic')[0].span = 16
              const treesId = data.column.filter(item => item.type === 'trees')[0].table_tree_id
              this.$store.dispatch('setTableTreeId', treesId)
            } else {
              data.column.filter(item => item.type === 'dynamic')[0].span = 24
            }
            const _column = data.column.filter(item => item.type === 'dynamic')[0].children.column
            for (let i = 0; i < _column.length; i++) {
                _column[i].filter = JSON.parse(_column[i].filter)
                _column[i].fixed = JSON.parse(_column[i].fixed)
                _column[i].sortable = JSON.parse(_column[i].sortable)
              }
            this.options = data
          }
        }
      })
    },
    getAttrs(modelId) {
      getAttrs({ modelId }).then(res => {
        if (res.code === 200) {
          this.attrs = res.rows
          this.generateCustomFields()
        }
      })
    },
    getData() {
      return this.$refs.formDesign.getData('json')
    },
    handleSaveData() {
      this.getData().then(data => {
        saveTableData({
          modelId: this.$route.query.id,
          ...data
        }).then((res) => {
          if (res.code === 200) {
            this.$message.success('保存成功')
            // this.$router.push({ path: '/standard/formModel' })
          }
        })
      })
    },
    generateCustomFields() {
      this.attrs.map((filed) => {
        this.allAttrs.push({
          type: 'attrs',
          label: filed.attr_name,
          span: 24,
          display: true,
          prop: filed.id,
          icon: 'el-icon-menu',
          status: filed.status,
          sortable: true,
          fixed: false,
          filter: false
        })
      })
      this.customFields = this.allAttrs
      .filter(attr => !this.options.column
      .filter(item => item.type === 'dynamic')[0].children.column
      .some(val => val.prop === attr.prop))
    },
    handlePublic() {
      updateModel({ id: this.$route.query.id, listPageStatus: '1' }).then((res) => {
        if (res.code === 200) {
          this.$message.success('发布成功')
          this.$router.push({ path: '/standard/formModel' })
        }
      })
    }
  }
}
</script>

<style scoped></style>
