<template>

  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="福袋名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入福袋名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="状态" prop="dataStatus">
        <el-select v-model="queryParams.dataStatus" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </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="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"

        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleUpdate"
          :disabled="single"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"

        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="rewardList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="福袋名称" align="center" prop="name" />
      <el-table-column label="福袋类型" align="center" prop="rewardType">
        <template slot-scope="scope">
          <dict-tag :options="typeOptions" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="dataStatus">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.dataStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="福袋内容" align="center" prop="actualRewards">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewReward(scope.row)"
          >查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"

          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(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="title" :visible.sync="open" :width="width" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="福袋名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入奖励名称" style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="福袋类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择福袋类型" clearable size="small">
            <el-option
              v-for="item in this.typeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <!-- 当选择定值时显示数字输入框 -->
        <el-form-item v-if="form.type === '1'" label="定值金额" prop="amount">
          <el-input-number :min="1" :step="1" :max="9999" :precision="0" v-model="form.amount" placeholder="期望值" />
        </el-form-item>
        <el-form-item v-if="form.type === '2'" label="随机奖励" prop="rewardItems">
          <div class="reward-table-container">
            <div class="table-header">
              <span>随机奖励配置</span>
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="addRewardItem">添加奖励项</el-button>
            </div>
            <el-table :data="form.rewardItems" border size="small">
              <el-table-column label="奖励模式">
                <template slot-scope="scope">
                  <span>积分</span>
                </template>
              </el-table-column>
              <el-table-column label="奖励数量">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.amount" :min="0" :max="9999" :step="1" :precision="0" :controls="false" style="width: 100%"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="概率" >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.probability" placeholder="例如: 20%"></el-input>
                </template>
              </el-table-column>
              <el-table-column  v-if="false" label="唯一序列号" >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.code" placeholder="奖励唯一序列号">
                    <el-button slot="append" icon="el-icon-refresh" @click="generateUUID(scope.row)"></el-button>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRewardItem(scope.$index)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="dataStatus">
          <el-radio-group v-model="form.dataStatus">
            <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </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>


    <el-dialog
      :title="`福袋详情`"
      :visible.sync="detailVisible"
      width="700px"
      append-to-body
    >
      <div class="reward-detail-container">
        <!-- 基础信息 -->
        <el-descriptions :column="2" border class="base-info" :label-style="{ width: '120px' }" :content-style="{ width: '200px' }">
          <el-descriptions-item label="福袋名称">{{ currentReward.name }}</el-descriptions-item>
          <el-descriptions-item label="福袋类型">
            <dict-tag :options="typeOptions" :value="currentReward.type"/>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <dict-tag :options="statusOptions" :value="currentReward.dataStatus"/>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 内容详情 -->
        <div class="reward-content">
          <h4>福袋内容详情</h4>
        </div>
        <div v-if="true" class="chest-reward">
          <el-table :data="actualRewards" size="small" border stripe>
            <el-table-column label="内容" prop="amount"  align="center">
              <template slot-scope="{row}">
                {{ row.name }}
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="amount"  align="center">
              <template slot-scope="{row}">
                {{ row.amount }}
              </template>
            </el-table-column>
            <el-table-column label="概率" prop="probability" align="center" v-if="currentReward.type=='2'">
              <template slot-scope="{row}">
                <el-tag v-if="row.probability" size="small">{{ row.probability }}</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script >
import {addReward, listReward,getReward,updateReward,delReward } from "@/api/qw/luckyBag";
export default {
  name: "luckyBag",
  data() {
    return {
      currentReward: {},
      detailVisible:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      open: false,
      title: '',
      form:{
        dataStatus: '1',
        status: '1'
      },
      width: '1200px',
      // 添加固定的奖励类型选项
      typeOptions: [
        { dictValue: '1', dictLabel: '定值' },
        { dictValue: '2', dictLabel: '随机' }
      ],
      statusOptions: [
        { dictValue: '1', dictLabel: '正常' },
        { dictValue: '0', dictLabel: '禁止' }
      ],
      actualRewards:[],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "奖励名称不能为空", trigger: "blur" }
        ],
      },
      // 总条数
      total: 0,
      rewardList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除奖励配置编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delReward(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getReward(id).then(response => {
        this.form = response.data[0];
        this.form.status = response.data[0].status.toString();
        this.form.type = response.data[0].type.toString();
        this.form.dataStatus = response.data[0].dataStatus.toString();

        try {
          const actualRewards = JSON.parse(response.data[0].actualRewards || "[]");
          this.form.rewardItems=actualRewards;
        } catch (e) {
          console.error("解析actualRewards失败", e);
          this.form.rewardItems = [];
          this.form.account = 0;
        }

        this.open = true;
        this.title = "修改奖励配置";
      });
    },
    // 解析奖励项数据
    parsedRewardItems() {
      if (this.currentReward.type == '1') {
        const newRewards = [
          {
            name: this.currentReward.name,
            amount: this.currentReward.amount
          }
        ];
        this.actualRewards=newRewards;
      }else{
        if (this.currentReward.actualRewards == null) {
          return null
        }
        try {
          const parsed = JSON.parse(this.currentReward.actualRewards);
          this.actualRewards = parsed;
        } catch (e) {
          console.error("解析奖励内容失败", e);
          this.actualRewards=null;
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    handleViewReward(row) {
      this.currentReward = { ...row };
      this.detailVisible = true;
      this.parsedRewardItems()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加福袋配置"
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        status: "1",
        dataStatus: '1',
        type: '1',
        rewardItems: []
      };
      this.resetForm("form");
    },
    // 查询
    getList() {
      this.loading = true;
      listReward(this.queryParams).then(response => {
        this.rewardList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 添加
    addRewardItem() {
      this.form.rewardItems.push({
        type: '1',
        name:'积分', // 默认使用表单中的奖励名称
        amount: 1,
        probability: '',
        code: this.generateUUID()
      });
    },
    // 移除奖励项
    removeRewardItem(index) {
      this.form.rewardItems.splice(index, 1);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let actualRewards = "";
          if (this.form.type === '2' ) {
            // 宝箱类型，将rewardItems转为JSON
            actualRewards = JSON.stringify(this.form.rewardItems);
          }

          // 设置actualRewards
          this.form.actualRewards = actualRewards;

          if (this.form.id != null) {
            updateReward(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReward(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },


    // 生成UUID
    generateUUID(item) {
      if (item) {
        item.code = this.generateUUIDString();
      } else {
        return this.generateUUIDString();
      }
    },
    // 生成UUID字符串
    generateUUIDString() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0,
          v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    },
  },
}
</script>
<style scoped>
.reward-table-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}
.reward-detail-container {
  max-height: 60vh;
  overflow-y: auto;
}
.base-info {
  margin-bottom: 20px;
  width: 100%;
  table-layout: fixed;
}
.reward-content {
  margin: 20px 0;
}
.chest-reward,
.redpacket-reward,
.points-reward {
  margin: 15px 0;
}
</style>
