Bootstrap

点击锁定按钮,锁定按钮要变成解锁按钮,然后状态要从待绑定变成 已锁定

  • 点击锁定按钮,锁定按钮要变成解锁按钮,然后状态要从待绑定变成
    已锁定
  • 点击解锁按钮,解锁按钮要变成锁定按钮,然后状态要从已锁定变成
    待绑定
{
    "code": 0,
    "msg": "状态更新成功",
    "data": {
        "status": 3
    }
}

1、状态列的 el-table-column

<el-table-column
  prop="status"
  label="状态"
  header-align="center"
  align="center"
>
  <template slot-scope="scope">
      <el-tag
      :type="getStatusType(scope.row.status)"
       size="mini"
      >
        {{ getStatusText(scope.row.status) }}
      </el-tag>
 </template>
 </el-table-column>

2、操作列的 el-table-column

<el-table-column
  label="操作"
  header-align="center"
  align="center"
>
  <template slot-scope="scope">
    <div class="operation-cell">
      <el-button
        type="text"
        size="mini"
        class="operation-btn"
        @click="handleLock(scope.row)"
      >
        {{ scope.row.isLocked === 0 ? '锁定' : '解锁' }}
      </el-button>
      <el-button
        type="text"
        size="mini"
        class="operation-btn"
        @click="handleRemark(scope.row)"
      >
        备注
      </el-button>
      <el-button
        type="text"
        size="mini"
        class="operation-btn"
        @click="handleLog(scope.row)"
      >
        日志
      </el-button>
    </div>
  </template>
</el-table-column>

3、invite-code-status.ts

// invite-code-status.ts
export class InviteCodeStatus {
    static readonly EFFECTIVE = { value: 0, name: "effective" };
    static readonly EXPIRED = { value: 1, name: "expired" };
    static readonly BOUND = { value: 2, name: "bound" };
    static readonly LOCKED = { value: 3, name: "locked" };

    static fromValue(value: number): { value: number, name: string } {
        switch (value) {
            case 0:
                return InviteCodeStatus.EFFECTIVE;
            case 1:
                return InviteCodeStatus.EXPIRED;
            case 2:
                return InviteCodeStatus.BOUND;
            case 3:
                return InviteCodeStatus.LOCKED;
            default:
                throw new Error(`No enum constant with value ${value}`);
        }
    }
      static fromName(name: string): { value: number, name: string } {
        switch (name) {
            case "effective":
                return InviteCodeStatus.EFFECTIVE;
            case "expired":
                return InviteCodeStatus.EXPIRED;
            case "bound":
                return InviteCodeStatus.BOUND;
             case "locked":
                return InviteCodeStatus.LOCKED;
            default:
                throw new Error(`No enum constant with value ${name}`);
        }
    }
}

4、updateInviteCodeStatus

import request from '@/utils/request';

// 更新邀请码状态接口
export const updateInviteCodeStatus = (data: {
  inviteCodeId: number;
  statusName: string;
}) =>
  request({
      url: '/api/invite-codes/updateStatus',
      method: 'put',
      params: data,
  });

3、handleLock

  private async handleLock(row: any) {
    const newIsLocked = row.isLocked === 0 ? 1 : 0;
    const newStatus = newIsLocked === 0
        ? InviteCodeStatus.EFFECTIVE.name
        : InviteCodeStatus.LOCKED.name;

    this.$confirm(
        `确定要${row.isLocked === 0 ? '锁定' : '解锁'}该邀请码吗?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )
    .then(async () => {
        try {
            console.log('请求参数:', {
                inviteCodeId: row.id,
                statusName: newStatus
            });

            // 调用后端的更新状态接口
            const response = await updateInviteCodeStatus({
                inviteCodeId: row.id,
                statusName: newStatus
            });

            console.log('response.data:', response.data);
            console.log('typeof response.data', typeof response.data);

            if (response &&  response.data && typeof response.data === 'object' && 'status' in response.data) {
                const status = response.data.status;

                // 调试步骤 1:打印状态值
                console.log('状态值:', status);

                // 调试步骤 2:检查状态映射
                let statusObj;
                try {
                    statusObj = InviteCodeStatus.fromValue(status);
                    console.log('映射后的状态:', statusObj);
                } catch (e) {
                    console.error('状态映射错误:', e);
                    this.$message.error('状态映射错误,请联系管理员');
                    return;
                }

                // 更新本地数据
                const index = this.tableData.findIndex(item => item.id === row.id);
                if (index !== -1) {
                    this.$set(this.tableData, index, {
                        ...this.tableData[index],
                        isLocked: newIsLocked,
                        status: status // 使用后端返回的 status 值
                    });
                    console.log('更新后的行数据:', this.tableData[index]);
                }

                this.$message.success(`${newIsLocked === 0 ? '解锁' : '锁定'}成功`);

                // 选择性地重新拉取数据,根据实际需求
                // await this.fetchInviteCodeList();
            } else {
                this.$message.error(' ');
            }
        } catch (error) {
            console.error('更新邀请码状态失败:', error);
            console.error('错误详情:', error.response || error.message);
            this.$message.error('更新邀请码状态失败:未知错误');
        }
    })
    .catch(() => { });
}

3、invite-code-list.vue

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import { ElMessageBox } from 'element-ui/types/message-box'
import InviteCodeAdd from './invite-code-add.vue'
import { AppModule } from '@/store/modules/app'
import { getInviteCodeList } from '@/api/invite-code'
import { getInviteCodeListByInvitor , updateInviteCodeStatus} from '@/api/invite-code'
import { UserModule } from '@/store/modules/user'
import { InviteCodeStatus } from '@/utils/productAuthentication/InviteCodeStatus'

type MessageBoxData = {
  value: string
  action: 'confirm' | 'cancel'
}

@Component({
  name: 'InviteCodeForm',
  components: {
    InviteCodeAdd
  }
})
export default class extends Vue {
  get tableHeight() {
    return Math.floor(AppModule.tableHeight * 2 / 3)
  }

  @Prop({ default: false })
  private visible!: boolean

  private tableData = []
  private currentPage = 1
  private pageSize = 100
  private total = 0

  private addVisible = false

  // private getStatusType(status: string) {
  //   const map: { [key: string]: string } = {
  //     effective: 'primary',
  //     expired: 'info',
  //     locked: 'danger',
  //     bound: 'success'
  //   }
  //   return map[status] || 'info'
  // }
    // 获取状态文字
  private getStatusText(status: number): string {
      try {
          const inviteCodeStatus = InviteCodeStatus.fromValue(status);
          const map: { [key: string]: string } = {
              effective: '待绑定',
              expired: '已失效',
              locked: '已锁定',
              bound: '已绑定'
          };
          return map[inviteCodeStatus.name] || inviteCodeStatus.name
      } catch (e) {
          console.error(`状态值${status}不存在`)
          return String(status)
      }

  }

  // private getStatusText(status: string) {
  //   const map: { [key: string]: string } = {
  //     effective: '待绑定',
  //     expired: '已失效',
  //     locked: '已锁定',
  //     bound: '已绑定'
  //   }
  //   return map[status] || status
  // }

    // 获取状态类型
  private getStatusType(status: number): string {
       try {
           const inviteCodeStatus = InviteCodeStatus.fromValue(status);
           const map: { [key: string]: string } = {
               effective: 'primary',
               expired: 'info',
               locked: 'danger',
               bound: 'success'
           };
           return map[inviteCodeStatus.name] || 'info'
       } catch (e) {
           console.error(`状态值${status}不存在`)
           return 'info';
       }
  }

  private formatDate(dateString: string): { date: string; time: string } {
    if (!dateString) {
      return { date: '', time: '' }
    }
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return {
      date: `${year}-${month}-${day}`,
      time: `${hours}:${minutes}:${seconds}`
    }
  }
  private handleClose() {
    this.$emit('update:visible', false)
  }

  private handleAdd() {
    this.addVisible = true
  }

  private async handleAddSuccess() {
    // TODO: 刷新列表数据
    this.addVisible = false
    await this.fetchInviteCodeList()
  }
  private async handleLock(row: any) {
    const newIsLocked = row.isLocked === 0 ? 1 : 0;
    const newStatus = newIsLocked === 0
        ? InviteCodeStatus.EFFECTIVE.name
        : InviteCodeStatus.LOCKED.name;

    this.$confirm(
        `确定要${row.isLocked === 0 ? '锁定' : '解锁'}该邀请码吗?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )
    .then(async () => {
        try {
            console.log('请求参数:', {
                inviteCodeId: row.id,
                statusName: newStatus
            });

            // 调用后端的更新状态接口
            const response = await updateInviteCodeStatus({
                inviteCodeId: row.id,
                statusName: newStatus
            });

            console.log('response.data:', response.data);
            console.log('typeof response.data', typeof response.data);

            if (response &&  response.data && typeof response.data === 'object' && 'status' in response.data) {
                const status = response.data.status;

                // 调试步骤 1:打印状态值
                console.log('状态值:', status);

                // 调试步骤 2:检查状态映射
                let statusObj;
                try {
                    statusObj = InviteCodeStatus.fromValue(status);
                    console.log('映射后的状态:', statusObj);
                } catch (e) {
                    console.error('状态映射错误:', e);
                    this.$message.error('状态映射错误,请联系管理员');
                    return;
                }

                // 更新本地数据
                const index = this.tableData.findIndex(item => item.id === row.id);
                if (index !== -1) {
                    this.$set(this.tableData, index, {
                        ...this.tableData[index],
                        isLocked: newIsLocked,
                        status: status // 使用后端返回的 status 值
                    });
                    console.log('更新后的行数据:', this.tableData[index]);
                }

                this.$message.success(`${newIsLocked === 0 ? '解锁' : '锁定'}成功`);

                // 选择性地重新拉取数据,根据实际需求
                // await this.fetchInviteCodeList();
            } else {
                this.$message.error(' ');
            }
        } catch (error) {
            console.error('更新邀请码状态失败:', error);
            console.error('错误详情:', error.response || error.message);
            this.$message.error('更新邀请码状态失败:未知错误');
        }
    })
    .catch(() => { });
}

  private handleRemark(row: any) {
    this.$prompt('请输入备注', '备注', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: row.remark,
      inputValidator: (value: string) => {
        return value.length <= 60
      },
      inputErrorMessage: '备注不能超过60个字符'
    })
      .then(async(data: MessageBoxData) => {
        // TODO: 调用保存备注API
        row.remark = data.value
        this.$message.success('备注保存成功')
      })
      .catch(() => { })
  }

  private handleLog(row: any) {
    // TODO: 显示日志记录
    // 可以打开一个新的对话框显示操作日志列表
  }

  private handleCurrentChange(page: number) {
    this.currentPage = page
    // TODO: Add your fetch data logic here
  }

  async mounted() {
    await this.fetchInviteCodeList()
  }

  // private async fetchInviteCodeList() {
  //   try {
  //     const response = await getInviteCodeList({
  //       page: this.currentPage,
  //       pageSize: this.pageSize
  //     })
  //     console.log(response)
  //     if (response && response.data && response.data.list) {
  //       this.tableData = response.data.list
  //       this.total = response.data.total
  //     } else {
  //       this.$message.error('获取邀请码列表失败: 返回数据结构不符合预期')
  //       console.error('getInviteCodeList response data error', response)
  //     }

  //   } catch (error) {
  //     console.error('获取邀请码列表时发生错误', error)
  //     this.$message.error('获取邀请码列表时发生错误')
  //   }
  // }

  private async fetchInviteCodeList() {
    try {
      const response = await getInviteCodeListByInvitor({
        invitorId: UserModule.id,
        page: this.currentPage,
        pageSize: this.pageSize
      })
      console.log(response)
      if (response && response.data && response.data.list) {
        this.tableData = response.data.list
        this.total = response.data.total
      } else {
        this.$message.error('获取邀请码列表失败: 返回数据结构不符合预期')
        console.error('getInviteCodeList response data error', response)
      }

    } catch (error) {
      console.error('获取邀请码列表时发生错误', error)
      this.$message.error('获取邀请码列表时发生错误')
    }
  }

  private copyInviteCode(inviteCode: string) {
    const input = document.createElement('input')
    input.value = inviteCode
    document.body.appendChild(input)
    input.select()
    document.execCommand('copy')
    document.body.removeChild(input)
    this.$message.success('邀请码已复制到剪贴板')
  }
}
</script>

在这里插入图片描述
在这里插入图片描述

;