<template>
  <div class="layout-no-cols" v-loading="dataLoading">
    <el-toolbar>
      <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary">
        <i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button type="button" class="el-button el-button--default save" @click="confirmMessageTemplateClick" :priv="this.messageTemplateId==='new'?'Message.Template.Add':'Message.Template.Edit'">
        <span>
          <i class="fa fa-save"></i>保存</span>
      </el-button>
    </el-toolbar>
    <div>
      <div class="detail-panel">
        <div class="panel-header">
          <div class="title">{{messageTemplateId=='new' ? '添加消息模板' : '编辑消息模板'}}</div>
        </div>
        <el-form :model="messageTemplate" ref="messageTemplateForm" :rules="rules" label-width="100px" class="self-form">
          <el-form-item prop="title" label="标题：">
            <el-input type="text" v-model="messageTemplate.title" auto-complete="off" style="width: 450px;"></el-input>
          </el-form-item>
          <el-form-item prop="type" label="消息类型：" :verify="['NotNull']">
            <el-select v-if="this.messageTemplateId === 'new'" clearable v-model="messageTemplate.type" placeholder="请选择消息类型" @change="changeMessages"
              @clear="typeClearHandler">
              <el-option v-for="type in types" :key="type.value" :label="type.text" :value="type.value"></el-option>
            </el-select>
            <el-select v-else disabled v-model="messageTemplate.type" placeholder="请选择消息类型">
              <el-option v-for="type in types" :key="type.value" :label="type.text" :value="type.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="businessType" label="业务类型：" :verify="['NotNull']">
            <el-select v-if="this.messageTemplateId === 'new'" clearable v-model="messageTemplate.businessType" placeholder="请选择业务类型"
              @change="changeBusiness">
              <el-option v-for="businessType in businessTypes" :key="businessType.id" :label="businessType.name" :value="businessType.id"></el-option>
            </el-select>
            <el-select v-else disabled v-model="messageTemplate.businessType" placeholder="请选择业务类型">
              <el-option v-for="businessType in businessTypes" :key="businessType.id" :label="businessType.name" :value="businessType.id"></el-option>
            </el-select>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <span v-show="isExistShow" style="color: red">该类型的模板已存在</span>
          </el-form-item>
          <el-form-item label="变量标签：">
            <a class="tagBtn" v-for="item in variableKeys" v-bind:key="item.name" v-bind:value="item.value" @click="getTemplateContent(item.name)">{{ item.value }}</a>
          </el-form-item>
          <el-form-item prop="content" label="模板内容：">
            <ueditor ref="editor" :content.sync="messageTemplate.content" :config="editorConfig" @contentChange="contentChange">
            </ueditor>
          </el-form-item>
          <el-form-item prop="sendTime" label="发送时间：">
            <el-date-picker type="datetime" placeholder="请选择发送时间" v-model="messageTemplate.sendTime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import util from '@src/common/util.js'
import ueditor from '@src/components/ueditor.vue'

export default {
  components: { ueditor },
  props: {
    messageTemplateId: {
      type: String,
      required: true
    }
  },
  data() {
    let titleLengthEXCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入标题'))
      } else {
        let lengthEx = util.getLengthEx(value, true)
        if (lengthEx > 50) {
          callback(new Error('标题必须小于等于16个汉字或者50个字母'))
        } else {
          callback()
        }
      }
    }
    return {
      // 该类型的模板是否已经存在的显示状态
      isExistShow: false,

      // 点击变量标签设置模板内容定义
      tmplateContents: [],

      // 点击变量标签设置模板内容定义
      newContents: [],

      // 变量标签设置定义
      variableKeys: [],

      // 消息类型下拉菜单选项获取定义
      types: [],
      rules: {
        title: [
          { validator: titleLengthEXCheck, trigger: 'blur change' }
        ]
      },
      // 业务类型下拉菜单选项获取定义
      businessTypes: [],

      // 编辑器配置
      editorConfig: {
        initialFrameHeight: 200,
        toolbars: [
          ['source', '|', 'undo', 'redo', '|',
            'inserttable', 'zpagebreak', 'insertorderedlist', 'insertunorderedlist', 'link', 'unlink', '|',
            'forecolor', 'fontfamily', 'fontsize', 'lineheight', '|',
            'bold', 'italic', 'underline', 'strikethrough', 'removeformat', '|',
            'indent', 'justifyleft', 'justifycenter', 'justifyright']
        ]
      },
      messageTemplate: {
        title: '',
        type: '',
        businessType: '',
        content: '',
        sendTime: ''
      },
      dataLoading: true
    }
  },
  mounted() {
    // 消息类型数据加载事件
    this.getMessageTypeData()
    // 业务类型数据加载事件
    this.getBusinessTypeData()
    this.beforeTurnToPage()
  },
  methods: {
    async beforeTurnToPage() {
      if (this.messageTemplateId !== 'new') {
        try {
          let res = await axios.get(`/ui/messagetemplate/${this.messageTemplateId}`)
          this.messageTemplate = res.data.data
          if (this.messageTemplate.sendTime) {
            this.messageTemplate.sendTime = Date.format(new Date(this.messageTemplate.sendTime), 'yyyy-MM-dd HH:mm:ss')
          }
          await this.getVariableKeyData(this.messageTemplate.businessType)
        } catch (e) {}
      }
      this.dataLoading = false
    },
    contentChange(val) {
      this.messageTemplate.content = val
    },
    // 消息模板消息类型触发事件
    changeMessages(typeValue) {
      if (typeValue) {
        this.getBusinessTypeData(typeValue)
      }
    },
    // 消息模板业务类型触发事件
    async changeBusiness(bTypeId) {
      // 判断某类型的模板是否已存在调用
      let data = await axios.get(`/ui/messagetemplate/isexist`, {
        params: { type: this.messageTemplate.type, businessType: bTypeId }
      })
      if (data.data.status === 1) {
        // 不存在
        this.isExistShow = false
      } else {
        // 已存在
        this.isExistShow = true
        /* return */
      }
      if (bTypeId) {
        this.getVariableKeyData(bTypeId)
      }
    },
    // 点击变量标签设置模板内容事件
    getTemplateContent(key) {
      this.$refs.editor.instance.execCommand('inserthtml', '${' + key + '}')
    },
    // 消息模板验证事件
    async confirmMessageTemplateClick() {
      try {
        if (!this.messageTemplate.content) {
          this.$alert('模板内容不能为空', '提示', {
            type: 'error'
          })
          return
        }
        await util.validateForm(this.$refs['messageTemplateForm'])
        if (this.messageTemplateId === 'new') {
          // 判断某类型的模板是否已存在调用
          let data = await axios.get(`/ui/messagetemplate/isexist`, {
            params: { type: this.messageTemplate.type, businessType: this.messageTemplate.businessType }
          })
          if (data.data.status === 1) {
            // 不存在
            this.isExistShow = false
            // 新建消息模板调用
            let res = await axios.post(`/ui/messagetemplate`, this.messageTemplate)
            if (res.data.status === 1 && this.messageTemplateId === 'new' && res.data.messageTemplateId) {
              util.showMessage(res)
              this.$router.replace({path: `/member/messageTemplate/${res.data.messageTemplateId}`})
            } else {
              util.showErrorMessageBox(res.data.message)
            }
          } else {
            // 已存在
            this.isExistShow = true
            this.addMessageTemplateDialog = true
            util.showErrorMessageBox('该类型的模板已存在')
          }
        } else {
          // 编辑消息模板调用
          let formdata = this.messageTemplate = {
            title: this.messageTemplate.title,
            type: this.messageTemplate.type,
            businessType: this.messageTemplate.businessType,
            content: this.messageTemplate.content,
            sendTime: this.messageTemplate.sendTime
          }
          let data = await axios.put(`/ui/messagetemplate/${this.messageTemplateId}`, formdata)
          if (data.data.status === 1) {
            util.showMessage(data)
            this.$emit('callback')
            // $router.back()
          } else {
            util.showErrorMessageBox(data.data.message)
          }
        }
      } catch (e) {
        util.showErrorMessageBox(e)
      }
    },
    // 消息类型数据加载事件
    async getMessageTypeData() {
      let data = await axios.get(`/ui/messagetemplate/getmessagetypes`)
      this.types = data.data.data
    },
    // 业务类型数据加载事件
    async getBusinessTypeData(type) {
      let data = await axios.get(`/ui/messagetemplate/getbusinesstypes`, {
        params: { type: type }
      })
      this.businessTypes = data.data.data
      if (type) {
        this.messageTemplate.businessType = this.businessTypes[0].id
        this.getVariableKeyData(this.businessTypes[0].id)
        // 判断某类型的模板是否已存在调用
        let data = await axios.get(`/ui/messagetemplate/isexist`, {
          params: { type: this.messageTemplate.type, businessType: this.messageTemplate.businessType }
        })
        if (data.data.status === 1) {
          // 不存在
          this.isExistShow = false
        } else {
          // 已存在
          this.isExistShow = true
        }
      }
    },
    // 变量标签数据加载事件
    async getVariableKeyData(businessType) {
      let data = await axios.get(`/ui/messagetemplate/getvariablekeys`, {
        params: { businessType: businessType }
      })
      this.variableKeys = data.data.data
    },
    typeClearHandler() {
      this.businessTypes = []
      this.messageTemplate.businessType = ''
      this.isExistShow = false
    }
  }
}
</script>

<style scoped>
  .page {
    float: right;
  }

  .tagBtn {
    height: 22px;
    line-height: 22px;
    padding: 6px 16px;
    border: 1px dashed #ccc;
    background-color: #f8f8f8;
    margin-right: 12px;
    border-radius: 4px;
    text-decoration: none;
    color: #666;
  }

  .self-form .el-select {
    width: auto !important;
  }
</style>
