<template>
  <section class="applyForIntegral">
    <ai-list>
      <template slot="content">
        <ai-search-bar bottomBorder>
          <template slot="left">
            <ai-select
                v-model="search.status"
                @change="page.current = 1, getList()"
                placeholder="请选择状态"
                :selectList="dict.getDict('integralRuleStatus')">
            </ai-select>
          </template>
          <template slot="right">
            <el-input size="small" placeholder="事件名称" v-model="search.eventName" clearable
                      @change="page.current=1, getList()" suffix-icon="iconfont iconSearch"/>
          </template>
        </ai-search-bar>

        <ai-search-bar style="margin-top: 16px;">
          <template #left>
            <el-button type="primary" icon="iconfont iconAdd" @click="dialog=true">添加</el-button>
          </template>
        </ai-search-bar>

        <ai-table
            :tableData="tableData"
            :col-configs="colConfigs"
            :total="page.total" :dict="dict"
            :current.sync="page.current"
            :size.sync="page.size"
            @getList="getList">
          <el-table-column slot="integral" label="分值" align="center">
            <template slot-scope="{ row }">
            <span
                v-if="row.integralValueType == 1">
              {{ row.integralStart > 0 ? '+' + row.integralStart : row.integralStart }} ~ {{ row.integralEnd > 0 ? '+' + row.integralEnd : row.integralEnd }}
            </span>
              <span v-else>{{ row.integral > 0 ? '+' : '' }}{{ row.integral }}</span>
            </template>
          </el-table-column>
          <el-table-column slot="options" label="操作" align="center" fixed="right" width="200">
            <template slot-scope="{ row }">
              <div class="table-options">
                <el-button type="text" @click="changeStatus(row.id, 0)" v-if="row.status == 1">
                  停用
                </el-button>
                <el-button type="text" @click="changeStatus(row.id, 1)" v-else>启用</el-button>
                <el-button type="text" @click="toEdit(row)">编辑</el-button>
                <el-button type="text" @click="remove(row.id)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </ai-table>

      </template>
    </ai-list>

    <!-- <ai-empty v-else>暂无应用权限</ai-empty> -->

    <ai-dialog :title="dialogTitle" :visible.sync="dialog" @onConfirm="onConfirm" @closed="close" width="800px">
      <div class="form_div">
        <el-form ref="DialogForm" :model="form" :rules="formRules" size="small" label-suffix="：" label-width="100px">

          <el-form-item label="事件名称" prop="eventName">
            <el-input v-model="form.eventName" clearable placeholder="请输入事件名称" type="text" maxlength="30" show-word-limit/>
          </el-form-item>
          <el-form-item label="简介说明" prop="eventDesc">
            <el-input v-model="form.eventDesc" clearable placeholder="请输入简介说明" type="text" maxlength="100" show-word-limit/>
          </el-form-item>

          <el-form-item label="规则" prop="ruleType" required>
            <el-radio-group v-model="form.ruleType" @change="typeChange">
              <el-radio label="0">常规</el-radio>
              <el-radio label="2">区间</el-radio>
              <el-radio label="1">阶梯</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="周期范围" prop="scoringCycle">
            <ai-select v-model="form.scoringCycle" :selectList="dict.getDict('integralRuleScoringCycle')"/>
          </el-form-item>

          <el-form-item label="奖励次数">
            <el-input placeholder="请输入，周期范围内，不填写表示不限制" v-model.number="form.numberLimit" clearable/>
          </el-form-item>
          <!-- 常规 -->
          <el-form-item label="积分分值" prop="integral" v-if="form.ruleType == '0'">
            <el-input placeholder="请输入" v-model="form.integral" clearable/>
          </el-form-item>
          <!-- 区间 -->
          <el-form-item label="积分分值" v-if="form.ruleType == '2'">
            <ai-range v-model="form.integralArr" clearable/>
          </el-form-item>
          <!-- 阶梯 -->
          <el-form-item label="积分分值" prop="ladderIntegral" v-if="form.ruleType == '1'">
            <el-row type="flex" justify="space-between">
              <div></div>
              <el-button v-if="form.ruleType==1" type="text" icon="iconfont iconAdd"
                         @click="addIntegral">添加
              </el-button>
            </el-row>
            <el-table v-if="form.ruleType==1" :data="form.ladderIntegral" size="mini" border stripe>
              <el-table-column label="加分项" align="center">
                <template slot-scope="{row}">
                  <el-input class="tableInput" v-model.number="row.viewCount" clearable placeholder="请输入"/>
                </template>
              </el-table-column>
              <el-table-column label="获得积分" align="center">
                <template slot-scope="{row}">
                  <el-input class="tableInput" v-model="row.integral" clearable placeholder="请输入" type="number"
                            @keyup.native="row.integral=checkIntegral(row.integral)"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="{ $index }">
                  <el-button type="text" @click="handleDelete($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
    </ai-dialog>
  </section>
</template>

<script>
export default {
  name: "applyForIntegral",
  props: {
    instance: Function,
    dict: Object,
  },
  computed: {
    isEdit() {
      return !!this.form.id
    },
    dialogTitle() {
      return this.isEdit ? "编辑积分规则" : "添加积分规则"
    },
    etOps() {
      return {
        lazy: true,
        value: "dictValue",
        label: "dictName",
        lazyLoad: (node, resolve) => {
          if (node.level == 0) resolve(this.dict.getDict('integralRuleEvent'))
          else if (node.level == 1) {
            let dict = 'integralRuleEvent' + node.value
            this.dict.load(dict).then(() => {
              let nodes = this.dict.getDict(dict).map(e => ({...e, leaf: true}))
              resolve(nodes)
            })
          }
        }
      }
    },
  },
  data() {
    return {
      search: {status: "", eventName: ""},
      page: {current: 1, size: 10, total: 0},
      colConfigs: [
        {prop: "eventName", label: "事件名称", "show-overflow-tooltip": true},
        {prop: "eventDesc", label: "简介", "show-overflow-tooltip": true},
        {prop: "ruleType", label: "规则", dict: "partyIntegralRuleRuleType", align: "center"},
        {prop: "scoringCycle", label: "周期范围", dict: "integralRuleScoringCycle", align: "center"},
        {prop: "status", label: "状态", align: "center", width: 96, dict: "integralRuleStatus"},
        {slot: "options", label: "操作", align: "center"},
      ],
      integralConfigs: [
        {prop: "event", label: "加分项",},
        {prop: "event", label: "获得积分",},
        {slot: "options", label: "操作", align: "center"},
      ],
      tableData: [],
      dialog: false,
      form: {
        classify: '0',
        eventName: '',
        eventDesc: '',
        ruleType: '',
        scoringCycle: '',
        numberLimit: '', //奖励次数
        integral: '',  // 常规
        integralMin: '', // 区间
        integralMax: '',
        integralArr: [],
        ladderRule: '', // 阶梯
        ladderIntegral: [],
      },
      formRules: {
        eventName: [{required: true, message: "请输入事件名称" }],
        eventDesc: [{required: true, message: "请输入简介说明" }],
        ruleType: [{required: true, message: "请选择规则" }],
        scoringCycle: [{required: true, message: "请选择周期范围" }],
        integral: [{required: true, pattern: /^\d*[.\d]\d?$/, message: "请输入积分分值,最多保留一位小数"}],
        numberLimit: [{pattern: /^\d*$/, message: "请输入正整数"}],
        ladderIntegral: [{required: true, message: "请输入积分分值"}]
      },
      cacheOps: [],
      integralFrom: '',
      integralTo: '',
      integralData: [],
      innerVisible: false,
      table: {},
      
    };
  },
  created() {
    this.dict.load("integralRuleStatus", "partyIntegralRuleRuleType", 'integralRuleScoringCycle', 'integralRuleEvent', 'integralRuleEventType').then(() => {
      this.getList();
    });
  },
 
  methods: {
    getList() {
      this.instance.post(`/app/apppartyintegralrule/list?classify=0`, null, {
        params: {...this.search, ...this.page},
      }).then(res => {
        if (res?.data) {
          this.tableData = res.data.records;
          this.page.total = res.data.total;
        }
      });
    },
    addIntegral() {
      this.form.ladderIntegral?.push({ viewCount: null, integral: null })
    },
    toEdit(row) {
      this.instance.post(`/app/apppartyintegralrule/queryDetailById?id=${row.id}`).then((res) => {
        if(res?.data) {
          // console.log(res);
          this.form = res.data
          this.form.ruleType = res.data.ruleType
          this.form.integralArr = [ res.data.integralMin, res.data.integralMax ]
          if(res.data.ruleType == 1) {
            this.form.ladderIntegral = JSON.parse(res.data.ladderRule)
          }
          this.dialog = true
        }
      })
    },
    
    close() {
      this.form = {
        classify: '0',
        eventName: '',
        eventDesc: '',
        ruleType: '',
        scoringCycle: '',
        numberLimit: '',
        integral: '',
        integralMin: '',
        integralMax: '',
        ladderRule: [],
        integralArr: [],
        ladderIntegral: []
      }
    },

    typeChange(val) {
      this.form.ruleType = val
      this.form.scoringCycle = ''
      this.form.numberLimit = ''
      this.form.integral = ''
      this.form.integralArr = []
      this.form.ladderRule = ''
      this.form.ladderIntegral = []
    },

    remove(id) {
      this.$confirm("删除后不可恢复，是否要删除该事项？", {
        type: 'error'
      }).then(() => {
        this.instance
        .post(`/app/apppartyintegralrule/delete?ids=${id}`)
        .then((res) => {
          if (res?.code == 0) {
            this.$message.success("删除成功！");
            this.getList();
          }
        });
      });
    },
    changeStatus(id, status) {
      let text = status == 1 ? '启用' : '停用'
      this.$confirm(`确定${text}该条规则？`).then(() => {
        this.instance.post(`/app/apppartyintegralrule/enableOrDisable?id=${id}`).then((res) => {
          if (res?.code == 0) {
            this.$message.success(`${text}成功！`)
            this.getList();
          }
        });
      });
    },
    onReset() {
      this.page.current = 1
      this.search.classification = ""
      this.search.integralType = ""
      this.search.ruleStatus = ""
      this.getList();
    },
    onConfirm() {
      if(this.form.ruleType == 2) {

        this.form.integralMin = this.form.integralArr[0] || ''
        this.form.integralMax = this.form.integralArr[1] || ''

        if(!this.form.integralArr[0] && !this.form.integralArr[1]) {
          return this.$message.error('请输入积分分值')
        }
        if(this.form.integralMin >= this.form.integralMax) {
          return this.$message.error('请输入正确积分区间')
        }
      }
      if(this.form.ruleType == 1) {
        this.form.ladderRule = JSON.stringify(this.form.ladderIntegral)
      }

      if(this.form.ruleType == 2 || this.form.ruleType == 0) {
        this.form.ladderRule = ''
      }

      this.$refs.DialogForm.validate((valid) => {
        if (valid) {
          this.instance.post(`/app/apppartyintegralrule/addOrUpdate`, {
            ...this.form,
            id: this.form.id || '',
            integralMin: this.form.integralArr[0] || '',
            integralMax: this.form.integralArr[1] || '',
          }).then((res) => {
            if (res?.code == 0) {
              this.$message.success(`${this.isEdit ? '编辑成功' : '添加成功'}`)
              this.dialog = false;
              this.close()
              this.getList()
            }
          });
        } else {
          return false;
        }
      });
    },
    handleTypeSearch(v) {
      this.search.event = v?.[0]
      this.search.type = v?.[1]
      this.page.current = 1
      this.$refs.eventTypeSearch.dropDownVisible = false
      this.getList()
    },
    handleTypeForm(v) {
      if (this.dialog) {
        this.form.event = v?.[0]
        this.form.type = v?.[1]
        this.form.ruleType = !this.form.event ? null : this.form.event == 3 ? 1 : 0
      }
    },
    handleDelete(i) {
      this.$confirm("是否要删除该规则?").then(() => {
        this.form.ladderIntegral.splice(i, 1)
      }).catch(() => 0)
    },
    checkIntegral(v) {
      return /\.\d{2,}$/.test(v) ? Math.abs(v).toFixed(1) : Math.abs(v)
    }
  },
};
</script>

<style lang="scss" scoped>
.applyForIntegral {
  height: 100%;
  background: #f3f6f9;

  

}
</style>
