<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="businessId">
        <el-input
          v-model="queryParams.businessId"
          placeholder="请输入订单关联"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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="change"></el-date-picker>
              </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="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['his:userIntegralLogs:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="userIntegralLogsList" @selection-change="handleSelectionChange">
      <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="intefralLogTypeOptions" :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" />

    </el-table>

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

    <!-- 添加或修改积分记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="1 签到获得积分 2购买商品获得积分 3购买积分商品 " prop="logType">
          <el-select v-model="form.logType" placeholder="请选择1 签到获得积分 2购买商品获得积分 3购买积分商品 ">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="积分 正数表示增加积分，负数表示减少积分" prop="integral">
          <el-input v-model="form.integral" placeholder="请输入积分 正数表示增加积分，负数表示减少积分" />
        </el-form-item>
        <el-form-item label="积分余额" prop="balance">
          <el-input v-model="form.balance" placeholder="请输入积分余额" />
        </el-form-item>
        <el-form-item label="订单关联id" prop="businessId">
          <el-input v-model="form.businessId" placeholder="请输入订单关联id" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUserIntegralLogs, getUserIntegralLogs, delUserIntegralLogs, addUserIntegralLogs, updateUserIntegralLogs, exportUserIntegralLogs } from "@/api/his/userIntegralLogs";

export default {
  name: "UserIntegralLogs",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      intefralLogTypeOptions: [],
      // 总条数
      total: 0,
      // 积分记录表格数据
      userIntegralLogsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      createTime:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        logtype: null,
        integral: null,
        balance: null,
        businessId: null,
        createTime: null,
        phone:null,
        sTime:null,
        eTime:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_integral_log_type").then(response => {
      this.intefralLogTypeOptions = this.mergeLogTypeOptions(response.data || []);
    });
  },
  methods: {
    /** 合并字典与本地兜底类型，确保所有已知 logType 都有对应名称 */
    mergeLogTypeOptions(dictOptions) {
      // 本地完整映射（与后端 FsUserIntegralLogTypeEnum 对齐），字典缺失时兜底
      const localMap = {
        1: '签到获得积分', 2: '消费获得积分', 3: '分享获得积分', 4: '退款扣除积分',
        5: '购买积分商品', 6: '平台取消售后', 7: '积分过期', 8: '螳螂同步积分',
        9: '购买课程小节扣除', 10: '观看课程获取积分', 11: '新用户完善就诊人获得积分',
        12: '新用户填写收货地址获取积分', 13: '浏览商品获得积分', 14: '浏览视频获得积分',
        15: '首次下单疗法获得积分', 16: '点播看课获得积分', 17: '点播答题获得积分',
        18: '邀请新用户获取积分', 19: '填写邀请码获取积分', 20: '首次完成手机号绑定注册',
        21: '首次完成专家咨询', 22: '首次完成积分商城下单', 23: '管理员添加',
        24: '付费课程订阅', 25: '下单使用积分抵扣', 26: '取消订单退回积分', 27: '退款订单退回积分'
      };
      // 字典已有项优先，收集已有 value
      const result = [...dictOptions];
      const existValues = new Set(dictOptions.map(o => Number(o.dictValue)));
      // 补充字典缺失的类型
      Object.keys(localMap).forEach(key => {
        const val = Number(key);
        if (!existValues.has(val)) {
          result.push({ dictValue: String(val), dictLabel: localMap[val] });
        }
      });
      return result;
    },
    /** 查询积分记录列表 */
    getList() {
      this.loading = true;
      listUserIntegralLogs(this.queryParams).then(response => {
        this.userIntegralLogsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        logType: null,
        integral: null,
        balance: null,
        businessId: null,
        createTime: null
      };

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.createTime=null;
      this.queryParams.sTime=null;
      this.queryParams.eTime=null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加积分记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUserIntegralLogs(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改积分记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUserIntegralLogs(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUserIntegralLogs(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    change(){
          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;
          }

        },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除积分记录编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUserIntegralLogs(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有积分记录数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportUserIntegralLogs(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
