<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="方案名称" prop="planName">
        <el-input v-model="queryParams.planName" placeholder="请输入方案名称" />
      </el-form-item>
      <el-form-item label="是否生效" prop="isActive">
        <el-select v-model="queryParams.isActive" filterable placeholder="请选择" clearable>
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="float: right">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-form-item>
      <el-row style="padding-bottom: 10px">
         <span style="color: #999; font-size: 12px;">
                * 说明：佣金方案为app端提成统计提供数据依据，计算结果仅供参考，
                <br>* 系统自动计算方式：
                    1.按成交订单使用的佣金方案分组，
                    2.按照方案中的比例计算某一组的提成，
                    3.所有分组的提成之和 = 最后应得提成，
               <br>* 举例：
                    课程顾问Amy本月成交了10单，其中有3单使用了佣金方案A，
                    如果这3单的销售额之和为12000元，大于方案A的第一阶梯阈值8000元，小于方案A的第二阶梯阈值15000元，
                    那么这三单的提成=Amy这三单的销售额之和 ✖️ 方案A的第二阶梯比例8% = 12000✖️0.08 = 960元；
                    以此类推，将剩余7单再按照佣金方案分组，分别计算提成；
    最后将提成结果相加，就是Amy本月成交的10单总提成；
              </span>
      </el-row>
    </el-form>

    <el-table
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
      border
      :cell-style="{ 'text-align': 'center' }"
      :header-cell-style="{'text-align': 'center'}" >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="planName" label="方案名称" />
      <el-table-column prop="tier1Threshold" label="第一阶梯阈值" />
      <el-table-column prop="tier1Rate" label="第一阶梯比例" />
      <el-table-column prop="tier2Threshold" label="第二阶梯阈值" />
      <el-table-column prop="tier2Rate" label="第二阶梯比例" />
      <el-table-column prop="tier3Threshold" label="第三阶梯阈值" />
      <el-table-column prop="tier3Rate" label="第三阶梯比例" />
      <el-table-column prop="tier4Rate" label="第四阶梯比例" />
<!--      <el-table-column prop="renewalRate" label="续费率" />-->
<!--      <el-table-column prop="referralRate" label="转介绍率" />-->
      <el-table-column prop="isActive" :formatter="activeFormat" label="是否生效" />
      <el-table-column prop="effectiveDate" label="生效日期" />
      <el-table-column width="150" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit-outline" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title"  :visible.sync="open" width="770px">
      <el-form ref="form" v-loading="loadingChange" :rules="rules" :model="form" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="方案名称:" prop="planName">
              <el-input v-model="form.planName" placeholder="请输入方案名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="第一阶梯阈值:" prop="tier1Threshold">
              <el-input v-model="form.tier1Threshold" placeholder="第一阶梯阈值(0-?元)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="第一阶梯比例:" prop="tier1Rate">
              <el-input v-model="form.tier1Rate" placeholder="第一阶梯比例(0.06)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="第二阶梯阈值:" prop="tier2Threshold">
              <el-input v-model="form.tier2Threshold" placeholder="第二阶梯阈值(?-?元)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="第二阶梯比例:" prop="tier2Rate">
              <el-input v-model="form.tier2Rate" placeholder="第二阶梯比例(0.08)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="第三阶梯阈值:" prop="tier3Threshold">
              <el-input v-model="form.tier3Threshold" placeholder="第三阶梯阈值(?-?元)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="第三阶梯比例:" prop="tier3Rate">
              <el-input v-model="form.tier3Rate" placeholder="第三阶梯比例(0.10)" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="第四阶梯比例:" prop="tier4Rate">
              <el-input v-model="form.tier4Rate" placeholder="第四阶梯比例(0.12)" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="续费率:" prop="renewalRate">-->
<!--              <el-input v-model="form.renewalRate" placeholder="续费率(5%)" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="转介绍率:" prop="referralRate">-->
<!--              <el-input v-model="form.referralRate" placeholder="转介绍率(8-10%)" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="12"  >
            <el-form-item label="是否生效:" prop="isActive">
              <el-select v-model="form.isActive" filterable placeholder="请选择" :disabled="form.id!=undefined && form.isActive!='0'">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="生效日期:" prop="effectiveDate">
              <el-date-picker
                v-model="form.effectiveDate"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期"
                :disabled="form.id!=undefined && form.isActive!='0'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="loadingChange" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, saveOrEdit, remove } from '@/api/school/salary/commissionPlans'
export default {
  name: 'commission_plans',

  data() {
    return {
      // 遮罩层
      loading: true,
      loadingChange: false,
      // 总条数
      total: 0,
      // 表格树数据
      dataList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planName:'',
        isActive:'',
      },
      // 表单参数
      form: {
        planName:'',
        tier1Threshold:null,
        tier1Rate:null,
        tier2Threshold:null,
        tier2Rate:null,
        tier3Threshold:null,
        tier3Rate:null,
        tier4Rate:null,
        renewalRate:null,
        referralRate:null,
        isActive:1,
        effectiveDate:'',
      },
      options:[
        {label:'生效',value:1},
        {label:'未生效',value:0},
      ],
      rules: {
        planName: [
          { required: true, message: '方案名称不能为空', trigger: 'blur' }
        ],
        tier1Threshold: [
          { required: true, message: '阈值不能为空', trigger: 'blur' },
          {validator:this.positiveIntegerLessThanSix,trigger: 'blur'}
        ],
        tier1Rate:[
          { required: true, message: '比例不能为空', trigger: 'blur' },
          { validator:this.positiveDecimalWith2Digits, trigger: 'blur' }
        ],
        tier2Threshold:  [
          { required: true, message: '阈值不能为空', trigger: 'blur' },
          {validator:this.positiveIntegerLessThanSix,trigger: 'blur'}
        ],
        tier2Rate:[
          { required: true, message: '比例不能为空', trigger: 'blur' },
          { validator:this.positiveDecimalWith2Digits, trigger: 'blur' }
        ],
        tier3Threshold:  [
          { required: true, message: '阈值不能为空', trigger: 'blur' },
          {validator:this.positiveIntegerLessThanSix,trigger: 'blur'}
        ],
        tier3Rate:[
          { required: true, message: '比例不能为空', trigger: 'blur' },
          { validator:this.positiveDecimalWith2Digits, trigger: 'blur' }
        ],
        tier4Rate:[
          { required: true, message: '比例不能为空', trigger: 'blur' },
          { validator:this.positiveDecimalWith2Digits, trigger: 'blur' }
        ],
      },

    }
  },
  created() {
    this.getList()
  },
  methods: {

    getList() {
      this.loading = true
      list(this.queryParams).then(response => {
        this.dataList = response.data.rows
        this.total = response.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    activeFormat(row,column,cellValue){
      for (const item of this.options) {
        if (item.value===cellValue){
          return item.label
        }
      }
      return cellValue
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        planName:'',
        tier1Threshold:null,
        tier1Rate:null,
        tier2Threshold:null,
        tier2Rate:null,
        tier3Threshold:null,
        tier3Rate:null,
        tier4Rate:null,
        renewalRate:null,
        referralRate:null,
        isActive:1,
        effectiveDate:new Date(),
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.open = true
      this.title = '添加佣金方案'
    },
    // 多选框选中数据
    handleSelectionChange(selection) {

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.form = row
      this.open=true
    },
    /** 提交按钮 */
    submitForm: function() {
      this.loadingChange = true
      this.$refs['form'].validate(valid => {
        if (!valid) {
          this.loadingChange =false
          return
        }
        saveOrEdit(this.form).then(response => {
          this.loadingChange = false
          this.msgSuccess(response.msg)
          this.open = false
          this.getList()
        }).catch((response) => {
          this.msgError(response.msg)
          this.loadingChange = false
        })
      })

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return remove(row)
      }).then((response) => {
        if (response.code === 200) {
          this.getList()
          this.msgSuccess('删除成功')
        } else {
          this.msgError(response.msg)
        }
      }).catch(function() {})
    },
    positiveIntegerLessThanSix(rule, value, callback) {
      if (value === '' || value === null || value === undefined) {
        callback(); // 空值由 required 处理
        return;
      }
      const str = String(value);
      if (!/^[1-9]\d{0,4}$/.test(str)) {
        callback(new Error('必须为非零正整数且小于6位'));
      } else {
        callback();
      }
    },
    positiveDecimalWith2Digits(rule, value, callback) {
      const str = String(value);
      if (!/^\d+(\.\d{1,2})?$/.test(str)) {
        callback(new Error('必须为小于1的正数且最多两位小数'));
      } else {
        const num = parseFloat(value);
        if (num <= 0) {
          callback(new Error('数值必须大于0'));
        } else if (num >= 1) {
          callback(new Error('数值必须小于1'));
        } else {
          callback();
        }
      }
    }
  }
}
</script>
