<template>
  <div>
    <el-form ref="form" :model="form" inline>
      <el-row>
        <el-col :span="6">
          <el-form-item
            label="分部"
            prop="organId"
            :rules="[{required: true, message: '请选择分部'}]"
          >
            <el-select
              clearable
              filterable
              v-model="form.organId"
              :disabled="!isCreate"
              placeholder="请选择分部"
            >
              <el-option v-for="(item,index) in selects.branchs"
                :key="index"
                :label="item.name"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="工作周期"
            prop="month"
            :rules="[{required: true, message: '请选择工作周期'}]"
          >
            <el-date-picker
              v-model="form.month"
              :disabled="!isCreate"
              type="month"
              placeholder="请选择工作周期">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="group" v-for="(groupItem, groupIndex) in form.group" :key="groupIndex">
        <el-col :span="6">
          <el-form-item
            label="乐团主管"
            :prop="`group.${groupIndex}.userId`"
            :rules="[{required: true, message: '请选择乐团主管'}]"
          >
            <el-select
              clearable
              filterable
              v-model="groupItem.userId"
              :disabled="!isCreate"
              placeholder="请选择乐团主管"
            >
              <el-option v-for="(item,index) in technicians"
                :key="index"
                :label="item.realName"
                :disabled="form.group.map(m => m.userId).includes(item.userId)"
                :value="item.userId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <template v-for="(matterItem, matterIndex) in groupItem.matter">
          <el-col :offset="matterIndex === 0 ? 0 : 6" :span="6" :key="groupIndex + '-' + matterIndex + '1'">
            <el-form-item
              :label="'任务事项' + (matterIndex + 1)"
              :prop="`group.${groupIndex}.matter.${matterIndex}.item`"
            >
              <el-select
                clearable
                filterable
                v-model="matterItem.item"
                :disabled="!isCreate && !!matterItem.item"
                placeholder="请选择任务事项"
              >
                <el-option v-for="(item,index) in matterTypesOptions"
                  :key="index"
                  :label="item.label"
                  :disabled="groupItem.matter.map(m => m.item).includes(item.value)"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :key="groupIndex + '-' + matterIndex + '2'">
            <el-form-item
              :label="'任务次数' + (matterIndex + 1)"
              :prop="`group.${groupIndex}.matter.${matterIndex}.times`"
            >
              <el-input clearable v-model="matterItem.times" placeholder="请输入次数" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :key="groupIndex + '-' + matterIndex + '3'">
            <div class="ctrl">
              <span>
                <el-tooltip content="添加任务" placement="top" :open-delay=".5">
                  <el-button
                    icon="el-icon-plus"
                    @click="createMatter(groupItem.matter)"
                    circle
                    
                  ></el-button>
                </el-tooltip>
                <el-tooltip content="删除任务" placement="top" :open-delay=".5">
                  <el-button
                    icon="el-icon-minus"
                    circle
                    
                    @click="removeMatter(groupItem.matter, matterIndex)"
                    :disabled="groupItem.matter.length <= 1"
                  ></el-button>
                </el-tooltip>
              </span>
              <el-tooltip  v-if="isCreate" content="删除乐团主管" placement="top" :open-delay=".5">
                <el-button
                  icon="el-icon-delete"
                  circle
                  type="danger"
                  
                  v-if="matterIndex === 0"
                  @click="removeGroup(form.group, groupIndex)"
                  :disabled="form.group.length <= 1"
                ></el-button>
              </el-tooltip>
            </div>
          </el-col>
        </template>
      </el-row>
      <el-button v-if="isCreate" @click="createGroup" plain block style="width: 100%">添加乐团主管</el-button>
    </el-form>
    <div slot="footer" style="text-align: right;margin-top: 20px;">
      <el-button @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="submit">确认</el-button>
    </div>
  </div>
</template>
<script>
import { matterTypes } from '@/views/main/constant'
import { objectToOptions } from '@/utils'
import { createRandom } from '@/helpers/uuidv4'
import { inspectionAdd, inspectionGetInfo, inspectionUpdate, getMusicGroupEduTeacher } from '@/views/main/api'
import { getOrganRole } from '@/api/buildTeam'
const emptyMatter = {
  item: '',
  times: ''
}
export default {
  props: ['id'],
  data() {
    return {
      form: {
        organId: '',
        group: [{
          _uuid: createRandom(),
          userId: '',
          matter: [{...emptyMatter}]
        }]
      },
      technicians: []
    }
  },
  computed: {
    matterTypesOptions() {
      return objectToOptions(matterTypes)
    },
    isCreate() {
      return !this.id
    },
  },
  watch: {
    async 'form.organId'() {
      if (this.form.organId) {
        try {
          const res = await getOrganRole({
            organId: this.form.organId,
            rows: 999
          })
          this.technicians = res.data?.EDUCATION || []
          if (this.isCreate) {
            this.$set(this.form, 'group', this.form.group.map(item => ({...item, userId: ''})))
          }
        } catch (error) {}
      }
    }
  },
  async mounted() {
    try {
      const res = await inspectionGetInfo({
        id: this.id
      })
      this.form = {
        ...this.form,
        organId: res.data.organId,
        month: res.data.month,
        group: [{
          _uuid: createRandom(),
          userId: res.data.userId,
          matter: res.data.inspectionItems.map(item => ({item: item.item, times: item.times}))
        }]
      }
    } catch (error) {}
  },
  methods: {
    createGroup() {
      this.form.group.push({
        userId: '',
        matter: [{...emptyMatter}]
      })
    },
    createMatter(matter) {
      matter.push({...emptyMatter})
    },
    removeMatter(matter, index) {
      matter.splice(index, 1)
    },
    async removeGroup(group, index) {
      try {
        await this.$confirm('是否确认删除此乐团主管?', '提示', {
          type: 'warning'
        })
        group.splice(index, 1)
      } catch (error) {}
    },
    async submit() {
      try {
        this.$refs.form.validate(async valid => {
          if (valid) {
            const data = this.form.group.map(item => ({
              organId: this.form.organId,
              month: this.form.month,
              userId: item.userId,
              inspectionItems: item.matter.map(m => ({
                ...m,
                organId: this.form.organId,
                month: this.form.month,
              }))
            }))
            if (this.isCreate) {
              await inspectionAdd(data)
              this.$message.success('创建成功')
            } else {
              await inspectionUpdate({
                ...data[0],
                id: this.id,
              })
              this.$message.success('修改成功')
            }
            this.$emit('close')
            this.$emit('submited')
          }
        })
      } catch (error) {}
    }
  }
}
</script>
<style lang="less" scoped>
.group{
  background-color: rgba(0, 0, 0, 0.05);
  padding: 10px;
  border-radius: 3px;
  margin-bottom: 10px;
}
.ctrl{
  margin-top: 45px;
  display: flex;
  justify-content: space-between;
  i{
    font-size: 24px;
  }
}
</style>
