<template>
  <wd-popup v-model="popupVisible" position="bottom" close-on-click-modal @close="handleClose">
    <view class="bg-white rounded-t-lg p-4">
      <view class="flex justify-between items-center mb-4">
        <text class="text-gray-400" @click="cancel">取消</text>
        <text class="text-lg font-medium">申请成为代理</text>
        <text class="text-gray-400" @click="cancel">关闭</text>
      </view>

      <wd-form :model="form" :rules="rules">
        <wd-cell-group border>
          <!-- 区域选择 -->
          <wd-col-picker v-model="region" label="代理区域" label-width="100px" prop="region" placeholder="请选择代理区域"
            :columns="columns" :column-change="handleColumnChange" @confirm="handleRegionConfirm"
            :display-format="displayFormat" />
          <!-- 手机号 -->
          <wd-input label="手机号码" label-width="100px" type="number" v-model="form.mobile" prop="mobile"
            placeholder="请输入您的手机号" :rules="[
              { required: true, message: '请输入手机号' },
              { required: true, pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
            ]" />

          <!-- 验证码 -->
          <wd-input label="验证码" label-width="100px" type="number" v-model="form.code" prop="code" placeholder="请输入验证码"
            :rules="[{ required: true, message: '请输入验证码' }]" use-suffix-slot>
            <template #suffix>
              <button class="verify-btn" :disabled="countdown > 0" @click.stop="sendVerifyCode">
                {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
              </button>
            </template>
          </wd-input>

          <!-- 微信号 -->
          <wd-input label="微信号" label-width="100px" v-model="form.wechat_id" prop="wechat_id" placeholder="请输入您的微信号"
            :rules="[{ required: true, message: '请输入微信号' }]" />
        </wd-cell-group>

        <!-- 同意条款的复选框 -->
        <view class="p-4">
          <view class="flex items-start">
            <wd-checkbox v-model="isAgreed" size="16px" class="flex-shrink-0 mr-2"></wd-checkbox>
            <view class="text-xs text-gray-400 leading-tight">
              我已阅读并同意
              <text class="text-blue-400" @click.stop="toUserAgreement">《用户协议》</text>
              <text class="text-blue-400" @click.stop="toServiceAgreement">《信息技术服务合同》</text>
              <text class="text-blue-400" @click.stop="toAgentManageAgreement">《推广方管理制度协议》</text>
              <view class="text-xs text-gray-400 mt-1">点击勾选即代表您同意上述法律文书的相关条款并签署上述法律文书</view>
              <view class="text-xs text-gray-400 mt-1">手机号未在本平台注册账号则申请后将自动生成账号</view>
            </view>
          </view>
        </view>

        <view class="p-4">
          <wd-button type="primary" block @click="submitForm">提交申请</wd-button>
          <wd-button type="default" block class="mt-2" @click="cancel">取消</wd-button>
        </view>
      </wd-form>
    </view>
  </wd-popup>
  <wd-toast />

</template>

<script setup>
import { ref, computed, watch, onUnmounted } from 'vue'
import { useColPickerData } from '../hooks/useColPickerData'
import { useToast } from 'wot-design-uni'
import { getCode } from '@/api/apis.js' // 导入getCode API

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  ancestor: {
    type: String,
    default: ''
  }
})
const region = ref([]) // 存储地区代码数组
const regionText = ref('') // 存储地区文本
const isAgreed = ref(false) // 用户是否同意协议

// 格式化显示文本
const displayFormat = (selectedItems) => {
  if (selectedItems.length === 0) return ''
  return selectedItems.map(item => item.label).join(' ')
}

const emit = defineEmits(['update:show', 'submit', 'close'])
const form = ref({
  mobile: '',
  code: '',
  wechat_id: ''
})

// 使用wot-design-ui的toast组件
const toast = useToast()

// 不再需要监听region变化触发表单验证
// watch(region, (newVal) => {
//   // 当region变化时，触发表单验证
//   if (formRef.value) {
//     formRef.value.validate(['region'])
//   }
// })

const popupVisible = ref(false)
const countdown = ref(0)
let timer = null

// 初始化省市区数据
const { colPickerData, findChildrenByCode } = useColPickerData()
const columns = ref([
  colPickerData.map((item) => {
    return {
      value: item.value,
      label: item.text
    }
  })
])

// 表单验证规则 - 仍然保留以供wd-form组件使用
const rules = {
  region: [{
    required: true,
    message: '请选择代理区域',
    validator: (value) => {
      // 这里直接检查region.value而不是传入的value
      if (Array.isArray(region.value) && region.value.length === 3) {
        return Promise.resolve()
      }
      return Promise.reject('请选择完整的省市区')
    }
  }],
  mobile: [
    { required: true, message: '请输入手机号' },
    { required: true, pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
  ],
  code: [{ required: true, message: '请输入验证码' }],
  wechat_id: [{ required: true, message: '请输入微信号' }]
}

// 协议跳转函数
const toUserAgreement = () => {
  uni.navigateTo({
    url: '/pages/agreement?type=user'
  })
}

const toServiceAgreement = () => {
  uni.navigateTo({
    url: '/pages/agreement?type=service'
  })
}

const toAgentManageAgreement = () => {
  uni.navigateTo({
    url: '/pages/agreement?type=manage'
  })
}

// 监听show属性变化
watch(() => props.show, (newVal) => {
  popupVisible.value = newVal
})

// 监听popupVisible同步回props.show
watch(() => popupVisible.value, (newVal) => {
  emit('update:show', newVal)
})

// Popup关闭事件
const handleClose = () => {
  emit('close')
}

// 取消按钮
const cancel = () => {
  popupVisible.value = false
  emit('close')
}

// 处理列变化
const handleColumnChange = ({ selectedItem, resolve, finish }) => {
  const children = findChildrenByCode(colPickerData, selectedItem.value)
  if (children && children.length) {
    resolve(children.map(item => ({
      label: item.text,
      value: item.value
    })))
  } else {
    finish()
  }
}

// 区域选择确认 - 获取选中项的文本值
const handleRegionConfirm = ({ value, selectedItems }) => {
  // 存储地区文本
  regionText.value = selectedItems.map(item => item.label).join('-')
  console.log('地区选择完成', regionText.value)
}

// 判断手机号是否有效
const isPhoneNumberValid = computed(() => {
  return /^1[3-9]\d{9}$/.test(form.value.mobile)
})

// 发送验证码
const sendVerifyCode = async () => {
  // 验证手机号
  if (!form.value.mobile) {
    toast.info('请输入手机号')
    return
  }
  if (!isPhoneNumberValid.value) {
    toast.info('手机号格式不正确')
    return
  }

  // 发送验证码请求
  getCode({
    mobile: form.value.mobile,
    actionType: 'agentApply',
  }).then((res) => {
    if (res.code === 200) {
      toast.success('验证码已发送')
      // 开始倒计时
      startCountdown()
    } else {
      toast.error(res.msg || '发送失败')
    }
  }).catch((err) => {
    toast.error('网络错误')
  })
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  if (timer) clearInterval(timer)

  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      timer = null
    }
  }, 1000)
}

// 组件卸载时清除计时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
})

// 提交表单 - 不再使用formRef验证
const submitForm = () => {
  try {
    // 检查区域是否已选择
    if (!Array.isArray(region.value) || region.value.length < 3) {
      console.log('区域选择不完整:', region.value)
      toast.info('请选择完整的代理区域')
      return
    }

    if (!regionText.value) {
      toast.info('请选择代理区域')
      return
    }

    // 检查手机号
    if (!form.value.mobile) {
      console.log('手机号为空')
      toast.info('请输入手机号')
      return
    }

    if (!isPhoneNumberValid.value) {
      console.log('手机号格式不正确:', form.value.mobile)
      toast.info('手机号格式不正确')
      return
    }

    // 检查验证码
    if (!form.value.code) {
      console.log('验证码为空')
      toast.info('请输入验证码')
      return
    }

    // 检查微信号
    if (!form.value.wechat_id) {
      console.log('微信号为空')
      toast.info('请输入微信号')
      return
    }

    // 检查用户是否同意协议
    if (!isAgreed.value) {
      toast.info('请阅读并同意相关协议')
      return
    }

    // 所有验证通过，构建表单数据
    const formData = {
      ...form.value,
      region: regionText.value,
    }
    console.log('提交的表单数据:', formData)

    // 提交完整数据
    emit('submit', formData)
  } catch (error) {
    console.error('提交表单过程中出现异常:', error)
    toast.error('系统错误，请稍后重试')
  }
}

</script>

<style scoped>
.verify-btn {
  height: 32px;
  padding: 0 12px;
  background-color: #3b82f6;
  color: white;
  border-radius: 4px;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.verify-btn[disabled] {
  background-color: #a0aec0;
}
</style>
