<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="用户id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入用户电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类别" prop="logType">
        <el-select v-model="queryParams.logType" placeholder="请选择类别" clearable size="small">
          <el-option
            v-for="dict in integralLogTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间" prop="createTime">
        <el-date-picker v-model="createTime" size="small" style="width: 220px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="changeTime" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAddIntegral"
          v-hasPermi="['user:integral:add']"
        >增加积分</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-minus"
          size="mini"
          @click="handleDeductIntegral"
          v-hasPermi="['user:integral:deduct']"
        >扣除积分</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="integralLogsList">
      <el-table-column label="用户id" align="center" prop="userId" />
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="用户电话" align="center" prop="phone" />
      <el-table-column label="类别" align="center" prop="logType">
        <template slot-scope="scope">
          <dict-tag :options="integralLogTypeOptions" :value="scope.row.logType"/>
        </template>
      </el-table-column>
      <el-table-column label="积分" align="center" prop="integral" />
      <el-table-column label="积分余额" align="center" prop="balance" />
      <el-table-column label="订单关联id" align="center" prop="businessId" />
      <el-table-column label="时间" align="center" prop="createTime" width="160" />
    </el-table>

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

    <!-- 增加/扣除积分弹窗 -->
    <el-dialog :title="integralDialogTitle" :visible.sync="integralDialogOpen" width="500px" append-to-body>
      <el-form ref="integralForm" :model="integralForm" :rules="integralRules" label-width="100px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="integralForm.userId" placeholder="请输入用户ID" @blur="handleCheckUser" />
        </el-form-item>
        <el-form-item label="用户信息" v-if="checkedUserInfo">
          <span>{{ checkedUserInfo.nickName }} / {{ checkedUserInfo.phone }} / 当前积分：{{ checkedUserInfo.integral }}</span>
        </el-form-item>
        <el-form-item label="类别">
          <span>{{ integralForm.type === 'add' ? '管理员后台添加' : '管理员后台删减' }}</span>
        </el-form-item>
        <el-form-item :label="integralForm.type === 'add' ? '增加积分' : '扣除积分'" prop="integral">
          <el-input-number v-model="integralForm.integral" :min="1" :step="1" placeholder="请输入积分数量" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitIntegralForm" :disabled="!checkedUserInfo">确 定</el-button>
        <el-button @click="cancelIntegralDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUserIntegralLogs, checkUser, addIntegral, deductIntegral } from "@/api/his/userIntegral";

export default {
  name: "UserIntegral",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 积分类别字典
      integralLogTypeOptions: [],

      // 总条数
      total: 0,
      // 积分记录表格数据
      integralLogsList: [],
      // 时间范围
      createTime: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        phone: null,
        logType: null,
        sTime: null,
        eTime: null
      },
      // 增加/扣除积分弹窗
      integralDialogOpen: false,
      integralDialogTitle: "",
      checkedUserInfo: null,
      integralForm: {
        userId: null,
        logType: null,
        integral: null,
        type: "add"
      },
      integralRules: {
        userId: [
          { required: true, message: "请输入用户ID", trigger: "blur" }
        ],

        integral: [
          { required: true, message: "请输入积分数量", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_integral_log_type").then(response => {
      this.integralLogTypeOptions = response.data;
    });
  },
  methods: {
    /** 查询积分记录列表 */
    getList() {
      this.loading = true;
      listUserIntegralLogs(this.queryParams).then(response => {
        this.integralLogsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.createTime = null;
      this.queryParams.sTime = null;
      this.queryParams.eTime = null;
      this.handleQuery();
    },
    /** 时间范围变化 */
    changeTime() {
      if (this.createTime != null) {
        this.queryParams.sTime = this.createTime[0];
        this.queryParams.eTime = this.createTime[1];
      } else {
        this.queryParams.sTime = null;
        this.queryParams.eTime = null;
      }
    },
    /** 校验用户 */
    handleCheckUser() {
      if (!this.integralForm.userId) {
        this.checkedUserInfo = null;
        return;
      }
      checkUser(this.integralForm.userId).then(response => {
        if (response.code === 200) {
          this.checkedUserInfo = {
            nickName: response.nickName,
            phone: response.phone,
            integral: response.integral
          };
        } else {
          this.checkedUserInfo = null;
          this.$message.error("用户不存在");
        }
      }).catch(() => {
        this.checkedUserInfo = null;
      });
    },

    /** 增加积分按钮操作 */
    handleAddIntegral() {
      this.integralForm = { userId: null, logType: 23, integral: null, type: "add" };
      this.checkedUserInfo = null;
      this.integralDialogTitle = "增加积分";
      this.integralDialogOpen = true;
      this.$nextTick(() => {
        this.$refs.integralForm && this.$refs.integralForm.clearValidate();
      });
    },
    /** 扣除积分按钮操作 */
    handleDeductIntegral() {
      this.integralForm = { userId: null, logType: 28, integral: null, type: "deduct" };
      this.checkedUserInfo = null;
      this.integralDialogTitle = "扣除积分";
      this.integralDialogOpen = true;
      this.$nextTick(() => {
        this.$refs.integralForm && this.$refs.integralForm.clearValidate();
      });
    },
    /** 提交积分表单 */
    submitIntegralForm() {
      this.$refs["integralForm"].validate(valid => {
        if (valid) {
          const data = {
            userId: this.integralForm.userId,
            logType: this.integralForm.logType,
            integral: this.integralForm.integral
          };
          if (this.integralForm.type === "add") {
            addIntegral(data).then(response => {
              if (response.code === 200) {
                this.msgSuccess("增加积分成功");
                this.integralDialogOpen = false;
                this.getList();
              }
            });
          } else {
            deductIntegral(data).then(response => {
              if (response.code === 200) {
                this.msgSuccess("扣除积分成功");
                this.integralDialogOpen = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 取消积分弹窗 */
    cancelIntegralDialog() {
      this.integralDialogOpen = false;
      this.checkedUserInfo = null;
    }
  }
};
</script>
