<template>
  <div class="app-container">
    <div
      class="background-color-fff padding-20 border-radius-8px margin-bottom-20"
    >
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="活动ID" prop="activityId">
          <el-input
            v-model="queryParams.activityId"
            placeholder="请输入活动ID"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="直播间ID" prop="roomId">
          <el-input
            v-model="queryParams.roomId"
            placeholder="请输入直播间ID"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="活动标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入活动标题"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            clearable
            v-model="queryParams.startTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择活动开始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            clearable
            v-model="queryParams.endTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择活动结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="创建账号" prop="creatorAccount">
          <el-input
            v-model="queryParams.creatorAccount"
            placeholder="请输入创建人账号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="重复参与" prop="isRepeat">
          <el-select
            v-model="queryParams.isRepeat"
            placeholder="请选择是否可重复参与"
            clearable
          >
            <el-option
              v-for="dict in sys_general_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div
      class="background-color-fff padding-20 border-radius-8px margin-bottom-20"
    >
      <el-row :gutter="10" class="mb8">
        <!-- <el-col :span="1.5">
                    <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['service:imLiveActivity:add']"
                    >
                        新增
                    </el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['service:imLiveActivity:edit']"
                    >
                        修改
                    </el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['service:imLiveActivity:remove']"
                    >
                        删除
                    </el-button>
                </el-col> -->
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['service:imLiveActivity:export']"
          >
            导出
          </el-button>
        </el-col>
        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
    </div>

    <div
      class="background-color-fff padding-20 border-radius-8px margin-bottom-20"
    >
      <el-table
        v-loading="loading"
        :data="imLiveActivityList"
        @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="活动ID" align="center" prop="activityId" />
        <el-table-column label="直播间ID" align="center" prop="roomId" />
        <el-table-column label="活动类型" align="center" prop="activityType">
          <template #default="{ row }">
            {{
              row.activityType == 1
                ? "签到"
                : row.activityType == 2
                  ? "抽奖"
                  : row.activityType == 3
                    ? "答题"
                    : "红包"
            }}
          </template>
        </el-table-column>
        <el-table-column label="活动标题" align="center" prop="title" />
        <!-- <el-table-column label="活动描述" align="center" prop="description" /> -->
        <!-- <el-table-column label="活动封面" align="center" prop="coverUrl" /> -->
        <el-table-column label="状态" align="center" prop="status">
          <template #default="{ row }">
            {{
              row.status == 1
                ? "进行中"
                : row.status == 2
                  ? "已结束"
                  : row.status == 3
                    ? "已取消"
                    : "未开始"
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="活动开始时间"
          align="center"
          prop="startTime"
          width="180"
        >
          <template #default="scope">
            <span>{{
              parseTime(scope.row.startTime, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="活动结束时间"
          align="center"
          prop="endTime"
          width="180"
        >
          <template #default="scope">
            <span>{{
              parseTime(scope.row.endTime, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="活动持续时长" align="center" prop="duration" /> -->
        <el-table-column label="创建人用户id" align="center" prop="userId" />
        <el-table-column label="创建人类型" align="center" prop="creatorType">
          <template #default="{ row }">
            {{
              row.creatorType == 1
                ? "主播"
                : row.creatorType == 2
                  ? "管理员"
                  : "系统"
            }}
          </template>
        </el-table-column>
        <el-table-column label="是否可重复参与" align="center" prop="isRepeat">
          <template #default="scope">
            <dict-tag
              :options="sys_general_yes_no"
              :value="scope.row.isRepeat"
            />
          </template>
        </el-table-column>
        <!-- <el-table-column label="重复间隔" align="center" prop="repeatInterval" /> -->
        <el-table-column
          label="最大参与人数"
          align="center"
          prop="maxParticipants"
        />
        <el-table-column
          label="当前参与人数"
          align="center"
          prop="participantCount"
        />
        <el-table-column label="奖励类型" align="center" prop="rewardType">
          <template #default="{ row }">
            {{
              row.rewardType == 1
                ? "积分"
                : row.rewardType == 2
                  ? "虚拟币"
                  : row.rewardType == 3
                    ? "实物"
                    : row.rewardType == 4
                      ? "勋章"
                      : "特权"
            }}
          </template>
        </el-table-column>
        <el-table-column label="奖励值" align="center" prop="rewardValue" />
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column label="版本号" align="center" prop="version" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          fixed="right"
          width="150"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['service:imLiveActivity:edit']"
            >
              查看
            </el-button>
            <el-button
              link
              type="warning"
              icon="Edit"
              v-if="scope.row.status === 1"
              @click="handleEndActivity(scope.row)"
              v-hasPermi="['service:imLiveActivity:edit']"
            >
              结束活动
            </el-button>
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="showRecordModal(scope.row)"
              v-hasPermi="['service:imLiveActivity:edit']"
            >
              参与记录
            </el-button>
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['service:imLiveActivity:remove']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 添加或修改直播间活动对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="imLiveActivityRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        label-position="top"
      >
        <el-form-item label="活动ID" prop="activityId">
          <el-input
            v-model="form.activityId"
            disabled
            placeholder="请输入活动ID"
          />
        </el-form-item>
        <el-form-item label="直播间ID" prop="roomId">
          <el-input
            v-model="form.roomId"
            disabled
            placeholder="请输入直播间ID"
          />
        </el-form-item>
        <el-form-item label="活动标题" prop="title">
          <el-input
            v-model="form.title"
            disabled
            placeholder="请输入活动标题"
          />
        </el-form-item>
        <!-- <el-form-item label="活动描述" prop="description">
                    <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
                </el-form-item> -->
        <!-- <el-form-item label="活动封面" prop="coverUrl">
                    <el-input v-model="form.coverUrl" type="textarea" placeholder="请输入内容" />
                </el-form-item> -->
        <el-form-item label="活动开始时间" prop="startTime">
          <el-date-picker
            clearable
            v-model="form.startTime"
            disabled
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择活动开始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="活动结束时间" prop="endTime">
          <el-date-picker
            clearable
            v-model="form.endTime"
            disabled
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择活动结束时间"
          ></el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="活动持续时长" prop="duration">
                    <el-input v-model="form.duration" placeholder="请输入活动持续时长" />
                </el-form-item> -->
        <el-form-item label="创建人用户id" prop="userId">
          <el-input
            v-model="form.userId"
            disabled
            placeholder="请输入创建人账号"
          />
        </el-form-item>
        <el-form-item label="创建人类型" prop="creatorType">
          <el-select
            v-model="form.creatorType"
            disabled
            placeholder="创建人类型"
          >
            <el-option label="主播" :value="1"></el-option>
            <el-option label="管理员" :value="2"></el-option>
            <el-option label="系统" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="是否可重复参与" prop="isRepeat">
                    <el-select
                        v-model="form.isRepeat"
                        placeholder="请选择是否可重复参与：0-否 1-是"
                    >
                        <el-option
                            v-for="dict in sys_general_yes_no"
                            :key="dict.value"
                            :label="dict.label"
                            :value="parseInt(dict.value)"
                        ></el-option>
                    </el-select>
                </el-form-item> -->
        <!-- <el-form-item label="重复间隔" prop="repeatInterval">
                    <el-input v-model="form.repeatInterval" placeholder="请输入重复间隔" />
                </el-form-item> -->
        <el-form-item label="最大参与人数" prop="maxParticipants">
          <el-input
            v-model="form.maxParticipants"
            disabled
            placeholder="请输入最大参与人数"
          />
        </el-form-item>
        <!-- <el-form-item label="当前参与人数" prop="participantCount">
                    <el-input v-model="form.participantCount" placeholder="请输入当前参与人数" />
                </el-form-item> -->
        <el-form-item label="奖励积分" prop="rewardValue">
          <el-input
            v-model="form.rewardValue"
            disabled
            placeholder="请输入内容"
          />
        </el-form-item>
        <!-- <el-form-item label="奖励类型" prop="rewardType">
                    <el-select v-model="form.rewardType" placeholder="创建人类型">
                        <el-option label="积分" :value="1"></el-option>
                    </el-select>
                </el-form-item> -->
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" disabled placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 引入弹窗组件 -->
    <ImLiveActivityRecordModal
      ref="recordModalRef"
      :activity-id="currentActivityId"
      @close="handleRecordModalClose"
    />
  </div>
</template>

<script setup name="ImLiveActivity">
import {
  listImLiveActivity,
  getImLiveActivity,
  delImLiveActivity,
  addImLiveActivity,
  updateImLiveActivity,
  endImLiveActivity,
} from "@/api/service/imLiveActivity";
import ImLiveActivityRecordModal from "@/components/ImLive/ImLiveActivityRecordModal.vue";

const { proxy } = getCurrentInstance();
const { sys_general_yes_no } = proxy.useDict("sys_general_yes_no");

const imLiveActivityList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const recordModalRef = ref();
const currentActivityId = ref(null); // 当前活动ID，可以从接口获取

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    activityId: null,
    roomId: null,
    activityType: null,
    title: null,
    description: null,
    coverUrl: null,
    status: null,
    startTime: null,
    endTime: null,
    duration: null,
    creatorAccount: null,
    creatorType: null,
    isRepeat: null,
    repeatInterval: null,
    maxParticipants: null,
    participantCount: null,
    rewardType: null,
    rewardValue: null,
    sort: null,
    version: null,
  },
  rules: {
    roomId: [{ required: true, message: "直播间ID不能为空", trigger: "blur" }],
    activityType: [
      {
        required: true,
        message:
          "活动类型：1-签到 2-抽奖 3-答题 4-红包 5-任务 6-投票 7-连麦PK不能为空",
        trigger: "change",
      },
    ],
    title: [{ required: true, message: "活动标题不能为空", trigger: "blur" }],
    status: [
      {
        required: true,
        message: "状态：0-未开始 1-进行中 2-已结束 3-已取消不能为空",
        trigger: "change",
      },
    ],
    startTime: [
      { required: true, message: "活动开始时间不能为空", trigger: "blur" },
    ],
    endTime: [
      { required: true, message: "活动结束时间不能为空", trigger: "blur" },
    ],
    userId: [
      { required: true, message: "创建人账号不能为空", trigger: "blur" },
    ],
    rewardValue: [
      { required: true, message: "奖励积分不能为空", trigger: "blur" },
    ],
    creatorType: [
      {
        required: true,
        message: "创建人类型：1-主播 2-管理员 3-系统不能为空",
        trigger: "change",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询直播间活动列表 */
function getList() {
  loading.value = true;
  listImLiveActivity(queryParams.value).then((response) => {
    imLiveActivityList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    activityId: null,
    roomId: null,
    activityType: null,
    title: null,
    description: null,
    coverUrl: null,
    status: null,
    startTime: null,
    endTime: null,
    duration: null,
    creatorAccount: null,
    creatorType: null,
    isRepeat: null,
    repeatInterval: null,
    maxParticipants: null,
    participantCount: null,
    rewardType: null,
    rewardValue: null,
    sort: null,
    version: null,
    createTime: null,
    updateTime: null,
  };
  proxy.resetForm("imLiveActivityRef");
}

// 显示记录弹窗
function showRecordModal(item) {
  currentActivityId.value = item.activityId;
  if (recordModalRef.value) {
    console.log(recordModalRef.value);
    recordModalRef.value.openModal(item.activityId);
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

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

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加直播间活动";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getImLiveActivity(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改直播间活动";
  });
}

function handleEndActivity(row) {
  console.log(row);

  const _id = row.activityId || ids.value;
  proxy.$modal
    .confirm('是否确认结束直播间活动编号为"' + _id + '"的数据项？')
    .then(function () {
      return endImLiveActivity(_id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("活动已结束");
    })
    .catch(() => {});
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["imLiveActivityRef"].validate((valid) => {
    if (valid) {
      form.isRepeat = 0;
      if (form.value.id != null) {
        updateImLiveActivity(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addImLiveActivity(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除直播间活动编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delImLiveActivity(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "service/imLiveActivity/export",
    {
      ...queryParams.value,
    },
    `imLiveActivity_${new Date().getTime()}.xlsx`,
  );
}

getList();
</script>
