<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="700px"
    @close="handleClose"
  >
    <div style="margin-bottom: 10px;">
      当前分组：{{ groupName }}
    </div>
    <el-form :model="form" ref="form" label-width="100px">
      <el-form-item
        label="选择票种"
        prop="ticketTypeIds"
        :rules="[{ required: true, message: '请至少选择一个票种', trigger: 'change' }]"
      >
        <el-select
          v-model="form.ticketTypeIds"
          multiple
          filterable
          placeholder="请选择票种"
          style="width: 100%"
        >
          <el-option
            v-for="item in ticketTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button @click="handleClose">
        取 消
      </el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="handleSubmit"
      >
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { batchAddTicketType } from '@/api/ticketTypeGroup'
import { getTicketTypeList } from '@/api/ticketType'

export default {
  data () {
    return {
      title: '分配票种',
      visible: false,
      loading: false,
      groupId: '',
      groupName: '',
      form: {
        ticketTypeIds: []
      },
      ticketTypeList: []
    }
  },
  methods: {
    show (row) {
      this.groupId = row.id
      this.groupName = row.name
      this.visible = true
      this.form.ticketTypeIds = (row.ticketTypes || []).map(t => t.id)
      this.getTicketTypeList()
    },
    getTicketTypeList () {
      getTicketTypeList({
        pageNum: 1,
        pageSize: 1000
      }).then(res => {
        this.ticketTypeList = res?.data?.records || []
      })
    },
    handleClose () {
      this.visible = false
      this.form.ticketTypeIds = []
    },
    handleSubmit () {
      if (this.form.ticketTypeIds.length === 0) {
        this.$message.warning('请至少选择一个票种')
        return
      }
      this.loading = true
      batchAddTicketType({
        groupId: this.groupId,
        ticketTypeIds: this.form.ticketTypeIds
      }).then(res => {
        this.$message.success('分配成功')
        this.$emit('update')
        this.handleClose()
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>
