<template>
  <div class="automaticallyAddCent">
    <ai-list>
    <template #content>
      <ai-search-bar bottomBorder style="margin-top: 16px">
        <template #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>
      </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-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="eventType" width="100%">
            <el-cascader v-model="form.eventType" :props="etOps" clearable placeholder="请选择" @change="handleTypeForm"
                         :options="cacheOps" style="width: 100%"></el-cascader>
          </el-form-item>
          <el-form-item label="规则">
            <span>常规</span>
          </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>
      </div>
    </ai-dialog>
  </div>
</template>

<script>
export default {
  name: "automaticallyAddCent",
  props: {
    instance: Function,
    dict: Object,
  },
  data() {
    return {
      search: { status: ""},
      page: {current: 1, size: 10, total: 0},
      tableData: [],
      page: {current: 1, size: 10, total: 0},
      colConfigs: [
        {prop: "event", label: "事件", dict: "partyIntegralRuleEvent", align: "center"},
        {prop: "type", label: "类型", dict: "integralRuleEvent4", align: "center"},
        {prop: "ruleType", label: "规则", dict: "integralRuleRuleType"},
        {prop: "scoringCycle", label: "周期范围", dict: "integralRuleScoringCycle", align: "center"},
        {prop: "status", label: "状态", align: "center", width: 96, dict: "integralRuleStatus"},
        {slot: "options", label: "操作", align: "center"},
      ],
      formRules: {
        eventType: [{required: true, message: "请选择事件类型" }],
        scoringCycle: [{required: true, message: "请选择周期范围" }],
        integral: [{required: true, pattern: /^\d*[.\d]\d?$/, message: "请输入积分分值,最多保留一位小数"}],
        numberLimit: [{pattern: /^\d*$/, message: "请输入正整数"}],
      },
      form: {
        classify: 1,
        eventType: '',
        event: '',
        type: '',
        ruleType: 0,
        scoringCycle: '',
        integral: '',  // 常规
        integralArr: [],
      },
      dialog: false,
      cacheOps: [],
      isEdit: false,
      flag: false,
    }
  }, 
  created() {
    this.$dict.load("integralRuleStatus", "integralRuleRuleType", 'integralRuleScoringCycle', 'integralRuleEvent', 'integralRuleEventType','partyIntegralRuleEvent','partyIntegralRuleEvent4','integralRuleEvent4').then(() => {
      this.getList();
    });
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? "编辑积分规则" : "添加积分规则"
    },
    etOps() {
      return {
        lazy: true,
        value: "dictValue",
        label: "dictName",
        lazyLoad: (node, resolve) => {
          if (node.level == 0) resolve(this.dict.getDict('partyIntegralRuleEvent'))
          else if (node.level == 1) {
            let dict = 'integralRuleEvent4' 
            this.dict.load(dict).then(() => {
              let nodes = this.dict.getDict(dict).map(e => ({...e, leaf: true}))
              resolve(nodes)
            })
          }
        }
      }
    },
  },
  methods: {
    getList() {
      this.instance.post(`/app/apppartyintegralrule/list?classify=1`, null, {
        params: {...this.search, ...this.page},
      }).then(res => {
        if (res?.data) {
          this.tableData = res.data.records;
          this.page.total = res.data.total;
        }
      });
    },
    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
      }
    },
    close() {
      this.form = {
        classify: 1,
        eventType: '',
        event: '',
        type: '',
        ruleType: 0,
        scoringCycle: '',
        integral: '',
        integralArr: [],
      }
    },
    onConfirm() {
      this.$refs.DialogForm.validate((valid) => {
        this.flag = true
        if (valid) {
          this.instance.post(`/app/apppartyintegralrule/addOrUpdate`, {
            ...this.form,
            id: this.form.id
          }).then((res) => {
            if (res.code == 0) {
              this.$message.success(`${this.isEdit ? '编辑成功' : '添加成功'}`)
              this.dialog = false;
              this.getList()
            }
          }).catch(() => {
            this.flag = false;
          })
        } else {
          this.flag = false;
        }
      });

    },
    toEdit(row) {
      this.form = this.$copy(row)
      let {event, type} = this.form
      this.$dict.load('partyIntegralDetailType').then(() => {
        this.form.eventType = [event, type]
        this.cacheOps = this.$dict.getDict('partyIntegralRuleEvent').map(e => {
          if (e.dictValue == event) {
            e.children = this.$dict.getDict('integralRuleEvent4').map(d => ({...d, leaf: true}))
          }
          return e
        })
        this.$nextTick(() => {
          this.dialog = true
        })
      })
    },
    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();
          }
        });
      });
    },
  },
}
</script>

<style>
.automaticallyAddCent {}
</style>