<template>
  <wrapper
    fill
    margin
    padding
    background
  >
    <schema-table
      ref="table"
      :schema="schema"
    />
    <confirm-dialog
      ref="editDialog"
      :title="dialogTitle"
      @confirm="onSave"
    >
      <div class="c-grid-form u-align-self--center">
        <span class="c-grid-form__label u-required">名称</span>
        <el-input
          v-model.trim="template.templateName"
          placeholder="最多30个字符"
          maxlength="30"
          clearable
        />
        <span class="c-grid-form__label u-required">内容</span>
        <el-input
          ref="textarea"
          v-model.trim="template.templateContent"
          type="textarea"
          :rows="3"
        />
        <div class="c-grid-form__row">
          <button
            class="o-button"
            @click="addPlaceholder"
          >
            <i class="o-button__icon el-icon-circle-plus-outline" />
            新增占位符
          </button>
        </div>
        <div
          v-for="(value, key) in template.keywordMap"
          :key="key"
          class="c-grid-form__row"
        >
          <span class="c-grid-form__label u-required c-grid-form__text">{{ "{" + key + "}" }}名称</span>
          <el-input
            v-model.trim="value.keywordName"
            placeholder="最多30个字符"
            maxlength="30"
            clearable
          >
            <template #append>
              <i
                class="c-sibling-item o-icon el-icon-plus has-active"
                @click="onAddPlaceholder(key)"
              />
              <i
                class="c-sibling-item o-icon el-icon-delete has-active"
                @click="onDelPlaceholder(key)"
              />
            </template>
          </el-input>
        </div>
      </div>
    </confirm-dialog>
  </wrapper>
</template>

<script>
import {
  getBroadcastTemplates,
  addBroadcastTemplate,
  updateBroadcastTemplate,
  delBroadcastTemplate,
  getBroadcastTemplate
} from '../api'

export default {
  name: 'BroadcastTemplate',
  data () {
    return {
      schema: {
        list: getBroadcastTemplates,
        buttons: [{ type: 'add', on: this.onAdd }],
        filters: [
          { key: 'templateName', type: 'search', placeholder: '模板名称' }
        ],
        cols: [
          { prop: 'templateName', label: '模板名称' },
          { prop: 'createTime', label: '创建时间' },
          { type: 'invoke', render: [
            { label: '编辑', on: this.onEdit },
            { label: '删除', on: this.onDel }
          ] }
        ]
      },
      template: {}
    }
  },
  computed: {
    dialogTitle () {
      return this.template.templateId ? '编辑模板' : '新增模板'
    }
  },
  methods: {
    getCursorIndex () {
      return this.$refs.textarea.$el.children[0].selectionStart || this.template.templateContent.length
    },
    addTemplateContent (content) {
      const arr = this.template.templateContent.split('')
      arr.splice(this.getCursorIndex(), 0, content)
      this.template.templateContent = arr.join('')
    },
    onAddPlaceholder (key) {
      this.addTemplateContent(`{${key}}`)
    },
    onDelPlaceholder (delKey) {
      this.template.optionalNumbers -= 1
      const max = this.template.optionalNumbers
      this.template.templateContent = this.template.templateContent.replace(
        new RegExp(`\\{${delKey}\\}`, 'g'),
        ''
      )
      for (let i = delKey + 1; i <= max; i++) {
        this.template.templateContent = this.template.templateContent.replace(
          new RegExp(`\\{${i}\\}`, 'g'),
          `{${i - 1}}`
        )
      }
      this.template.keywordMap.splice(delKey, 1)
    },
    addPlaceholder () {
      this.template.keywordMap.push({
        type: 0,
        keywordName: ''
      })
      this.addTemplateContent(`{${this.template.optionalNumbers}}`)
      this.template.optionalNumbers += 1
    },
    onAdd () {
      this.template = {
        type: 0,
        templateName: '',
        templateContent: '',
        optionalNumbers: 0,
        keywordMap: []
      }
      this.$refs.editDialog.show()
    },
    onEdit ({ templateId }) {
      getBroadcastTemplate(templateId).then(({ data }) => {
        const { templateId, type, templateName, templateContent, keywordMap, optionalNumbers } = data
        const arr = []
        for (let i = 0; i < optionalNumbers; i++) {
          arr.push(keywordMap[i])
        }
        this.template = {
          templateId, templateName, templateContent, type, optionalNumbers,
          keywordMap: arr
        }
        this.$refs.editDialog.show()
      })
    },
    onSave (done) {
      const { templateId, templateName, templateContent, keywordMap, type, optionalNumbers } = this.template
      if (!templateName) {
        this.$message({
          type: 'warning',
          message: '请填写模板名称'
        })
        return
      }
      if (!templateContent) {
        this.$message({
          type: 'warning',
          message: '请填写模板内容'
        })
        return
      }
      const map = {}
      for (let i = 0; i < optionalNumbers; i++) {
        const keyword = keywordMap[i]
        if (!keyword.keywordName) {
          this.$message({
            type: 'warning',
            message: `请填写占位符{${i}}名称`
          })
          return
        }
        if (!new RegExp(`\\{${i}\\}`).test(templateContent)) {
          this.$message({
            type: 'warning',
            message: `模板内容缺少占位符{${i}}`
          })
          return
        }
        map[i] = keyword
      }
      if (templateId) {
        updateBroadcastTemplate({
          templateId,
          type,
          templateName,
          templateContent,
          optionalNumbers,
          keywordMap: map
        }).then(() => {
          done()
          this.$refs.table.pageTo()
        })
      } else {
        addBroadcastTemplate({
          type,
          templateName,
          templateContent,
          optionalNumbers,
          keywordMap: map
        }).then(() => {
          done()
          this.$refs.table.resetCondition({ templateName })
        })
      }
    },
    onDel ({ templateId, templateName }) {
      this.$confirm(
        `删除模板${templateName}?`,
        { type: 'warning' }
      ).then(() => {
        delBroadcastTemplate(templateId).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.$refs.table.decrease(1)
        })
      })
    }
  }
}
</script>
