<template>
	<view class="f-straight wrapper">
		<!-- <uni-notice-bar class="ss-m-b-30" scrollable text="填写联系人1后可获得500积分，可前往【门墩儿商城】兑换礼品【减压捏捏乐】，企业注册审核通过后积分将自动发放到您的账户中。" /> -->
		<view v-for="(val, index) in contacts" :key="index" class="f-straight contact-item">
			<view class="d-flex justify-space-between align-center ss-m-b-20">
				<view class="color-primary">{{ index === 0 ? '管理员' : '联系人' + index }}</view>
				<view v-if="index > 1">
					<uni-icons type="closeempty" size="20" color="#fe574a" @click="deleteContact(index)"></uni-icons>
				</view>
			</view>
			<uni-forms ref="formRef" :modelValue="val" :rules="formRules" validateTrigger="bind" label-width="105px" label-align="right" label-position="left">
				<uni-forms-item name="contactName" label="联系人姓名" required>
					<uni-easyinput v-model="val.contactName" placeholder="请输入"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="phone" label="联系电话" required>
					<uni-easyinput v-model="val.phone" placeholder="请输入" :disabled="index === 0"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="email" label="企业邮箱" required>
					<uni-easyinput v-model="val.email" placeholder="请输入企业邮箱（用于日后“登录邮箱”）"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="password" label="账户登录密码" required>
					<uni-easyinput v-model="val.password" placeholder="请输入"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="passwordConfirm" label="密码二次确认" required>
					<uni-easyinput v-model="val.passwordConfirm" placeholder="请输入"></uni-easyinput>
				</uni-forms-item>
			</uni-forms>
		</view>
		<view class="color-warning" style="text-align: center; margin-bottom: 50px;" @tap.stop="handleAddContact">
			<uni-icons type="plusempty" size="20" color="#fb8c00"></uni-icons>
			继续添加联系人
		</view>

		<button class="send-button" @tap="handleSubmit">提 交</button>
	</view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { userStore } from '@/store/user'
import { onLoad } from '@dcloudio/uni-app'
import { realName, mobile, emailRequired, password } from '@/utils/validate'
import { enterpriseRegisterApply } from '@/api/enterprise'

const useUserStore = userStore()
const adminUserPhone = computed(() => useUserStore?.phone)
const register = ref(JSON.parse(uni.getStorageSync('registerInfo')))
console.log(adminUserPhone.value, '注册手机号', register.value)

const formRef = ref()
const formRules = {
	contactName: realName,
  phone: mobile,
	email: emailRequired,
	password,
	passwordConfirm: {
		rules: [
			{ required: true, errorMessage: '请再次输入密码' },
			{ 
				validateFunction: function(rule, value, data, callback) {
					if (value !== data.password) callback('两次输入的密码不一致')
					return true
				}
			}
		]
	}
}

const contacts = ref([
  {
    contactName: '',
    phone: adminUserPhone.value || '',
    email: '',
    password: '',
    passwordConfirm: ''
  },
  {
    contactName: '',
    phone: '',
    email: '',
    password: '',
    passwordConfirm: ''
  }
])

onLoad((options) => {
	if (options?.isEdit) {
		const applyInfo = ref(uni.getStorageSync('entRegisterData') ? JSON.parse(uni.getStorageSync('entRegisterData')) : {})
		contacts.value = applyInfo.value.contacts.map(e =>  {
			e.passwordConfirm = e.password
			return e
		})
	}
})

const handleAddContact = () => {
	contacts.value.push({
		contactName: '',
		phone: '',
		email: '',
		password: '',
		passwordConfirm: ''
	})
}

const deleteContact = (index) => {
	contacts.value.splice(index, 1)
}

// 检查联系人信息是否重复
const checkDuplicates = (dataList) => {
  const emailRecord = {}
  const phoneRecord = {}
  for (const item of dataList) {
    const email = item.email
    const phone = item.phone
    if (emailRecord[email]) {
      return false
    }
    if (phoneRecord[phone]) {
      return false
    }
    emailRecord[email] = true
    phoneRecord[phone] = true
  }
  return true
}

const handleSubmit = async () => {
  // 存储所有的验证Promise
  const validationPromises = []
  formRef.value.forEach((e) => {
    validationPromises.push(e.validate().catch(err => {
      return false
    }))
  })

  // 等待所有验证Promise完成
  const validationResults = await Promise.all(validationPromises)
  const errorCount = validationResults.filter(result => result === false).length
  if (errorCount > 0) return

  if (!contacts.value.length || contacts.value.length < 2) {
    uni.showToast({
      title: '请至少添加两个联系人',
      icon: 'none',
      duration: 2000
    })
    return
  }

  const checkValue = checkDuplicates(contacts.value)
  if (!checkValue) {
    uni.showToast({
      title: '手机号或邮箱不能重复',
      icon: 'none',
      duration: 2000
    })
    return
  }

	const params = {
		...register.value,
		contacts: contacts.value,
		contactName: contacts.value[0].contactName,
		phone: contacts.value[0].phone,
		email: contacts.value[0].email
	}
	console.log(params, '企业注册参数')

	uni.showLoading({ title: '提交中' })
	try {
		await enterpriseRegisterApply(params)
		uni.hideLoading()
		uni.showToast({
			title: '提交成功',
			icon: 'success',
			duration: 2000
		})
		uni.reLaunch({
			url: '/pages/register/review'
		})
	} catch {
		uni.hideLoading()
	}
}
</script>

<style lang="scss" scoped>
.wrapper{
	padding: 15px;
}
.contact-item {
	border-bottom: 1px solid #eee;
	margin-bottom: 30px;
}
</style>