<template>
  <div class='m-container'>
    <h2>
      <el-page-header @back="onCancel"
                      :content="(pageType == 'create' ? '添加' : '修改') + '分部活动'"></el-page-header>
    </h2>
    <div class="m-core">
      <el-form :model="result"
               :rules="rules"
               ref="form"
               label-width="120px">
        <el-form-item label="活动名称"
                      prop="name"
                      style="width: 500px">
          <el-input v-model.trim="result.name"></el-input>
        </el-form-item>
        <el-form-item prop="rewardMode"
                      label="活动类型"
                      style="width: 500px">
          <el-radio-group v-model.trim="result.rewardMode">
            <el-radio label="STAIR">阶梯奖励</el-radio>
            <el-radio label="PER">累计奖励</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="moreRule"
                      style="margin-bottom: 0;">
          <span class="min">最小值</span>
          <span class="min">最大值</span>
          <span class="max">奖励金额</span>
        </el-form-item>
        <div class="moreRule">
          <div class="moreRuleIn"
               v-for="(domain, index) in result.domains"
               :key="domain.key">
            <el-form-item :label="'梯度' + (index + 1)">
              <el-input type="number"
                        v-number
                        :disabled="domain.disabled"
                        @mousewheel.native.prevent
                        v-model.trim="domain.min"></el-input>
            </el-form-item>
            <el-form-item>
              <el-input type="number"
                        @mousewheel.native.prevent
                        v-number
                        :disabled="domain.disabled"
                        v-model.trim="domain.max"></el-input>
            </el-form-item>
            <el-form-item>
              <el-input style="width: auto;"
                        type="number"
                        @mousewheel.native.prevent
                        :disabled="domain.disabled"
                        v-model.trim="domain.money"></el-input>
              <el-button v-if="index != 0 && !domain.disabled"
                         @click.prevent="removeDomain(result, domain)">删除</el-button>
            </el-form-item>
          </div>
          <div class="el-form-item__error"
               v-if="result.errorText">{{ result.errorText }}</div>
        </div>
        <el-form-item class="add">
          <el-button icon="el-icon-plus"
                     @click="addDomain(result)">新增梯度</el-button>
        </el-form-item>

        <el-form-item prop="vipGroupCategoryIdList"
                      label="课程类型"
                      style="width: 500px">
          <el-select style="width: 100% !important;"
                     v-model.trim="result.vipGroupCategoryIdList"
                     filterable
                     clearable
                     multiple
                     placeholder="请选择">
            <el-option v-for="item in selects.vipGroupCategory"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id.toString()"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="organId"
                      label="所属分部"
                      style="width: 500px">
          <el-select style="width: 100% !important;"
                     filterable
                     clearable
                     @change="onSubjectChange('search')"
                     v-model.trim="result.organId"
                     placeholder="请选择">
            <el-option v-for="item in selects.branchs"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id.toString()"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="subjectIds"
                      label="所属声部"
                      style="width: 500px">
          <el-select style="width: 100% !important;"
                     filterable
                     clearable
                     multiple
                     @change="onSubjectChange('search')"
                     v-model.trim="result.subjectIds"
                     placeholder="请选择">
            <el-option v-for="(item, i) in selects.subjects"
                         :key="i"
                         :label="item.name"
                         :value="item.id.toString()"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="teacherId"
                      label="老师"
                      style="width: 500px">
          <el-select style="width: 80% !important;"
                     v-model.trim="result.teacherId"
                     filterable
                     clearable
                     multiple
                     placeholder="请选择">
            <el-option v-for="(item, index) in teacherList"
                       :key="index"
                       :label="item.label"
                       :value="item.value.toString()"> </el-option>
          </el-select>
          <el-button @click="onCheckAll">全选</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary"
                     @click="onSubmit('form')">立即{{ pageType == "create" ? '创建' : '修改' }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { getEmployeeOrgan, getSoundTree } from '@/api/buildTeam'
import { courseScheduleRewardsQuery, getUserRole, courseScheduleRewardsAdd, courseScheduleRewardsUpdate, findTeacherByOrganId } from '@/api/systemManage'
import { vipGroupCategory } from "@/api/vipSeting"
export default {
  name: 'branchActiveOperation',
  data () {
    return {
      organId: null,
      pageType: this.$route.query.type,
      id: this.$route.query.id,
      teacherList: [], // 老师列表
      result: {
        name: null,
        rewardMode: null,
        vipGroupCategoryIdList: null,
        organId: null,
        teacherId: null,
        subjectIds: null,
        courseScheduleType: 'VIP',
        domains: [{
          min: null,
          max: null,
          money: null,
          disabled: false,
          key: Date.now()
        }],
        errorText: null
      },
      rules: {
        name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        rewardMode: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
        vipGroupCategoryIdList: [{ type: 'array', required: true, message: '请选择课程类型', trigger: 'change' }],
        organId: [{ required: true, message: '请选择所属分部', trigger: 'change' }],
        subjectIds: [{ type: 'array', required: true, message: '请选择所属声部', trigger: 'change' }],
        teacherId: [{ type: 'array', required: true, message: '请选择老师', trigger: 'change' }]
      }
    }
  },
  mounted () {
    this.__init()
  },
  methods: {
    async __init () {
      this.$refs.form.resetFields()
      // 获取类型
      this.$store.dispatch('setVipGroupCategory')
      // 获取分部
      this.$store.dispatch('setBranchs')
      // 获取声部
      this.$store.dispatch('setSubjects')

      if (this.pageType == 'update') {
        let courseScheduleRewards = await courseScheduleRewardsQuery({ id: this.id })
        if (courseScheduleRewards.code == 200) {
          let data = courseScheduleRewards.data
          this.$nextTick(() => {
            this.result.organId = data.organId
            this.result.subjectIds = data.subjectIds ? data.subjectIds.split(',') : data.subjectIds
            this.onSubjectChange('update')
            this.result = {
              id: data.id,
              name: data.name,
              rewardMode: data.rewardMode,
              organId: data.organId,
              subjectIds: data.subjectIds ? data.subjectIds.split(',') : data.subjectIds,
              vipGroupCategoryIdList: data.vipGroupCategoryIdList ? data.vipGroupCategoryIdList.split(',') : data.vipGroupCategoryIdList,
              teacherId: data.teacherId ? data.teacherId.split(',') : data.teacherId,
              courseScheduleType: data.courseScheduleType,
              domains: data.rewardsRulesJson ?
                JSON.parse(data.rewardsRulesJson) : [{
                  min: null,
                  max: null,
                  money: null,
                  disabled: false,
                  key: Date.now()
                }],
              errorText: null
            }
          })
        }
      } else {
        this.resetForm()
      }
    },
    async onSubjectChange (type) {
      let organId = this.result.organId
      let subject = this.result.subjectIds
      // 判断是否有分部和声部
      if (subject.length <= 0 || !organId || organId == '') {
        this.teacherList = []
        this.result.teacherId = []
        return
      }
      let subjectIds = Object.assign([], subject).join(',')
      await findTeacherByOrganId({ organId: organId, subjectIds: subjectIds, jobNature: 'FULL_TIME' }).then(res => {
        if (res.code == 200) {
          if (type != 'update') {
            this.teacherList = []
            this.result.teacherId = []
          }
          res.data.forEach(item => {
            this.teacherList.push({
              label: item.realName,
              value: item.id
            })
          })
        }
      })
    },
    onCheckAll () { // 全选老师
      if (this.teacherList.length <= 0) {
        return
      }
      this.result.teacherId = []
      this.teacherList.forEach(item => {
        this.result.teacherId.push(item.value.toString())
      })
    },
    onSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        let result = JSON.parse(JSON.stringify(this.result))
        this.addDomain(result, true)
        if (valid && !result.errorText) {
          // 如果奖励金额为空时,默认为0
          result.domains.forEach(item => {
            if (!item.money) {
              item.money = 0
            }
          })
          let params = {
            organId: result.organId,
            vipGroupCategoryIdList: result.vipGroupCategoryIdList.join(','),
            teacherId: result.teacherId.join(','),
            courseScheduleType: result.courseScheduleType,
            rewardMode: result.rewardMode,
            subjectIds: result.subjectIds.join(','),
            rewardsRulesJson: JSON.stringify(result.domains),
            name: result.name
          }
          if (this.pageType == 'update') {
            params.id = result.id
            courseScheduleRewardsUpdate(params).then(res => {
              this.messageTips('修改', res)
            })
          } else if (this.pageType == 'create') {
            // return false
            courseScheduleRewardsAdd(params).then(res => {
              this.messageTips('添加', res)
            })
          }
        } else {
          return false;
        }
      })

    },
    messageTips (title, res) {
      if (res.code == 200) {
        this.$message.success('修改成功')
        this.$router.push({ path: '/vipClassSet/branchActive', query: { rules: this.pageInfo, searchForm: this.searchForm } })
      } else {
        this.$message.error(res.msg)
      }
    },
    onCancel () {
      this.$router.push({ path: '/vipClassSet/branchActive', query: { rules: this.pageInfo, searchForm: this.searchForm } })
    },
    resetForm () {
      this.teacherList = []
      this.result = {
        name: null,
        rewardMode: null,
        organId: null,
        subjectIds: [],
        teacherId: [],
        courseScheduleType: 'VIP',
        domains: [{
          min: null,
          max: null,
          money: null,
          disabled: false,
          key: Date.now()
        }],
        errorText: null
      }
      this.$refs.form.resetFields()
    },
    removeDomain (form, item) {
      var index = form.domains.indexOf(item)
      if (index !== -1) {
        form.domains.splice(index, 1)
        // 取消最后一个数据的禁用状态
        form.domains[form.domains.length - 1].disabled = false
        form.errorText = null
      }
    },
    addDomain (form, checked) {
      // debugger
      let domains = form.domains,
        singleLength = domains.length,
        lastDate = domains[singleLength - 1] // 获取倒数一个对象
      if (!lastDate.min) {
        form.errorText = '最小值不能为空'
        return
      }
      if (singleLength <= 1 && parseInt(lastDate.min) <= 0) {
        form.errorText = '最小值不能小于0'
        return
      } else if (singleLength > 1 && parseInt(lastDate.min) <= parseInt(domains[singleLength - 2].max)) {
        form.errorText = '最小值不能小于或等于上一个梯度的最大值'
        return
      }

      if (!parseInt(lastDate.max)) {
        form.errorText = '最大值不能为空'
        return
      } else if (parseInt(lastDate.max) <= parseInt(lastDate.min)) {
        form.errorText = '最大值应大于该梯度的最小值'
        return
      }

      form.errorText = null
      if (!checked) {
        lastDate.disabled = true
        domains.push({
          min: null,
          max: null,
          disabled: false,
          key: Date.now()
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.el-button--primary {
  background: #14928a;
  border-color: #14928a;
  color: #fff;
  &:hover,
  &:active,
  &:focus {
    background: #14928a;
    border-color: #14928a;
    color: #fff;
  }
}
.el-row {
  margin-top: 40px;
}
.el-col {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  justify-content: flex-end;
  margin-right: 50%;
}
.el-input-group {
  width: 200px;
  margin: 0 20px;
}
/deep/.el-tree-node__content {
  height: 40px !important;
}
.moreRule {
  background: #f0f0f0;
  position: relative;

  .el-form-item__error {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    position: absolute;
    left: 120px;
    top: 100%;
    margin-top: -21px;
  }
}
.add {
  margin-bottom: 22px;
  background: #f0f0f0;
  padding-bottom: 22px;
}
.moreRuleIn {
  .el-form-item {
    display: inline-block;
    &:first-child {
      /deep/.el-form-item__content {
        margin-left: 120px !important;
      }
    }
    /deep/.el-form-item__content {
      margin-left: 0 !important;
    }
  }
}
.min,
.max {
  display: inline-block;
  width: 180px;
  text-align: center;
  margin-right: 10px;
}
</style>