<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="result.name"></el-input>
        </el-form-item>
        <el-form-item prop="rewardMode"
                      label="活动类型"
                      style="width: 500px">
          <el-radio-group v-model="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"
                        :disabled="domain.disabled"
                        v-model="domain.min"></el-input>
            </el-form-item>
            <el-form-item>
              <el-input type="number"
                        :disabled="domain.disabled"
                        v-model="domain.max"></el-input>
            </el-form-item>
            <el-form-item>
              <el-input style="width: auto;"
                        type="number"
                        :disabled="domain.disabled"
                        v-model="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="organIdList"
                      label="适用分部"
                      style="width: 500px">
          <el-select style="width: 100% !important;"
                     v-model="result.organIdList"
                     multiple
                     placeholder="请选择">
            <el-option v-for="item in branchList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"
                       :disabled="item.disabled"> </el-option>
          </el-select>
        </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 store from '@/store'
import { branchQueryPage, queryOrganIdList } from '@/api/specialSetting'
import { courseScheduleRewardsQuery, getUserRole, courseScheduleRewardsAdd, courseScheduleRewardsUpdate } from '@/api/systemManage'
export default {
  name: 'adminManager',
  data () {
    return {
      organId: null,
      pageType: this.$route.query.type,
      id: this.$route.query.id,
      branchList: [],
      useBranchId: [], // 使用的分部编号
      result: {
        name: null,
        rewardMode: null,
        organIdList: 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' }],
        organIdList: [{ type: 'array', required: true, message: '请选择适用分部', trigger: 'change' }]
      }
    }
  },
  mounted () {
    this.__init()
  },
  methods: {
    async __init () {
      this.$refs.form.resetFields()
      // 获取已经配置过的分部编号
      let result = await queryOrganIdList()
      let branchList = await branchQueryPage({ delFlag: 0, rows: 9999 })
      if (result.code == 200) {
        this.useBranchId = result.data
      }
      if (branchList.code == 200) {
        branchList.data.rows.forEach(item => {
          let tempArr = {}
          if (this.useBranchId.indexOf(item.id) != -1) {
            tempArr = {
              label: item.name,
              value: item.id,
              disabled: true
            }
          } else {
            tempArr = {
              label: item.name,
              value: item.id
            }
          }
          this.branchList.push(tempArr)
        })
      }

      if (this.pageType == 'update') {
        let courseScheduleRewards = await courseScheduleRewardsQuery({ id: this.id })
        if (courseScheduleRewards.code == 200) {
          let data = courseScheduleRewards.data
          let tempList = []
          if (data.organIdList) {
            data.organIdList.split(',').forEach(item => {
              tempList.push(parseInt(item))
            })
          }
          this.result = {
            id: data.id,
            name: data.name,
            rewardMode: data.rewardMode,
            organIdList: tempList,
            courseScheduleType: data.courseScheduleType,
            domains: data.rewardsRulesJson ?
              JSON.parse(data.rewardsRulesJson) : [{
                min: null,
                max: null,
                money: null,
                disabled: false,
                key: Date.now()
              }],
            errorText: null
          }

          // 修改可以取消选中
          this.branchList.forEach(item => {
            if (tempList.indexOf(item.value) != -1) {
              item.disabled = false
            }
          })
        }
      }


    },
    onSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        let result = this.result
        this.addDomain(result, true)
        if (valid && !result.errorText) {
          let params = {
            organIdList: result.organIdList.join(','),
            courseScheduleType: result.courseScheduleType,
            rewardMode: result.rewardMode,
            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('/vipClassSet/branchActive')
      } else {
        this.$message.error(res.msg)
      }
    },
    onCancel () {
      this.$router.push('/vipClassSet/branchActive')
    },
    resetForm () {
      this.result = {
        name: null,
        rewardMode: null,
        organIdList: [],
        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>