<template>
  <el-dialog
    :title="`${id ? '编辑' : '新增'} - 教练员数据`"
    :visible.sync="dialogVisible"
    custom-class="new-edition-dialog"
    width="60%"
    @closed="closed"
    @open="open"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="top"
      label-width="auto"
    >
      <el-row :gutter="24" style="flex-wrap:wrap" type="flex">
        <el-col :span="8">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="form.name"
              clearable
              placeholder="请输入姓名"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="任教课目" prop="subjectName">
            <el-select
              v-model="form.subjectName"
              clearable
              multiple
              placeholder="请输入任教课目"
              style="width: 100%;"
            >
              <el-option
                v-for="(item, i) in dicts"
                :label="item.name"
                :value="item.name"
                :key="i"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="等级" prop="level">
            <el-input
              v-model="form.level"
              clearable
              placeholder="请输入等级"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button :loading="saveLoading" type="primary" @click="handleSave">
        确 认
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import * as api from '@/api/examDataMenu/examObjectData/couchDataMenu.js'
import * as apis from '@/api/examDataMenu/examObjectData/teachDataMenu'
export default {
  name: 'AddEditDialog',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    rowInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      rules: {
        name: [{required: true, message: '请输入姓名', trigger: 'blur'}]
      },
      form: {},
      saveLoading: false,
      dicts: []
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    id() {
      return this.rowInfo?.id || ''
    }
  },
  created() {},
  methods: {
    async loadData() {
      try {
        this.loading = true
        const {rows = []} = await apis.tableData()
        if (rows.length > 0) {
          this.dicts = rows.map(item => {
            return {name: item.subjectName, id: item.id}
          })
        }
      } finally {
        this.loading = false
      }
    },
    // 打开弹层
    open() {
      console.log(11111111111)
      this.loadData()
      if (this.id) {
        this.saveLoading = true
        this.getDetail(this.id)
      }
    },

    // 关闭弹层后
    closed() {
      const {rules} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {rules})

      this.$nextTick(_ => {
        this.$refs.form.$el.scrollTop = 0
        this.$refs.form.clearValidate()
      })
    },

    // 获取详情
    async getDetail(id) {
      try {
        const res = await api.tableDetail(id)
        res.subjectName = res.subjectName.split(',')
        this.form = res
      } finally {
        this.saveLoading = false
      }
    },

    // 保存
    handleSave() {
      this.$refs.form.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveLoading = true
          const myInterFace = this.id ? api.tableEdit : api.tableAdd
          const parmas = JSON.parse(JSON.stringify(this.form))
          parmas.couchTeachList = []
          this.dicts.forEach(item => {
            parmas.subjectName.forEach(val => {
              if (val == item.name) {
                parmas.couchTeachList.push({teachId: item.id})
              }
            })
          })
          parmas.subjectName = parmas.subjectName.join(',')
          console.log(parmas)

          try {
            let {state, message} = await myInterFace(parmas)

            if (state) {
              this.$emit('submit', this.id ? 'edit' : 'add')
              message = this.id ? '编辑' : '新增'
              this.$message.success(`教练员数据${message}成功`)
              this.dialogVisible = false
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    }
  }
}
</script>

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