<template>
  <view class="container">
    <view class="switch-container">
      <text>铃声状态：</text>
      <u-switch 
        v-model="isSwitchOn" 
        @change="handleSwitchChange"
        size="20"
      ></u-switch>
      <text>{{ isSwitchOn ? '打开' : '关闭' }}</text>
    </view>
  </view>
</template>

<script>
import { GetRingStatus, UpdateRingStatus } from '../../../api/ring.js'

export default {
  data() {
    return {
      ringtoneIsEnable: null, 
      isSwitchOn: false, 
      form: {} 
    }
  },
  onLoad() {
    this.getRingtoneStatus();
  },
  methods: {
    async getRingtoneStatus() {
      try {
        let res = await GetRingStatus();
        this.ringtoneIsEnable = res.data.ringtone_is_enable;
        this.isSwitchOn = res.data.ringtone_is_enable === 1;
        this.form = res.data; 
      } catch (error) {
        uni.showToast({
          title: '获取状态失败',
          icon: 'none',
          duration: 2000
        });
      }
    },
    
    async handleSwitchChange(value) {
      try {
        const status = value ? 1 : 2;
        this.form.ringtone_is_enable = status;
        
        const formData = new URLSearchParams();
        for (const key in this.form) {
          if (this.form.hasOwnProperty(key)) {
            formData.append(key, this.form[key]);
          }
        }
        let res = await UpdateRingStatus(formData); 
        this.ringtoneIsEnable = status;
        this.isSwitchOn = value;
        
        uni.showToast({
          title: `铃声已${value ? '开启' : '关闭'}`,
          icon: 'success',
          duration: 1500
        });
      } catch (error) {
        this.isSwitchOn = !value;
        uni.showToast({
          title: '更新失败，请重试',
          icon: 'none',
          duration: 2000
        });
      }
    }
  }
}
</script>

<style>
.container {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.switch-container {
  display: flex;
  align-items: center;
  margin-top: 30rpx;
  gap: 15rpx;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
}

.switch-container text {
  font-size: 32rpx;
  color: #333;
}

.loading-text {
  margin-top: 30rpx;
  font-size: 30rpx;
  color: #666;
  padding: 20rpx;
}
</style>
