<template>
  <view class="container">
    <form @submit="handleSubmit">
      <u-input label="姓名" v-model.trim="tempContact.name" placeholder="请输入姓名"></u-input>
      <u-input label="关系" v-model.trim="tempContact.relationship" placeholder="请输入关系（如：父亲/母亲）"></u-input>
      <u-input label="手机号" v-model.trim="tempContact.phone" placeholder="请输入11位手机号" keyboard-type="number"></u-input>
      <button type="primary" class="submit-btn" :disabled="!isFormValid" form-type="submit">
        {{ currentType === 'add' ? '确认添加' : '确认修改' }}
      </button>
    </form>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tempContact: {
        name: '',
        relationship: '',
        phone: '',
        remark: '',
        // userId: null,
      },
      currentType: 'add',
    };
  },
  onLoad(options) {
    this.currentType = options.type || 'add';
    if (this.currentType === 'edit') {
      const contactId = options.id;
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2]; // 上一个页面
      const parentList = prevPage?.data?.personList || [];
  
      const found = parentList.find(item => item.id == contactId);
      if (found) {
        this.tempContact = { ...found };
      } else {
        uni.navigateBack(); // 未找到数据，返回
      }
    }
  },
  computed: {
    isFormValid() {
      const { name, relationship, phone } = this.tempContact;
      return name && relationship && /^1[3-9]\d{9}$/.test(phone);
    }
  },
  methods: {
    async handleSubmit() {
      if (!this.isFormValid) return;
      const url = this.currentType === 'add'
        ? '/app/emergency/insertEmergency'
        : '/app/emergency/updateEmergency';

      try {
        const res = await this.$Request.postT(url, this.tempContact);
        if (res.code === 0) {
          // 成功后回传联系人信息（带ID）
          const contact = {
			name: this.tempContact.name,
			relationship: this.tempContact.relationship,
			phone: this.tempContact.phone,
			id: res.data?.id || this.tempContact.id // 以接口返回ID为准
          };
          uni.$emit('updateContact', {
            ...contact,
            type: this.currentType
          });
          uni.showToast({ title: '操作成功', icon: 'success' });
          uni.navigateBack();
        } else {
          uni.showToast({ title: res.msg || '操作失败', icon: 'none' });
        }
      } catch (err) {
        uni.showToast({ title: '网络错误', icon: 'none' });
        console.error('提交失败:', err);
      }
    }
  }
};
</script>

<style scoped lang="scss">
	.container {
		padding: 40rpx 30rpx;
		background-color: #fff;
	}

	.page-title {
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
		text-align: center;
		margin: 40rpx 0;
	}

	.upload-avatar {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 40rpx;

		.avatar-preview {
			width: 200rpx;
			height: 200rpx;
			border-radius: 50%;
			overflow: hidden;
			position: relative;

			image {
				width: 100%;
				height: 100%;
			}

			.delete-btn {
				position: absolute;
				top: -15rpx;
				right: -15rpx;
				width: 30rpx;
				height: 30rpx;
				background-color: #ff4949;
				color: #fff;
				border-radius: 50%;
				text-align: center;
				line-height: 30rpx;
				font-size: 24rpx;
				z-index: 1;
			}
		}

		.upload-btn {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-top: 20rpx;
			color: #999;
			font-size: 28rpx;

			image {
				width: 120rpx;
				height: 120rpx;
				margin-bottom: 10rpx;
			}
		}
	}

	.submit-btn {
		margin-top: 60rpx;
		background-color: #409eff;
		border-radius: 10rpx;
		font-size: 32rpx;
		height: 80rpx;
		border: none;
	}
</style>