<template>
  <div>
    <!--头部,搜索框-->
    <div class="search-bar-box clearfix">
      <h4>使用泽元提供的专业模板</h4>
      <div @keydown.enter="onSearch">
        <el-input placeholder="请输入关键字搜索模板" v-model="searchText" class="input-with-select">
          <el-button @click="onSearch" slot="append"><i class="fa fa-fw fa-search"></i> 搜索</el-button>
        </el-input>
      </div>
    </div>

    <!--内容部分-->
    <div class="layout-row-main" style="margin-top: 0;">

      <!--分类标签选择区域-->
      <div class="temp-left">
        <el-card :body-style="{padding: '0 20px 14px 0'}">
          <h4 slot="header"><i class="fa fa-fw fa-cubes"></i>&nbsp;场景分类</h4>
          <el-menu class="layout-menu" :default-active="condition.scene?condition.scene.ID.toString():'0'" @select="onSelectScene">
            <el-menu-item :index="scene.ID.toString()" v-for="(scene, i) in scenes" :key="scene.ID + '-' + i">{{scene.name}}</el-menu-item>
          </el-menu>
        </el-card>
        <el-card :body-style="{padding: '0 20px 14px 0'}">
          <h4 slot="header"><i class="fa fa-fw fa-cogs"></i>&nbsp;行业分类</h4>
          <el-menu class="layout-menu" :default-active="condition.type?condition.type.ID.toString():'0'" @select="onSelectType">
            <el-menu-item :index="type.ID.toString()" v-for="(type, i) in types" :key="type.ID + '-' + i">{{type.name}}</el-menu-item>
          </el-menu>
        </el-card>
      </div>

      <!--主体内容区-->
      <div class="temp-main">

        <!--模板列表区-->
        <div class="temp-list-box">
          <div class="temp-condition">
            <span class="condition-item condition-type">{{condition.scene.ID||condition.type.ID||condition.search?'选择:':'全部'}}</span>
            <button class="condition-item" @click="onRemoveCondition('scene')" v-if="condition.scene.ID">{{condition.scene.name}}</button>
            <button class="condition-item" @click="onRemoveCondition('type')" v-if="condition.type.ID">{{condition.type.name}}</button>
            <button class="condition-item" @click="onRemoveCondition('search')" v-if="condition.search">{{condition.search}}</button>
            <button class="condition-item" @click="onRemoveCondition('id')" v-if="condition.tempId">ID: {{condition.tempId}}</button>
          </div>
          <ul class="temp-list">
            <li v-for="i in condition.pageSize" :key="(temps[i-1]?temps[i-1].ID:Math.random())+'-'+i" :class="{'temp-list-item':true,'selected':temps[i-1]?(temps[i-1].ID===selectedTempId):false}">
              <a v-if="temps[i-1]" class="temp-list-item-content" @click="selectedTempId=temps[i-1].ID" href="javascript: void(0)">{{temps[i-1].name}}</a>
              <a v-else class="temp-list-item-content" href="javascript: void(0)"></a>
            </li>
          </ul>
          <el-pagination background layout="prev, pager, next" :page-size="condition.pageSize" :total="condition.count" @current-change="index => condition.pageIndex = index"></el-pagination>
        </div>

        <!--模板预览区-->
        <div class="temp-content">
          <div class="temp-content-header">
            <h4 class="temp-content-header-name" v-if="selectedTemp">{{selectedTemp.name}}</h4>
            <el-button type="primary" plain native-type="button" @click="openTemp">使用此模板</el-button>
          </div>
          <div class="temp-content-body" ref="form-box"></div>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import $ZF from './libs/zform.js'
const $ = window.$
const axios = window.axios

export default {
  props: {
    tempId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      scenes: [], // 场景类型列表
      types: [], // 行业类型列表
      temps: [], // 模板列表
      searchText: '', // 搜索框内容

      // 搜索条件
      condition: {
        scene: {
          ID: 0
        },
        type: {
          ID: 0
        },
        tempId: '',
        search: '',
        pageIndex: 1,
        pageSize: 10,
        count: 0
      },
      selectedTempId: 0, // 当前选中的模板id
      selectedTempData: null, // 当前模板数据
      tempCache: {},
      selectedTemp: null,
      ok: false,
      submitting: false,
      httpTask: null,
      name
    }
  },
  watch: {
    temps: {
      handler () {
        this.onTempsChange()
      },
      deep: true
    },
    'condition.search': 'onConditionChange',
    'condition.scene': 'onConditionChange',
    'condition.type': 'onConditionChange',
    'condition.tempId': 'onConditionChange',
    'condition.pageIndex': 'onPageChange',
    'selectedTempId': 'onTempChange'
  },
  /**
     * 初始化,后期改为从后台获取数据
     */
  mounted () {
    this.init()
  },
  methods: {
    async init () {
      this.condition.tempId = this.tempId
      let res = await axios.get('/ui/customforms/customFormType/treeData?editFlag=Y')
      res = res.data
      if (res.status === 1) {
        this.types = res.data[0].children
        this.scenes = res.data[1].children
        this.onConditionChange()
        this.selectedTempId = parseInt(this.ID) || this.selectedTempId
      } else {
        this.$alert(res.message, '错误', {confirmButtonText: '确定'})
      }
    },

    /**
       * 场景分类点击事件
       */
    onSelectScene (id) {
      this.condition.scene = this.scenes.find(t => t.ID.toString() === id)
    },

    /**
       * 行业分类点击事件
       */
    onSelectType (id) {
      this.condition.type = this.types.find(t => t.ID.toString() === id)
    },

    /**
       * 搜索按钮点击,或搜索框中回车,添加搜索内容到过滤条件
       */
    onSearch () {
      this.condition.search = this.searchText
      this.searchText = ''
    },

    /**
       * 条件变化,初始化页码,重新获取模板数据
       */
    onConditionChange () {
      this.condition.pageIndex = 1
      this.getTemps()
    },

    /**
       * 模板数据发生变化时,重置当前模板id,默认选择第一个
       */
    onTempsChange () {
      if (this.condition.tempId && !isNaN(parseInt(this.condition.tempId))) {
        this.selectedTempId = parseInt(this.condition.tempId)
      } else if (this.temps && this.temps.length) {
        this.selectedTempId = this.temps[0].ID
      } else {
        this.selectedTempId = -1
      }
    },

    /**
       * 移除过滤条件
       * @param key 移除类型
       */
    onRemoveCondition (key) {
      switch (key) {
        case 'scene':
          this.condition.scene = {ID: 0}
          break
        case 'type':
          this.condition.type = {ID: 0}
          break
        case 'search':
          this.condition.search = ''
          break
        case 'id':
          this.condition.tempId = ''
          break
      }
    },

    /**
       * 页码发生变化,重新获取数据
       */
    onPageChange () {
      this.getTemps()
    },

    /**
       * 页码发生变化,重新获取数据(做防重复提交和防抖处理)
       */
    getTemps () {
      const task = function () {
        this.submitting = true
        axios.get('/ui/customforms/templates', {
          params: {
            name: encodeURIComponent(this.condition.search),
            order: 'default',
            industryInnercode: this.condition.type.innerCode,
            sceneInnercode: this.condition.scene.innerCode,
            pageSize: this.condition.pageSize,
            pageIndex: this.condition.pageIndex - 1,
            tempId: this.condition.tempId
          }
        }).then(res => {
          this.submitting = false
          this.temps = res.data.data
        })
      }.bind(this)

      if (!this.submitting) {
        if (this.httpTask) {
          clearTimeout(this.httpTask)
        }
        this.httpTask = setTimeout(task, 300)
      }
    },

    /**
       * 获取模板数据(做防重复提交和防抖处理)
       */
    async onTempChange () {
      this.selectedTemp = null

      if (this.selectedTempId) {
        if (this.tempCache[this.selectedTempId]) {
          this.selectedTemp = this.tempCache[this.selectedTempId]
          this.selectedTempData = $ZF.zcmsDataFormat(JSON.parse(this.selectedTemp.content))
          $ZF.createForm(this.$refs['form-box'], this.selectedTempData)
          $(this.$refs['form-box']).find('form').css('pointer-events', 'none')
        } else {
          const task = function () {
            axios.get(`/ui/customforms/templates/${this.selectedTempId}`).then(res => {
              this.tempCache[this.selectedTempId] = this.selectedTemp = res.data.data
              this.selectedTempData = $ZF.zcmsDataFormat(JSON.parse(this.selectedTemp.content))
              $ZF.createForm(this.$refs['form-box'], this.selectedTempData)
              $(this.$refs['form-box']).find('form').css('pointer-events', 'none')
            })
          }.bind(this)

          if (!this.submitting) {
            if (this.httpTask) {
              clearTimeout(this.httpTask)
            }
            this.httpTask = setTimeout(task, 300)
          }
        }
      }
    },

    /**
       * 打开模板
       */
    openTemp () {
      if (!this.ok) {
        this.ok = true
        this.$prompt('请输入名称', '创建表单', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /[\S]{3,25}/,
          inputErrorMessage: '名称为3-25个字符,不能有空格'
        }).then(({ value }) => {
          axios.post('/ui/customforms', {
            name: value,
            from: this.selectedTempId
          }).then(res => {
            if (res.data.status === 1) {
              this.$router.push('/formDesigner/editform/' + res.data.data.ID)
            }
          })
        })
      }
      this.ok = false
    }
  }
}
</script>

<style scoped>
  .layout-row-main {
    min-height: calc(100vh - 218px) !important;
  }

  .search-bar-box {
    position: relative;
    width: calc(100vw - 50px);
    max-width: 1280px;
    padding: 0 10px 0 0;
    margin: 0 auto;
    transition: all ease 0.3s;
    background-color: white;
    background-clip: content-box;
  }

  .search-bar-box > h4 {
    position: absolute;
    top: 50%;
    margin-left: 10px;
    transform: translateY(-50%);
  }

  .search-bar-box > div {
    padding: 10px;
    width: 50%;
    float: right;
  }

  .temp-left {
    width: 150px;
    overflow-x: hidden;
  }

  .temp-main {
    width: calc(100% - 150px);
    padding: 10px;
    position: relative;
  }

  .temp-list-box {
    min-height: calc(100vh - 238px);
    width: 38.196601125010515179541316563436%;
    border: 1px solid #ECEDEF;
    box-shadow: 0 1px 1px rgba(99, 99, 99, .05);
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
    background-color: white;
  }

  .temp-content {
    width: calc(61.803398874989484820458683436564% - 12px);
    position: absolute;
    right: 10px;
    top: 10px;
    bottom: 10px;
    border-top: 1px solid #ECEDEF;
    border-bottom: 1px solid #ECEDEF;
    border-right: 1px solid #ECEDEF;
    box-shadow: 0 1px 1px rgba(99, 99, 99, .05);
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    background-color: #f8f8f8;
  }

  .temp-content-header {
    position: relative;
    width: 100%;
    height: 60px;
    padding: 10px;
    text-align: right;
    background-color: white;
    border-bottom: 1px solid #ECEDEF;
  }

  .temp-content-header-name {
    position: absolute;
    left: 10px;
    line-height: 40px;
  }

  .temp-content-body {
    width: 100%;
    height: calc(100% - 60px);
    overflow-x: hidden;
    overflow-y: scroll;
  }

  .temp-condition {
    width: 100%;
    height: 60px;
    padding: 10px;
    border-bottom: 1px solid #ECEDEF;
  }

  .condition-type {
    font-size: 16px;
    font-weight: 600;
    border-style: hidden !important;
  }

  .condition-type:after {
    content: '' !important;
    display: none !important;
  }

  .condition-item {
    padding: 4px 10px;
    margin: 3px;
    border: 1px solid #ECEDEF;
    border-radius: 4px;
    display: inline-block;
    background-color: white;
  }

  button.condition-item:after {
    content: 'X';
    margin-left: 6px;
    display: inline-block;
    transform: scale(.75, .75);
  }

  button.condition-item:hover {
    color: #53C08B;
    border-color: #53C08B;
  }

  .temp-list {
    width: 100%;
    padding: 0 20px;
  }

  .temp-list-item {
    position: relative;
    list-style: none;
    color: #73767F;
    border-bottom: 1px dashed #eaeaea;
  }

  .temp-list-item-content {
    display: block;
    height: 38px;
    line-height: 38px;
    width: 100%;
    color: inherit;
    overflow:hidden;
    white-space: nowrap;
    text-overflow:ellipsis;
    text-decoration: none;
  }

  .selected.temp-list-item,
  .temp-list-item:hover {
    color: #28B06E;
    border-bottom-color: #28B06E;
    font-weight: 600;
  }

  .temp-list-item::after,
  .temp-list-item::before {
    content: '';
    z-index: 1000;
    display: none;
    position: absolute;
    top: 0;
    height: 0;
    width: 0;
    border-width: 20px 10px 20px 10px;
    border-style: solid hidden solid solid;
  }

  .temp-list-item::after {
    right: -28.5px;
    border-color: rgba(0, 0, 0, 0) rgba(0, 0, 0, 0) rgba(0, 0, 0, 0) white;
  }

  .temp-list-item::before {
    right: -30px;
    border-color: rgba(0, 0, 0, 0) rgba(0, 0, 0, 0) rgba(0, 0, 0, 0) #ECEDEF;
  }

  .temp-list-item:hover::after, .temp-list-item:hover::before,
  .selected.temp-list-item::after, .selected.temp-list-item::before {
    display: block;
  }

  .el-menu-item {
    height: 30px !important;
  }
</style>
