<script setup lang="ts">
import { ref } from 'vue'
import { bindWxMpUser } from '@/common/apis/ab98'
import { showLoadingToast, showSuccessToast, showFailToast } from 'vant';
import { useWxStore } from '@/pinia/stores/wx';

interface Props {
  show: boolean
}

const props = defineProps<Props>();

const wxStore = useWxStore();

const emit = defineEmits<{
  (e: 'update:show', value: boolean): void
  (e: 'success'): void
}>()

const formData = ref({
  dynamicCode: '',
  name: '',
  idNum: ''
})

const loading = ref(false)

const handleClose = () => {
  emit('update:show', false)
}

const handleSubmit = async () => {
  if (!formData.value.dynamicCode || !formData.value.name || !formData.value.idNum) {
    showFailToast('请填写完整信息')
    return
  }

  loading.value = true
  showLoadingToast({
    message: '绑定中...',
    forbidClick: true
  })

  try {
    await bindWxMpUser({
      corpid: wxStore.corpid,
      dynamicCode: formData.value.dynamicCode,
      name: formData.value.name,
      idNum: formData.value.idNum
    })

    showSuccessToast('绑定成功')
    emit('success')
    handleClose()

    // 重置表单
    formData.value = {
      dynamicCode: '',
      name: '',
      idNum: ''
    }
  } catch (error) {
    console.error('绑定失败:', error)
    showFailToast('绑定失败，请检查信息是否正确')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <van-dialog
    :show="props.show"
    title="代绑汇邦云"
    show-cancel-button
    confirm-button-text="绑定"
    cancel-button-text="取消"
    :before-close="handleClose"
    @confirm="handleSubmit"
  >
    <div class="bind-form p-4">
      <van-form>
        <van-cell-group inset>
          <van-field
            v-model="formData.dynamicCode"
            label="动态码"
            placeholder="请输入动态码"
            required
          />
          <van-field
            v-model="formData.name"
            label="姓名"
            placeholder="请输入姓名"
            required
          />
          <van-field
            v-model="formData.idNum"
            label="身份证号"
            placeholder="请输入身份证号"
            required
          />
        </van-cell-group>
      </van-form>
    </div>
  </van-dialog>
</template>

<style lang="scss" scoped>
.bind-form {
  max-height: 400px;
  overflow-y: auto;
}
</style>
