<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="用户手机号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入用户手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 用户列表 -->
    <el-table v-loading="loading" :data="userList">
      <el-table-column label="用户ID" align="center" prop="userId" width="100" />
      <el-table-column label="用户名称" align="center" prop="nickName" />
      <el-table-column label="手机号码" align="center" prop="phone" width="150" />
      <el-table-column label="积分" align="center" prop="integral" width="120" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewLogs(scope.row)"
          >查看积分明细</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAddIntegral(scope.row)"
          >添加积分</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 积分明细对话框 -->
    <el-dialog title="积分明细" :visible.sync="logsOpen" width="900px" append-to-body @close="handleLogsDialogClose">
      <!-- 查询条件 -->
      <el-form :model="logsQueryParams" ref="logsQueryForm" size="small" :inline="true" style="margin-bottom: 15px;">
        <el-form-item label="积分类型" prop="logType">
          <el-select v-model="logsQueryParams.logType" placeholder="请选择积分类型" clearable style="width: 200px;">
            <el-option v-for="item in logTypeOptions" :key="item.dictCode" :label="item.dictLabel" :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleLogsQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetLogsQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 积分明细表格 -->
      <el-table v-loading="logsLoading" :data="logsList" border style="width: 100%">
        <el-table-column label="ID" align="center" prop="id" width="80" />
        <el-table-column label="积分类型" align="center" prop="logType" width="120">
          <template slot-scope="scope">
            <span>{{ getLogTypeName(scope.row.logType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="积分变化" align="center" prop="integral" width="120">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.integral >= 0 ? '#67C23A' : '#F56C6C' }">
              {{ scope.row.integral >= 0 ? '+' : '' }}{{ scope.row.integral }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="积分余额" align="center" prop="balance" width="120" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="logsTotal > 0"
        :total="logsTotal"
        :page.sync="logsParams.pageNum"
        :limit.sync="logsParams.pageSize"
        @pagination="loadLogsList"
        style="margin-top: 15px;"
      />
    </el-dialog>

    <!-- 添加积分对话框 -->
    <el-dialog title="添加积分" :visible.sync="addOpen" width="500px" append-to-body>
      <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="100px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="addForm.userId" disabled />
        </el-form-item>
        <el-form-item label="用户名称" prop="nickName">
          <el-input v-model="addForm.nickName" disabled />
        </el-form-item>
        <el-form-item label="当前积分" prop="currentIntegral">
          <el-input v-model="addForm.currentIntegral" disabled />
        </el-form-item>
        <el-form-item label="积分类型" prop="logType">
          <el-select v-model="addForm.logType" placeholder="请选择积分类型" style="width: 100%">
            <el-option v-for="item in logTypeOptions" :key="item.dictCode" :label="item.dictLabel" :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="积分数量" prop="integral">
          <el-input-number
            v-model="addForm.integral"
            :min="1"
            :precision="0"
            placeholder="请输入积分数量"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAdd">确 定</el-button>
        <el-button @click="cancelAdd">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getIntegralLogs, addIntegral } from "@/api/user/integral";
import { parseTime, resetForm, selectDictLabel } from "@/utils/common";

export default {
  name: "Integral",
  data() {
    return {
      // 遮罩层
      loading: true,
      logsLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户列表
      userList: [],
      // 积分明细列表
      logsList: [],
      // 积分明细分页参数
      logsParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null
      },
      // 积分明细查询条件
      logsQueryParams: {
        logType: null
      },
      // 积分明细总数
      logsTotal: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        phone: null,
        nickName: null
      },
      // 字典：积分类型
      logTypeOptions: [],
      // 积分明细对话框
      logsOpen: false,
      // 添加积分对话框
      addOpen: false,
      // 添加积分表单
      addForm: {},
      // 添加积分表单校验
      addRules: {
        logType: [
          { required: true, message: "积分类型不能为空", trigger: "change" }
        ],
        integral: [
          { required: true, message: "积分数量不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    // 仅加载字典，不默认拉取数据
    this.getDicts("sys_integral_log_type").then(res => {
      this.logTypeOptions = res.data || [];
    });
    this.loading = false;
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      // 必须输入手机号或昵称才允许查询
      if (!this.queryParams.phone && !this.queryParams.nickName) {
        this.$message.warning("请先输入用户手机号或昵称再查询");
        this.userList = [];
        this.total = 0;
        return;
      }
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    // resetQuery() {
    //   this.resetForm("queryForm");
    //   this.handleQuery();
    // },
    /** 查看积分明细 */
    handleViewLogs(row) {
      this.logsOpen = true;
      // 重置分页参数和查询条件
      this.logsParams = {
        pageNum: 1,
        pageSize: 10,
        userId: row.userId
      };
      this.logsQueryParams = {
        logType: null
      };
      this.logsList = [];
      this.logsTotal = 0;
      this.loadLogsList();
    },
    /** 加载积分明细列表 */
    loadLogsList() {
      this.logsLoading = true;
      const params = {
        pageNum: this.logsParams.pageNum,
        pageSize: this.logsParams.pageSize
      };
      // 添加查询条件
      if (this.logsQueryParams.logType) {
        params.logType = this.logsQueryParams.logType;
      }
      getIntegralLogs(this.logsParams.userId, params).then(response => {
        this.logsList = response.data || [];
        this.logsTotal = response.total || 0;
        this.logsLoading = false;
      }).catch(() => {
        this.logsLoading = false;
      });
    },
    /** 积分明细搜索 */
    handleLogsQuery() {
      this.logsParams.pageNum = 1;
      this.loadLogsList();
    },
    /** 重置积分明细查询条件 */
    resetLogsQuery() {
      this.logsQueryParams = {
        logType: null
      };
      this.logsParams.pageNum = 1;
      this.loadLogsList();
    },
    /** 积分明细对话框关闭 */
    handleLogsDialogClose() {
      this.logsList = [];
      this.logsParams = {
        pageNum: 1,
        pageSize: 10,
        userId: null
      };
      this.logsQueryParams = {
        logType: null
      };
      this.logsTotal = 0;
    },
    /** 添加积分 */
    handleAddIntegral(row) {
      this.reset();
      this.addForm = {
        userId: row.userId,
        nickName: row.nickName,
        currentIntegral: row.integral || 0,
        logType: null,
        integral: null
      };
      this.addOpen = true;
    },
    /** 提交添加积分 */
    submitAdd() {
      this.$refs["addForm"].validate(valid => {
        if (valid) {
          addIntegral({
            userId: this.addForm.userId,
            logType: this.addForm.logType,
            integral: this.addForm.integral
          }).then(response => {
            this.$message.success("添加积分成功");
            this.addOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 取消添加积分 */
    cancelAdd() {
      this.addOpen = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.addForm = {
        userId: null,
        nickName: null,
        currentIntegral: null,
        logType: null,
        integral: null
      };
      this.resetForm("addForm");
    },
    /** 获取积分类型名称 */
    getLogTypeName(logType) {
      return selectDictLabel(this.logTypeOptions, String(logType)) || "未知类型";
    },
    parseTime,
    resetForm
  }
};
</script>

