<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="群名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入群名称" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="群类型" prop="groupType">
        <el-select v-model="queryParams.groupType" placeholder="请选择群类型" clearable style="width: 240px">
          <el-option
            v-for="item in groupTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="isActive">
        <el-select v-model="queryParams.isActive" placeholder="请选择状态" clearable style="width: 240px">
          <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>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</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>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="xbgroupList" @selection-change="handleSelectionChange" highlight-current-row>
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="群名称" align="left" prop="name" :show-overflow-tooltip="true" min-width="200">
        <template slot-scope="scope">
          <span>{{ decodeUnicode(scope.row.name) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="微信ID" align="center" prop="wxid" width="240" />
      <el-table-column label="群类型" align="center" prop="groupTypeName" width="120">

      </el-table-column>
      <el-table-column label="状态" align="center" prop="isActive" width="100">
        <template slot-scope="scope">
                     <el-switch
             v-model="scope.row.isActive"
             :active-value="1"
             :inactive-value="0"
             @change="handleStatusChange(scope.row)"
             v-hasPermi="['system:xbgroup:edit']"
           ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createDate" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.createDate ? parseTime(scope.row.createDate) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateDate" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.updateDate ? parseTime(scope.row.updateDate) : '-' }}</span>
        </template>
      </el-table-column>
      <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-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:xbgroup:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:xbgroup:remove']">删除</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="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="群名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入群名称" />
        </el-form-item>
        <el-form-item label="微信ID" prop="wxid">
          <el-input v-model="form.wxid" placeholder="请输入微信ID" />
        </el-form-item>
        <el-form-item label="群类型" prop="groupType">
          <el-select v-model="form.groupType" placeholder="请选择群类型" style="width: 100%">
            <el-option
              v-for="item in groupTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-select v-model="form.isActive" placeholder="请选择状态" style="width: 100%">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </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 { listXbgroup, getXbgroup, delXbgroup, addXbgroup, updateXbgroup, getGroupTypeOptions } from "@/api/system/xbgroup";

export default {
  name: "Xbgroup",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 线报群表格数据
      xbgroupList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        groupType: null,
        isActive: null
      },
      // 表单参数
      form: {},
      // 群类型选项
      groupTypeOptions: [],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "群名称不能为空", trigger: "blur" }
        ],
        groupType: [
          { required: true, message: "群类型不能为空", trigger: "change" }
        ],
        wxid: [
          { required: true, message: "微信ID不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询线报群列表 */
    getList() {
      this.loading = true;
      listXbgroup(this.queryParams).then(response => {
        this.xbgroupList = response.rows;
        this.total = response.total;
        this.loading = false;
        // 列表加载成功后，再获取群类型选项
        this.getGroupTypeOptions();
      }).catch(error => {
        console.error('获取列表失败:', error);
        this.loading = false;
      });
    },
    /** 获取群类型选项 */
    getGroupTypeOptions() {
      getGroupTypeOptions().then(response => {
        this.groupTypeOptions = response.data || [];
      }).catch(error => {
        console.error('获取群类型选项失败:', error);
        this.groupTypeOptions = [];
      });
    },
    /** 解码Unicode字符 */
    decodeUnicode(str) {
      if (!str || typeof str !== 'string') return str;
      try {
        return str.replace(/\\u([0-9a-fA-F]{4})/g, (match, hex) => {
          return String.fromCharCode(parseInt(hex, 16));
        });
      } catch (e) {
        return str;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        wxid: null,
        groupType: null,
        isActive: 1
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      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 groupId = row.id || this.ids[0];
      
      if (!groupId) {
        this.$modal.msgError("无法获取群组ID");
        return;
      }
      
      getXbgroup(groupId).then(response => {
        // 确保数据类型正确
        this.form = {
          ...response.data,
          isActive: parseInt(response.data.isActive) || 1
        };
        this.open = true;
        this.title = "修改线报群";
      }).catch(error => {
        console.error("获取群组详情失败:", error);
        this.$modal.msgError("获取群组详情失败");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateXbgroup(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addXbgroup(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const groupIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除线报群编号为"' + groupIds + '"的数据项？').then(function() {
        return delXbgroup(groupIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.isActive === 1 ? "启用" : "禁用";
      this.$modal.confirm('确认要"' + text + '""' + row.name + '"线报群吗？').then(() => {
        return updateXbgroup(row);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        // 状态修改成功后刷新列表
        this.getList();
      }).catch(() => {
        // 失败时回滚状态
        row.isActive = row.isActive === 1 ? 0 : 1;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/xbgroup/export', {
        ...this.queryParams
      }, `xbgroup_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>
