<template>
  <el-dialog
    :visible.sync="visible"
    v-bind="modalOptions"
    append-to-body
  >
    <el-form
      ref="formData"
      :model="formData"
      :rules="formRules"
      size="mini"
      label-suffix=":"
      label-width="150px"
    >
      <el-form-item label="客户ID" prop="buyerUserId">
        <el-input
          v-model="formData.buyerUserId" maxlength="20" placeholder="客户ID" disabled
        />
      </el-form-item>
      <el-form-item label="标签" prop="labelIds">
        <el-select v-model="formData.labelIds" multiple size="mini" placeholder="请选择标签">
          <el-option v-for="item in tagList" :key="item.labelId" :label="item.labelName" :value="item.labelId" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="mini" @click="handleClose">取 消</el-button>
        <el-button type="primary" size="mini" @click="handleSubmit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { buyerSaveLabel, getLabelData } from '@/api/customer'

export default {
  name: 'TagAdd',
  components: {
  },
  data() {
    return {
      modalOptions: {
        closeOnClickModal: false,
        width: '620px',
        title: ''
      },
      visible: false,
      formData: {
        buyerUserId: '',
        labelIds: []
      },
      formRules: {
        buyerUserId: [
          { required: true, message: '缺少客户信息' }
        ],
        labelIds: [
          { type: 'array', required: true, message: '请选择标签' }
        ]
      },
      tagList: []
    }
  },
  methods: {
    handleClose() {
      this.visible = false
    },
    async getTagList() {
      const res = await getLabelData()
      this.tagList = res.data
    },
    initList() {
      this.getTagList()
    },
    handleOpen(params = {}) {
      this.modalOptions.title = '添加标签'
      this.formData.buyerUserId = params.buyerUserId
      // this.formData = Object.assign(this.$options.data().formData, params)
      this.visible = true
      this.initList()
      this.$refs.formData && this.$refs.formData.resetFields()
    },
    handleSubmit() {
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          const loading = this.$loading({ text: '加载中' })
          try {
            const { ...otps } = this.formData
            const params = {
              ...otps
            }
            await buyerSaveLabel(params)
            loading.close()
            this.$message({ message: `添加成功!`, type: 'success' })
            this.$emit('success')
            this.visible = false
          } catch (e) {
            loading.close()
          } finally {
            loading.close()
          }
        } else {
          this.$message({ message: '请输入相关信息', type: 'warning' })
          return false
        }
      })
    }
  }
}
</script>

