<template>
  <el-dialog
    width="600px"
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
  >
    <span style="height: 360px">
      <el-form
        ref="form"
        :model="model"
        data-vv-scope="contactsForm"
        label-width="80px"
      >
        <el-form-item label="群组名称" required>
          <ht-input
            v-model="model.groupName"
            clearable
            validate="required"
            :maxlength="20"
            show-word-limit
            style="width: 90%"
          ></ht-input>
        </el-form-item>
        <el-form-item label="群组编号" required>
          <ht-input
            v-model="model.code"
            validate="required"
            clearable
            :disabled="!!model.id"
            :maxlength="20"
            show-word-limit
            style="width: 90%"
          ></ht-input>
        </el-form-item>
      </el-form>
    </span>
    <span slot="footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirm">保存</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { getPinyin } from '@/api/base.js'
  import deepmerge from 'deepmerge'
  export default {
    props: {
      dialogTitle: {
        type: String,
        default: '添加群组信息',
      },
    },
    data() {
      return {
        dialogVisible: false,
        model: {
          groupName: '',
          code: '',
        },
      }
    },
    watch: {
      'model.groupName'(newValue) {
        if (newValue && !this.model.id) {
          getPinyin(newValue).then((resp) => {
            this.model.code = resp.value
          })
        }
      },
    },
    methods: {
      confirm() {
        this.$root.$validator.validateAll('contactsForm').then((result) => {
          if (result) {
            this.$emit('confirm', this.model)
            this.dialogVisible = false
          }
        })
      },
      showDialog(row) {
        if (row) {
          const data = deepmerge({}, row, { clone: true })
          data && this.$set(this, 'model', data)
        } else {
          this.$set(this, 'model', {
            groupName: '',
            code: '',
          })
        }
        this.dialogVisible = true
      },
    },
  }
</script>

<style lang="scss" scoped></style>
