<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="群活码" prop="liveCodeId">
        <el-select v-model="queryParams.liveCodeId" placeholder="请选择群活码" clearable size="small" @change="handleQuery">
          <el-option
            v-for="item in groupLiveCodeList"
            :key="item.id"
            :label="item.groupName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="群名称" prop="groupName">
        <el-input
          v-model="queryParams.groupName"
          placeholder="请输入群名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="启用" :value="1" />
          <el-option label="停用" :value="0" />
        </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>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="groupActualList" border>
      <el-table-column label="群名称" align="center" prop="groupName" />
      <el-table-column label="实际群二维码" align="center" prop="groupUrl">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.groupUrl"
            :src="scope.row.groupUrl"
            :preview-src-list="[scope.row.groupUrl]"
            style="width: 80px; height: 80px;"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="分配数" align="center" prop="assignNum" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <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"
            @click="handleStatusChange(scope.row)"
          >{{ scope.row.status === 1 ? '停用' : '启用' }}</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="500px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="群活码" prop="liveCodeId">
          <el-select v-model="form.liveCodeId" placeholder="请选择群活码">
            <el-option
              v-for="item in groupLiveCodeList"
              :key="item.id"
              :label="item.groupName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="群名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入群名称" />
        </el-form-item>
        <el-form-item label="群二维码" prop="groupUrl">
          <image-upload v-model="form.groupUrl" :limit="1" />
        </el-form-item>
        <el-form-item label="有效期" prop="efficientTime">
          <el-date-picker v-model="form.efficientTime" type="date" placeholder="请选择有效期" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="分配数" prop="assignNum">
          <el-input-number v-model="form.assignNum" :min="0" />
        </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 { listGroupActual, getGroupActual, addOrUpdateGroupActual, delGroupActual } from "@/api/qw/groupActual";
import { listGroupLiveCode } from "@/api/qw/groupLiveCode";
import ImageUpload from "@/components/ImageUpload";

export default {
  name: "GroupActual",
  components: {
    ImageUpload
  },
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      groupActualList: [],
      groupLiveCodeList: [],
      title: "",
      open: false,
      liveCodeId: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        liveCodeId: null,
        groupName: null,
        status: null,
      },
      form: {},
      rules: {
        groupName: [
          { required: true, message: "群名称不能为空", trigger: "blur" }
        ],
        groupUrl: [
          { required: true, message: "群二维码不能为空", trigger: "change" }
        ],
        liveCodeId: [
          { required: true, message: "群活码不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    // 从路由参数中获取liveCodeId
    this.liveCodeId = this.$route.query.liveCodeId;
    // 如果从群活码页面跳转过来，自动设置筛选条件
    if (this.liveCodeId) {
      this.queryParams.liveCodeId = this.liveCodeId;
    }
    this.loadGroupLiveCodeList();
    this.getList();
  },
  methods: {
    /** 查询群实际码列表 */
    getList() {
      this.loading = true;
      const params = { ...this.queryParams };
      if (this.liveCodeId) {
        params.liveCodeId = this.liveCodeId;
      }
      listGroupActual(params).then(response => {
        this.groupActualList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 新增按钮 */
    handleAdd() {
      this.reset();
      // 如果是从群活码页面跳转过来的，新增时自动带入liveCodeId
      if (this.liveCodeId) {
        this.form.liveCodeId = parseInt(this.liveCodeId);
      }
      this.loadGroupLiveCodeList();
      this.open = true;
      this.title = "新增群实际码";
    },

    /** 加载群活码列表 */
    loadGroupLiveCodeList() {
      listGroupLiveCode({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.groupLiveCodeList = response.data.records;
      }).catch(() => {
        this.groupLiveCodeList = [];
      });
    },

    // ... existing code ...
    handleUpdate(row) {
      this.reset();
      this.loadGroupLiveCodeList();
      this.open = true;
      this.title = "修改群实际码";
      getGroupActual(row.id).then(response => {
        this.form = response.data;
      });
    },

    /** 启用/停用 */
    handleStatusChange(row) {
      const status = row.status === 1 ? 0 : 1;
      const statusText = status === 1 ? "启用" : "停用";
      this.$confirm(`确认要${statusText}该群实际码吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const data = {
          id: row.id,
          status: status
        };
        addOrUpdateGroupActual(data).then(response => {
          this.msgSuccess(`${statusText}成功`);
          this.getList();
        });
      }).catch(() => {});
    },

    /** 表单提交 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const data = { ...this.form };
          // 有效期处理：剆除时間秘，添加默认时間秘 00:00:00
          if (data.efficientTime && typeof data.efficientTime === 'string') {
            data.efficientTime = data.efficientTime + 'T00:00:00';
          }
          addOrUpdateGroupActual(data).then(response => {
            this.msgSuccess(this.form.id ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },

    /** 取消 */
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 表单重置 */
    reset() {
      this.form = {
        id: null,
        liveCodeId: null,
        groupName: null,
        groupUrl: null,
        efficientTime: null,
        assignNum: 0,
        status: 1
      };
      this.resetForm("form");
    },

    /** 搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置 */
    resetQuery() {
      this.resetForm("queryForm");
      // 重置时，如果是从群活码页面跳转过来的，保留liveCodeId筛选
      if (this.liveCodeId) {
        this.queryParams.liveCodeId = this.liveCodeId;
      }
      this.handleQuery();
    }
  }
};
</script>
