<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">
            <ai-select
              v-model="search.classification"
              @change="search.current = 1, getList()"
              placeholder="请选择分类"
              :selectList="dict.getDict('atWillReportType')">
            </ai-select>
            <ai-select
              v-model="search.integralType"
              @change="search.current = 1, getList()"
              placeholder="请选择类型"
              :selectList="dict.getDict('integralIntegralType')">
            </ai-select>
            <ai-select
              v-model="search.ruleStatus"
              @change="search.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="addRule">添加</el-button>
          </template>
        </ai-search-bar>
        <ai-table
          :tableData="tableData"
          :col-configs="colConfigs"
          :total="total"
          ref="aitableex"
          :current.sync="search.current"
          :size.sync="search.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.ruleStatus == 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-dialog
      :title="dialog.title"
      :visible.sync="dialog.visible"
      :customFooter="true"
      :destroyOnClose="true"
      @close="init('ruleForm')"
      width="520px">
      <div class="form_div">
        <el-form
          ref="ruleForm"
          :model="dialogInfo"
          :rules="formRules"
          size="small"
          label-suffix="："
          label-width="100px">
          <el-form-item label="类别" prop="classification">
            <ai-select
              size="small"
              v-model="dialogInfo.classification"
              placeholder="请选择..."
              :selectList="dict.getDict('atWillReportType')">
            </ai-select>
          </el-form-item>
          <el-form-item label="事项" prop="ruleName">
            <el-input placeholder="请输入…" v-model="dialogInfo.ruleName"></el-input>
          </el-form-item>
          <el-form-item label="规则说明" prop="ruleDescription">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入…"
              v-model="dialogInfo.ruleDescription">
            </el-input>
          </el-form-item>
          <el-form-item label="类型" prop="integralType">
            <el-radio-group v-model="dialogInfo.integralType">
              <el-radio label="1">加分</el-radio>
              <el-radio label="0">扣分</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- <el-form-item label="分值" prop="integralValueType">
            <el-radio-group v-model="dialogInfo.integralValueType" @change="numTypeChange">
              <el-radio label="0">固定分值</el-radio>
              <el-radio label="1">区间分值</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <!-- <el-form-item label="积分" required v-if="dialogInfo.integralValueType == '1'">
            <el-col :span="7" style="width: 30%;">
              <el-form-item prop="integralStart">
                <el-input placeholder="请输入整数" v-model="dialogInfo.integralStart"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="line" :span="1" style="width: 4%;text-align:center;">-</el-col>
            <el-col :span="7" style="width: 30%;">
              <el-form-item prop="integralEnd">
                <el-input placeholder="请输入整数" v-model="dialogInfo.integralEnd"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="line" :span="9" style="width: 36%;"></el-col>
          </el-form-item> -->
          <el-form-item label="积分" required v-if="dialogInfo.integralValueType == '0'">
            <el-form-item prop="integral">
              <el-input placeholder="请输入自然数" v-model="dialogInfo.integral"></el-input>
            </el-form-item>
          </el-form-item>
        </el-form>
      </div>
      <div class="dialog-footer" slot="footer">
        <el-button @click="dialog.visible=false" size="medium">取消</el-button>
        <el-button @click="onConfirm('ruleForm')" type="primary" size="medium">确认</el-button>
      </div>
    </ai-dialog>
  </section>
</template>

<script>
export default {
  name: "AppScoreRules",
  label: "积分规则",
  props: {
    instance: Function,
    dict: Object,
  },

  data() {
    var integralPass = (rule, value, callback) => {
      if (value) {
        if ((/(^[0-9]\d*$)/.test(value))) {
          callback();
        } else {
          callback(new Error("请输入自然数"));
        }
      } else {
        callback(new Error("请输入积分"));
      }
    };
    var integralStartPass = (rule, value, callback) => {
      if (value) {
        if ((/(^[1-9]\d*$)/.test(value))) {
          callback();
        } else {
          callback(new Error("请输入整数积分"));
        }
      } else {
        callback(new Error("请输入积分"));
      }
    };
    var integralEndPass = (rule, value, callback) => {
      if (value) {
        if ((/(^[1-9]\d*$)/.test(value))) {
          if (Number(value) < Number(this.dialogInfo.integralStart)) {
            callback(new Error("请输入大于前面数字的积分"));
          } else {
            callback()
          }
        } else {
          callback(new Error("请输入整数积分"));
        }
      } else {
        callback(new Error("请输入积分"));
      }
    };
    return {
      search: {
        current: 1,
        size: 10,
        classification: "",
        integralType: "",
        ruleStatus: "",
      },
      total: 10,
      colConfigs: [
        {
          prop: "classification", label: "类型", width: 168,
          formart: (classification) =>
              this.dict.getLabel("atWillReportType", classification),
        },
        {prop: "ruleName", label: "事项", "show-overflow-tooltip": true, width: 260},
        {prop: "ruleDescription", label: "规则说明", width: 390},
        {
          prop: "integralType",
          label: "类型",
          width: 60,
          formart: (integralType) =>
              this.dict.getLabel("integralIntegralType", integralType),
        },
        {slot: "integral", label: "分值", width: 70},
        {prop: "doTime", label: "最后编辑时间", width: 160},
        {prop: "doUserName", label: "操作人", width: 120},
        {
          prop: "ruleStatus",
          label: "状态",
          align: "center",
          width: 96,
          fixed: "right",
          render: (h, params) => {
            return h(
                "span",
                {
                  class: "status-" + params.row.ruleStatus,
                },
                this.dict.getLabel("integralRuleStatus", params.row.ruleStatus)
            );
          },
        },
        {slot: "options", label: "操作", align: "center"},
      ],
      tableData: [],

      dialog: {
        title: "",
        visible: false,
      },
      dialogInfo: {
        classification: "",
        ruleName: "",
        ruleDescription: "",
        integralType: '1',
        integralValueType: '0',
        integral: "",
        // integralStart: "",
        // integralEnd: "",
        doTime: '',
        id: '',
        doUserId: '',
        doUserName: '',
      },
      formRules: {
        classification: [
          {required: true, message: "请选择类型", trigger: "change"},
        ],
        ruleName: [{required: true, message: "请输入事项", trigger: "blur"}],
        ruleDescription: [
          {required: true, message: "请输入规则说明", trigger: "blur"},
        ],
        integralType: [
          {required: true, message: "请选择类型", trigger: "change"},
        ],
        integralValueType: [
          {required: true, message: "请选择分值类型", trigger: "change"},
        ],
        integral: [
          {required: true, validator: integralPass, trigger: "change"},
        ],
        integralStart: [
          {required: true, validator: integralStartPass, trigger: "change"},
        ],
        integralEnd: [
          {required: true, validator: integralEndPass, trigger: "change"},
        ],
      },
    };
  },

  created() {
    this.dict.load(["classification", "integralIntegralType", "integralRuleStatus", 'atWillReportType']).then(() => {
      this.getList();
    });
  },

  methods: {
    getList() {
      this.instance
      .post(`/app/appvillagerintegralrule/list`, null, {
        params: {
          ...this.search,
        },
      })
      .then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.records;
          this.total = res.data.total;
        }
      });
    },

    toEdit(row) {
      this.dialog.title = "编辑积分规则";
      this.dialog.visible = true;
      this.dialogInfo = {...row}
      this.dialogInfo.integralStart = Math.abs(this.dialogInfo.integralStart)
      this.dialogInfo.integralEnd = Math.abs(this.dialogInfo.integralEnd)
      this.dialogInfo.integral = Math.abs(this.dialogInfo.integral)
    },

    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) {
      var 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.search.current = 1
      this.search.classification = ""
      this.search.integralType = ""
      this.search.ruleStatus = ""
      this.getList();
    },

    onAdd() {
      this.$emit("change", {
        type: "add",
      });
    },

    addRule() {
      this.dialog.title = "添加积分规则";
      this.dialog.visible = true;
    },

    onConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.instance
          .post(`/app/appvillagerintegralrule/addOrUpdate`, this.dialogInfo)
          .then((res) => {
            if (res.code == 0) {
              this.$message.success(`${this.dialogInfo.id ? '编辑成功' : '添加成功'}`)
              this.onReset()
              this.onCancel();
            }
          });
        } else {
          return false;
        }
      });
    },

    onCancel() {
      this.dialog.visible = false;
    },

    numTypeChange() {
      // this.dialogInfo.integra = "";
      // this.dialogInfo.integralStart = "";
      // this.dialogInfo.integralEnd = "";
    },

    init(formName) {
      this.$refs[formName].clearValidate();
      Object.keys(this.dialogInfo).forEach((e) => {
        this.dialogInfo[e] = "";
      });
      this.dialogInfo.integralType = '1'
      this.dialogInfo.integralValueType = '0'
    },
  },
};
</script>

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

  .cur-p {
    cursor: pointer;
  }

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

  .status-0 {
    color: #ff4466;
  }

  .status-1 {
    color: #2ea222;
  }
}
</style>
