<template>
  <view class="page-container">
    <view class="form-section">
      <uni-section title="环境模式" type="line" title-color="#666666" title-font-size="13px" padding="12px">
        <uni-forms>
          <uni-forms-item name="serverType">
            <uni-data-checkbox
              v-model="selectedEnv"
              :localdata="envOptions"
              @change="onEnvChange"
            ></uni-data-checkbox>
          </uni-forms-item>
        </uni-forms>
      </uni-section>
    </view>

    <view class="btn-area">
      <button
        class="btn btn-primary"
        :loading="isSubmitting"
        :disabled="!selectedEnv"
        @click="handleSubmit"
      >提交</button>
    </view>
  </view>
</template>

<script>
import { api } from '@/api'

export default {
  data() {
    return {
      selectedEnv: '',
      isSubmitting: false,
      envOptions: [
        { text: '测试环境', value: 'test' },
        { text: '生产环境', value: 'prod' }
      ]
    }
  },
  methods: {
    onEnvChange(e) {
      console.log('选中环境:', this.selectedEnv)
    },

    async handleSubmit() {
      if (!this.selectedEnv) {
        uni.showToast({ title: '请先选择环境', icon: 'none' })
        return
      }
      if (this.isSubmitting) return

      const confirmed = await new Promise((resolve) => {
        uni.showModal({
          title: '确认提交',
          content: `确定要切换到${this.selectedEnv === 'test' ? '测试' : '生产'}环境吗？`,
          success: (res) => resolve(res.confirm)
        })
      })
      if (!confirmed) return

      this.isSubmitting = true
      try {
        const res = await api.switchTest({ server_type: this.selectedEnv })
        uni.showToast({ title: '切换成功', icon: 'success' })
      } catch (error) {
        console.error('[环境切换] 失败:', error)
        uni.showToast({ title: '切换失败', icon: 'none' })
      } finally {
        this.isSubmitting = false
      }
    }
  }
}
</script>

