<template>
  <section class="AppScoreRules">
    <ai-list v-if="permissions('app_appvillagerintegralrule_detail')">
      <template slot="title">
        <ai-title title="积分规则" isShowBottomBorder></ai-title>
      </template>
      <template slot="content">
        <ai-search-bar bottomBorder>
          <template slot="left">
            <el-cascader size="small" v-model="search.eventType" placeholder="请选择事件/类型" clearable
                         :props="{...etOps,checkStrictly:true}" @change="handleTypeSearch" ref="eventTypeSearch"/>
            <ai-select
                v-model="search.status"
                @change="page.current = 1, getList()"
                placeholder="请选择状态"
                :selectList="dict.getDict('integralRuleStatus')">
            </ai-select>
          </template>
          <template slot="right">
          </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" :disabled="!permissions('app_appvillagerintegralrule_edit')" @click="changeStatus(row.id, 0)" v-if="row.status == 1">
                  停用
                </el-button>
                <el-button type="text" :disabled="!permissions('app_appvillagerintegralrule_edit')" @click="changeStatus(row.id, 1)" v-else>启用</el-button>
                <el-button type="text" :disabled="!permissions('app_appvillagerintegralrule_edit')" @click="toEdit(row)">编辑</el-button>
                <el-button type="text" :disabled="!permissions('app_appvillagerintegralrule_del')" @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="form={ladderRule: []}" width="700px">
      <div class="form_div">
        <el-form ref="DialogForm" :model="form" :rules="formRules" size="small" label-suffix="：" label-width="100px">
          <el-form-item label="事件/类型" prop="eventType">
            <el-cascader v-model="form.eventType" :props="etOps" clearable placeholder="请选择" @change="handleTypeForm"
                         :options="cacheOps"/>
          </el-form-item>
          <el-form-item label="规则" prop="ruleType" v-if="form.ruleType>-1" required>
            <el-row type="flex" justify="space-between">
              <div v-text="dict.getLabel('integralRuleRuleType',form.ruleType)"/>
              <el-button v-if="form.ruleType==1" type="text" icon="iconfont iconAdd"
                         @click="form.ladderRule.push({viewCount:null,integral:null})">添加
              </el-button>
            </el-row>
            <el-table v-if="form.ruleType==1" :data="form.ladderRule" 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="{row,$index}">
                  <el-button type="text" @click="handleDelete($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="周期范围" prop="scoringCycle">
            <ai-select v-model="form.scoringCycle" :selectList="dict.getDict('integralRuleScoringCycle')"/>
          </el-form-item>
          <template v-if="form.ruleType==0">
            <el-form-item label="奖励次数" prop="numberLimit">
              <el-input placeholder="请输入,周期范围内,不填写表示不限制" v-model.number="form.numberLimit" clearable/>
            </el-form-item>
            <el-form-item label="积分分值" prop="integral">
              <el-input placeholder="请输入" v-model="form.integral" clearable/>
            </el-form-item>
          </template>
        </el-form>
      </div>
    </ai-dialog>
  </section>
</template>

<script>
export default {
  name: "AppScoreRules",
  label: "积分规则",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function
  },
  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: "", eventType: null},
      page: {current: 1, size: 10, total: 0},
      colConfigs: [
        {prop: "event", label: "事件", dict: "integralRuleEvent"},
        {prop: "type", label: "类型", dict: "integralRuleEventType"},
        {prop: "ruleType", label: "规则", dict: "integralRuleRuleType"},
        {prop: "scoringCycle", label: "周期范围", dict: "integralRuleScoringCycle"},
        {prop: "status", label: "状态", align: "center", width: 96, dict: "integralRuleStatus"},
        {slot: "options", label: "操作", align: "center"},
      ],
      tableData: [],
      dialog: false,
      form: {ladderRule: []},
      formRules: {
        eventType: [{required: true, message: "请选择事件/类型", trigger: "change"}],
        scoringCycle: [{required: true, message: "请选择周期范围", trigger: "change"}],
        integral: [{required: true, pattern: /^\d*[.\d]\d?$/, message: "请输入积分分值,最多保留一位小数"}],
        numberLimit: [{pattern: /^\d*$/, message: "请输入正整数"}]
      },
      cacheOps: []
    };
  },
  created() {
    this.dict.load("integralRuleStatus", "integralRuleRuleType", 'integralRuleScoringCycle', 'integralRuleEvent', 'integralRuleEventType').then(() => {
      this.getList();
    });
  },
  methods: {
    getList() {
      this.instance.post(`/app/appvillagerintegralrule/list`, null, {
        params: {...this.search, ...this.page},
      }).then(res => {
        if (res?.data) {
          this.tableData = res.data.records;
          this.page.total = res.data.total;
        }
      });
    },
    toEdit(row) {
      this.form = this.$copy(row)
      let {ladderRule, event, type} = this.form,
          dict = 'integralRuleEvent' + event
      this.dict.load(dict).then(() => {
        this.form.eventType = [event, type]
        this.form.ladderRule = JSON.parse(ladderRule || "[]")
        this.cacheOps = this.dict.getDict('integralRuleEvent').map(e => {
          if (e.dictValue == event) {
            e.children = this.dict.getDict(dict).map(d => ({...d, leaf: true}))
          }
          return e
        })
        this.$nextTick(() => {
          this.dialog = true
        })
      })
    },
    remove(id) {
      this.$confirm("删除后不可恢复，是否要删除该事项？", {
        type: 'error'
      }).then(() => {
        this.instance
        .post(`/app/appvillagerintegralrule/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/appvillagerintegralrule/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==1 && !this.form.ladderRule.length) {
        return this.$message.error('请添加规则')
      }
      this.$refs.DialogForm.validate((valid) => {
        if (valid) {
          let formData = this.$copy(this.form)
          formData.ladderRule = JSON.stringify(formData.ladderRule)
          formData.integral = formData.integral || 0
          this.instance.post(`/app/appvillagerintegralrule/addOrUpdate`, formData).then((res) => {
            if (res.code == 0) {
              this.$message.success(`${this.isEdit ? '编辑成功' : '添加成功'}`)
              this.onReset()
              this.dialog = false;
            }
          });
        } 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.ladderRule.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>
.AppScoreRules {
  height: 100%;
  background: #f3f6f9;

  ::v-deep .ai-list__content--right {
    width: 100%;
  }

  ::v-deep .ai-dialog {
    .el-cascader {
      width: 100%;
    }

    .tableInput {
      & > input {
        text-align: center;
        border: none;
        background: transparent;
      }
    }
  }
}
</style>
