<template>
  <div class="fullheight">
    <ht-table
      @load="loadData"
      :data="data"
      :page-result="pageBean"
      :selection="true"
      :quick-search-props="[{prop:'A.name_',label:'名称'},{prop:'A.code_',label:'编码'}]"
      ref="htTable"
      :show-export="false"
      :show-custom-column="false"
      @row-click="rowClick"
    >
      <template v-slot:toolbar>
       
          <el-button
            size="small"
            @click="handleOpen('添加消息配置')"
            icon="el-icon-plus"
            type='primary'
          >添加</el-button>
          <ht-delete-button
            :url="formDeleteUrl()"
            :htTable="$refs.htTable"
            style="margin-left:10px"
          >删除</ht-delete-button>
        
      </template>
      <template>
        <ht-table-column
          type="index"
          width="50"
          align="center"
          label="序号"
        />
        <ht-table-column
          prop="name"
          label="名称"
          width="160"
          :show-overflow-tooltip="true"
          :sortable="true"
        >
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click="handleOpen('编辑消息配置', scope.row)"
            >{{ scope.row.name }}</el-link>
          </template>
        </ht-table-column>
        <ht-table-column
          prop="code"
          label="编码"
          width="160"
          :show-overflow-tooltip="true"
          :sortable="true"
        />
        <ht-table-column
          prop="templateName"
          :show-overflow-tooltip="true"
          label="消息模板"
          :sortable="true"
        />
        <ht-table-column
          prop="notifyType"
          :show-overflow-tooltip="true"
          label="消息提示"
          :sortable="true"
        />
        <ht-table-column
          prop="userConfigType"
          label="接收人配置"
          width="120"
          :filters="[
                        {text: '动态', value: 1},
                        {text: '固定', value: 2},
                    ]"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.userConfigType == '1'">
              <el-tag type="success">动态</el-tag>
            </span>
            <span v-else>
              <el-tag type="warning">固定</el-tag>
            </span>
          </template>
        </ht-table-column>
      </template>
    </ht-table>

    <el-dialog
      width="900px"
      top="5vh"
      :title="title"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form
        :model="formData"
        data-vv-scope="msgTemplateForm"
      >
        <el-row>
          <el-col :span="12">
            <ht-form-item
              label="配置名称"
              label-width="120px"
            >
              <ht-input
                style="width: 100%"
                v-model="formData.name"
                :validate="{required: true}"
                :maxlength="50"
                :showWordLimit="true"
              />
            </ht-form-item>
          </el-col>
          <el-col :span="12">
            <ht-form-item
              label="配置编码"
              label-width="120px"
            >
              <ht-input
                v-pinyin="formData.name"
                style="width: 100%"
                v-model="formData.code"
                :validate="{required: true}"
                :disabled="formData.id ? true : false"
              />
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <ht-form-item
              label="消息模板"
              label-width="120px"
            >
              <ht-input
                :validate="{required: true}"
                placeholder="请选择消息模板"
                style="width: 100%"
                readonly
                v-model="formData.templateName"
                class="input-with-select"
              >
                <el-button
                  type="primary"
                  @click="openTemplate"
                  slot="append"
                  icon="el-icon-search"
                ></el-button>
              </ht-input>
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <ht-form-item
              label="消息提醒"
              label-width="120px"
            >
              <ht-checkbox
                v-model="formData.notifyType"
                :options="msgType"
                :validate="{required: true}"
              />
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <ht-form-item
              label="接收人配置"
              label-width="120px"
            >
              <el-radio-group
                v-model="formData.userConfigType"
                @change="changeReceiverType"
              >
                <el-radio :label="1">动态</el-radio>
                <el-radio :label="2">固定</el-radio>
              </el-radio-group>
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <ht-form-item
              label="接收人"
              label-width="120px"
            >
              <ht-input
                v-show="formData.userConfigType == 1"
                v-model="formData.userStr"
                readonly
                :validate="{required: true}"
              />
              <div v-show="formData.userConfigType == 2">
                <el-button @click="openSelecter">管理接收人</el-button>
                <el-table
                  :data="receiverData"
                  style="width: 400px; margin-top: 10px"
                  border
                  max-height="220"
                >
                  <el-table-column
                    align="center"
                    prop="name"
                    label="接收人名称"
                  >
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="code"
                    label="接收账号/编码"
                  >
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="type"
                    label="接收类型"
                  >
                    <template slot-scope="scope">
                      <span>{{
                                                scope.row.type == 'user'
                                                    ? '用户'
                                                    : '组织'
                                            }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </ht-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <ht-submit-button
          :url="saveUrl()"
          :model="formData"
          :is-submit="isSubmit"
          scope-name="msgTemplateForm"
          @before-save-data="beforeSaveData()"
          @after-save-data="afterSaveData"
        >保存</ht-submit-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
      <select-type-dialog
        ref="selecter"
        @select="handleSelect"
        :selectType="selectType"
      />
      <msg-template-dialog
        ref="template"
        @select="handleSelectTemplate"
      ></msg-template-dialog>
    </el-dialog>
  </div>
</template>

<script>
import msg from '@/api/msg.js'
import SelectTypeDialog from '@/components/dialog/SelectTypeDialog'
import MsgTemplateDialog from '@/components/dialog/MsgTemplateDialog'
export default {
    components: {SelectTypeDialog, MsgTemplateDialog},
    data() {
        return {
            selectType: ['org', 'user'],
            msgType: [
                {
                    key: 'voice',
                    value: '语音',
                },
                {
                    key: 'mail',
                    value: '邮件',
                },
                {
                    key: 'sms',
                    value: '短信',
                },
                {
                    key: 'inner',
                    value: '站内',
                },
            ],
            title: '',
            pageBean: {
                page: 1,
                pageSize: 20,
                total: 0,
            },
            dialogVisible: false,
            data: [],
            formData: {
                name: '',
                code: '',
                tplKey: '',
                tplName: '',
                notifyType: '',
                userConfigType: 1,
                userStr: '${receiver}',
            },
            receiverData: [],
            isSubmit: false,
        }
    },
    methods: {
        handleSelectTemplate(row) {
            this.formData.tplKey = row.key;
            this.formData.templateName = row.name;
            this.$forceUpdate();
        },
        openTemplate() {
            this.$refs.template.open()
        },
        handleSelect(data) {
            if (data.length) {
                let param = JSON.stringify(data)
                this.formData.userStr = param
                this.receiverData = this.parseTypeData(data)
                this.$refs.selecter.closeDialog()
            } else {
                this.$message.error('请选择接收人！')
            }
            return
        },
        parseTypeData(data) {
            let temp = []
            data.forEach((item) => {
                if (item.codes) {
                    let codes = item.codes.split(',')
                    let names = item.name.split(',')
                    codes.forEach((code, i) => {
                        let obj = {}
                        obj.code = codes[i]
                        obj.name = names[i]
                        obj.type = item.type
                        temp.push(obj)
                    })
                }
            })
            return temp
        },
        openSelecter() {
            let obj = {}
            if (this.formData.userStr.indexOf('$') == -1) {
                obj = {json: this.formData.userStr}
            }
            this.$refs.selecter.showDialog(obj)
        },
        changeReceiverType(value) {
            if (value == 1) {
                this.formData.userStr = '${receiver}'
            } else {
                this.formData.userStr = ''
            }
        },
        //------------------------------------
        rowClick(row, column, event) {
            this.$refs.htTable.$refs.htTable.toggleRowSelection(row)
        },

        handleOpen(param, row) {
            this.title = param
            if (row) {
                this.formData = row
                if (this.formData.userStr.indexOf('$') == -1) {
                    let data = JSON.parse(this.formData.userStr);
                    this.receiverData = this.parseTypeData(data)
                }else{
                    this.receiverData = []
                }
            }
            this.dialogVisible = true
        },
        loadData(param, cb) {
            if(param && param.querys && param.querys.length){
                param.querys.forEach(item=>{
                    if(item.property == 'userConfigType'){
                        item.property = 'a.user_config_type_'
                    }
                })
            }
            if (!param) {
                this.pageBean.total = 0
                param = {pageBean: ''}
                param.pageBean = this.pageBean
                param.sorter = this.defaultSort
            }
            msg.getMessageConfig(param)
                .then((resp) => {
                    this.data = resp.rows
                    this.pageBean = {
                        page: resp.page,
                        pageSize: resp.pageSize,
                        total: resp.total,
                    }
                })
                .finally(() => cb())
        },
        handleClose() {
            this.dialogVisible = false
            // this.loadData()
            this.formData = {
                name: '',
                code: '',
                tplKey: '',
                tplName: '',
                notifyType: '',
                userConfigType: 1,
                userStr: '${receiver}',
            }
        },
        saveUrl() {
            return (
                window.context.application +
                '/msg/messageConfig/v1/save'
            )
        },
        beforeSaveData() {
            if (!this.formData || !this.formData.isDefault) {
                this.formData.isDefault = 0
            }
            this.isSubmit = true
        },
        afterSaveData() {
            this.loadData()
            this.dialogVisible = false
            this.formData = {
                name: '',
                code: '',
                tplKey: '',
                tplName: '',
                notifyType: '',
                userConfigType: 1,
                userStr: '${receiver}',
            }
        },
        formDeleteUrl() {
            return `${window.context.application}/msg/messageConfig/v1/removes`
        },
    },
}
</script>

<style scoped>
.el-link {
  margin: 0 5px;
}
>>> .el-dialog__body {
  padding: 10px 20px 0 20px;
}
</style>
