<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="subjectName">
            <el-input
              v-model="form.subjectName"
              clearable
              placeholder="请输入任教课目"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="任课关联课目" prop="teachSubjectList">
            <el-select
              v-model="form.teachSubjectList"
              multiple
              placeholder="请选择任课关联课目"
              style="width: 100%;"
              @change="selectSubject"
              v-on:click.native="subjectDUsers"
            >
              <el-option
                v-for="(item, index) in subjectList"
                :key="index"
                :label="item.name"
                :value="item.subjectId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="任课关联资源" prop="subjectResourcesList">
            <el-select
              v-model="form.subjectResourcesList"
              multiple
              placeholder="请选择任课关联资源"
              style="width: 100%;"
              @change="selectPlan"
              v-on:click.native="planUsers"
            >
              <el-option
                v-for="(item, index) in planList"
                :key="index"
                :label="item.name"
                :value="item.subjectId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="示讲视角情况" prop="showView">
            <el-input
              v-model="form.showView"
              clearable
              placeholder="请输入示讲视角情况"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审核人" prop="approveName">
            <el-input
              v-model="form.approveName"
              clearable
              placeholder="请输入审核人"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审核状态" prop="approveStatus">
            <el-input
              v-model="form.approveStatus"
              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>
    <subjectDialog ref="subjectDialog" @getUser="getUser" />
    <planDialog ref="planDialog" @getUser="getUserPick" />
  </el-dialog>
</template>

<script>
import * as api from '@/api/examDataMenu/examObjectData/teachDataMenu'
import subjectDialog from './subjectDialog.vue'
import planDialog from './planDialog.vue'
// import questionListMenu from '@/api/examination/questionListMenu.js' // import questionListMenu from '@/api/examination/questionListMenu.js'
import * as publicApi from '@/api/examDataMenu/examKnowledgeData/teachingResourceData'

export default {
  name: 'AddEditDialog',
  components: {
    subjectDialog,
    planDialog
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    rowInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      rules: {
        subjectName: [
          {required: true, message: '请输入任教课目', trigger: 'blur'}
        ]
      },
      form: {},
      saveLoading: false,
      subjectList: [],
      planList: []
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    id() {
      return this.rowInfo?.id || ''
    }
  },
  created() {},
  methods: {
    selectSubject(val) {
      let arr = JSON.parse(JSON.stringify(this.subjectList))
      this.subjectList = []
      arr.forEach((p, pi) => {
        val.forEach(v => {
          if (p.id == v) {
            this.subjectList.push(p)
          }
        })
      })
    },
    selectPlan(val) {
      let arr = JSON.parse(JSON.stringify(this.planList))
      this.planList = []
      arr.forEach((p, pi) => {
        val.forEach(v => {
          if (p.id == v) {
            this.planList.push(p)
          }
        })
      })
    },
    subjectDUsers() {
      this.$refs.subjectDialog.add(this.subjectList)
    },
    planUsers() {
      this.$refs.planDialog.add(this.planList)
    },
    getUserPick(val) {
      this.form.subjectResourcesList = []
      this.planList = val.map(i => ({...i, subjectId: i.subjectId || i.id}))
      this.planList.forEach(e => {
        this.form.subjectResourcesList.push(e.subjectId)
      })
    },
    getUser(val) {
      this.form.teachSubjectList = []
      this.subjectList = val.map(i => ({...i, subjectId: i.subjectId || i.id}))
      this.subjectList.forEach(e => {
        this.form.teachSubjectList.push(e.subjectId)
      })
    },
    // 打开弹层
    open() {
      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) {
      console.log(11111, id)
      try {
        const form = await api.tableDetail(id)
        console.log(222, form)

        if (form.subjectResourcesList.length > 0) {
          form.subjectResourcesList = form.subjectResourcesList.map(
            item => item.resourceId
          )
          const {rows} = await publicApi.tableData()
          console.log(333, rows)

          form.subjectResourcesList.forEach(item => {
            rows.forEach(val => {
              if (item === val.id) {
                this.planList.push({...val, subjectId: val.id})
              }
            })
          })
        }

        if (form.teachSubjectList.length > 0) {
          form.teachSubjectList = form.teachSubjectList.map(item => {
            return item.subjectId
          })
          const {rows} = await api.findByMajorIds()
          console.log(444, rows)
          form.teachSubjectList.forEach(item => {
            rows.forEach(val => {
              if (item === val.id) {
                this.subjectList.push({...val, subjectId: val.id})
              }
            })
          })
        }

        this.form = {...form}
      } finally {
        this.saveLoading = false
      }
    },

    // 保存
    handleSave() {
      this.$refs.form.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          // return
          this.form.subjectResourcesList = this.form.subjectResourcesList.map(
            item => {
              return {
                resourceId: item
              }
            }
          )
          this.form.teachSubjectList = this.form.teachSubjectList.map(item => {
            return {
              subjectId: item
            }
          })
          this.saveLoading = true
          const myInterFace = this.id ? api.tableEdit : api.tableAdd

          try {
            let {state, message} = await myInterFace(this.form)

            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>
