<template>
  <div>
    <el-form ref="form" inline :model="form">
      <template v-for="(item, key) in form">
        <select-user
          v-if="item.length > 0"
          :key="key"
          :name="key"
          :item="item"
          :branchsyId="branchsyId"
          :teachersByOrganId="teachersByOrganId"
        />
      </template>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="$listeners.close">取 消</el-button>
      <el-button @click="submit" type="primary">确 定</el-button>
    </span>
  </div>
</template>
<script>
import { array2object } from '@/helpers/utils'
import { employeeLevelDetail, employeeLevel } from '../api'
import selectUser from './select-user'
export default {
  props: ['detail'],
  components: {
    'select-user': selectUser
  },
  data() {
    return {
      list: [],
      form: {
        repair: [],
        director: [],
        education: [],
        teamTeacher: [],
      }
    }
  },
  computed: {
    branchsyId() {
      return array2object(this.selects.branchs, 'id')
    },
    teachersByOrganId() {
      const data = {}
      for (const item of this.selects.teachers) {
        if (!data[item.organId]) {
          data[item.organId] = []
        }
        data[item.organId].push(item)
      }
      return data
    }
  },
  mounted() {
    this.$store.dispatch('setBranchs')
    this.$store.dispatch('setTeachers')
    this.FetchDetail()
  },
  methods: {
    async submit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          let list = []
          for (const key in this.form) {
            if (Object.hasOwnProperty.call(this.form, key)) {
              const item = this.form[key];
              list = list.concat(item.map(row => ({...row, roleName: key})))
            }
          }
          await employeeLevel(list)
          this.$message.success('提交成功')
          this.$listeners.submited()
        }
      })
    },
    async FetchDetail() {
      try {
        const res = await employeeLevelDetail({
          userId: this.detail.id
        })
        this.list = res.data
        for (const key in res.data) {
          if (Object.hasOwnProperty.call(res.data, key)) {
            const type = res.data[key];
            for (const item of type) {
              this.form[key].push({
                organId: item,
                transferUserId: '',
                levelUserId: this.detail.id
              })
            }
          }
        }
        this.form = this.form
      } catch (error) {}
    }
  }
};
</script>
<style lang="less" scoped>
.dialog-footer{
  text-align: right;
  display: block;
  padding-bottom: 20px;
}
</style>
