<template>
  <view class="register_baby_overlay" v-if="visible" @click.stop>
    <!-- 遮罩层 -->
    <view class="mask_overlay" @click="handleClose"></view>
    
    <!-- 弹窗内容 -->
    <view class="register_baby_container" @click.stop>
      <!-- 弹窗头部 -->
      <view class="register_baby_header">
        <text class="register_baby_title">选择你当前的状态</text>
        <view class="close_button" @click="handleCancel">
          <text class="close_icon">×</text>
        </view>
      </view>

      <view class="register_baby_description">
        <text class="description_text">为了提供更有价值的服务，我们会将信息关联科学分析，星妈会不会泄漏您的任何个人信息，请放心使用。</text>
      </view>

      <form @submit="onSubmit">
        <view class="register_baby_info">
          <block v-for="(item, index) in formItems
            .filter(formItemFilter)
            .slice(
              0,
              formData.babyStage == 2 && pageStatus.formStatus == 2
                ? 6
                : formItems.length
            )" :key="item.name">
            <view class="form_row" :style="{
              'border-bottom':
                pageStatus.formStatus == 0 &&
                  index == formItems.filter(formItemFilter).length - 1
                  ? 'none'
                  : 'none'
            }">
              <text class="form_label">
                {{ getlabelFn(item) }}
                <text v-if="item.required" class="required">*</text>
              </text>

              <!-- 输入框类型 -->
              <input v-if="item.type === 'input'" class="form_input" :name="item.name" :placeholder="item.placeholder"
                v-model="formData[item.name]" :maxlength="item.maxLength" />

              <!-- 选择器类型 -->
              <PickerCustom v-else-if="item.type === 'picker'" :mode="item.mode" :range="item.range" :value="item.mode === 'date'
                ? formData[item.name]
                : getPickerIndex(item)
                " :onPickerChange="(e) => onPickerChange(e, item.name)"
                :onLayerVisibleChange="(e) => (pageStatus.btnStatus = !e)" :onStatusChange="onDateStatusChange">
                <view class="form_input_box">
                  <view class="form_input">{{
                    getLabelByValue(item, formData[item.name]) || item.placeholder
                  }}</view>
                  <text class="form_input_icon">{{'>'}}</text>
                </view>
              </PickerCustom>

              <!-- 多选弹窗类型 -->
              <view v-else-if="item.type === 'multi-picker'" @click="handleMultiPickerOpen(item)">
                <view class="form_input_box">
                  <view class="form_input">
                    {{
                      (formData[item.name] &&
                        (formData[item.name].split(",").join("、").length > 11
                          ? formData[item.name]
                            .split(",")
                            .join("、")
                            .slice(0, 11) + "..."
                          : formData[item.name].split(",").join("、"))) ||
                      item.placeholder
                    }}
                  </view>
                  <text class="form_input_icon">{{'>'}}</text>
                </view>
              </view>
            </view>
          </block>

          <view v-if="formData.babyStage == 2" class="form_bottom_btn" @click="handleFormBottomBtn">
            <text class="form_bottom_text">
              {{ pageStatus.formStatus == 1 ? "收起" : "展开" }}
            </text>
            <image v-if="pageStatus.formStatus == 1" class="form_bottom_icon"
              :src="$baseUrl + 'registerLayer/icon_arrow_yellow_up.png'" mode="aspectFit" />
            <image v-else class="form_bottom_icon" :src="$baseUrl + 'registerLayer/icon_arrow_yellow_down.png'"
              mode="aspectFit" />
          </view>
        </view>

        <!-- <view class="agreement_section">
          <view class="agreement_checkbox">
            <view class="checkbox" :class="{ checked: agreementChecked }" @click="agreementChecked = !agreementChecked">
              <text v-if="agreementChecked" class="checkmark">✓</text>
            </view>
            <text class="agreement_text">我已阅读并同意<text class="agreement_link" @click="openAgreement"
                data-type="member">《星妈会用户注册协议》</text><text class="agreement_link" @click="openAgreement"
                data-type="privacy">《星妈会隐私政策》</text></text>
          </view>
        </view> -->

        <button v-if="pageStatus.btnStatus" form-type="submit" class="form_btn" :class="{ disabled: !isBtnActive }">
          完成
        </button>
      </form>
    </view>

    <MultiSelectLayer v-if="multiPickerStatus && currentMultiPickerName" v-model="multiPickerStatus" :title="formItems.find((i) => i.name === currentMultiPickerName)?.label +
      '（多选）'
      " :options="formItems.find((i) => i.name === currentMultiPickerName)?.range"
      :modelSelected="multiPickerSelected[currentMultiPickerName]" @confirm="handleMultiPickerConfirm"
      @cancel="handleMultiPickerCancel" />
  </view>
</template>
<script setup>
import { ref, watch, computed, onMounted } from "vue";
import { showLoading, hideLoading } from "../utils";
import { useUserStore } from "../stores/user.js";
import { usePageCfgStore } from "../stores/pageCfg.js";
import PickerCustom from "./PickerCustom.vue";
import MultiSelectLayer from "./MultiSelectLayer.vue";
import { throttleTap } from "../utils/index.js";
import { jump, JumpType } from "../utils/index.js";

const userStore = useUserStore();
const pageCfgStore = usePageCfgStore();

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['close', 'confirm', 'cancel', 'update:modelValue']);

// 兼容 v-model 和 visible prop
const visible = computed(() => props.visible || props.modelValue);

watch(
  () => props.modelValue,
  (val) => {
    if (val !== visible.value) {
      emit('update:modelValue', val);
    }
  }
);

const handleClose = () => {
  emit('close');
  emit('update:modelValue', false);
};

function handleCancel() {
  emit("cancel");
  handleClose();
}

// 协议同意状态
const agreementChecked = ref(true);

// 页面状态管理
const pageStatus = ref({
  formStatus: 2, // 0: 隐藏 1: 展开, 2: 收起
  btnStatus: true, // 是否显示提交按钮
});

// 0备孕 1孕中 2出生
const formData = ref({
  babyStage: 2,
  babyName: "",
  babyBirthday: "",
  babyGender: "",
  babyType: "",
  feedingType: "",
  contentPreference: "",
  productPreference: "",
  followInfo: "",
  purchaseChannel: "",
});

const babyTypeMap = [
  { label: "一胎", value: 1 },
  { label: "二胎", value: 2 },
  { label: "三胎", value: 3 },
];
const babyStageMap = [
  { label: "备孕", value: 0 },
  { label: "孕中", value: 1 },
  { label: "已出生", value: 2 },
];
const babyGenderMap = [
  { label: "男", value: "M" },
  { label: "女", value: "F" },
  { label: "其他", value: "O" },
];

const FormMap = {
  0: ["babyStage", "contentPreference", "followInfo"],
  1: [
    "babyStage",
    "babyBirthday",
    "babyType",
    "contentPreference",
    "followInfo",
  ],
  2: [
    "babyStage",
    "babyName",
    "babyBirthday",
    "babyType",
    "babyGender",
    "feedingType",
    "contentPreference",
    "productPreference",
    "followInfo",
    "purchaseChannel",
  ],
};

const formItemFilter = (item) => {
  return FormMap[formData.value.babyStage].includes(item.name);
};

// 内容偏好选项
const contentLikeOptions = ref([]);
// 产品偏好选项
const productLikeOptions = ref([]);
// 特别关注选项
const specialAttentionOptions = ref([]);
// 购买渠道选项
const channelOptions = ref([]);

const MAX_babyName_LENGTH = 10;

watch(
  () => formData.value.babyStage,
  (newVal) => {
    pageStatus.value.formStatus = newVal == 2 ? 2 : 0;
  }
);

// 表单项配置
const formItems = ref([
  {
    label: "当前状态",
    name: "babyStage",
    required: true,
    placeholder: "请选择当前状态",
    type: "picker",
    range: babyStageMap.map((i) => i.label),
    mode: "custom",
  },
  {
    label: "宝宝昵称",
    name: "babyName",
    required: true,
    placeholder: "暂无昵称",
    type: "input",
    maxLength: MAX_babyName_LENGTH,
  },
  {
    label: "宝宝出生日期",
    name: "babyBirthday",
    required: true,
    placeholder: "请选择出生日期",
    type: "picker",
    mode: "date",
    defaultToday: true,
  },
  {
    label: "宝宝胎数",
    name: "babyType",
    required: true,
    placeholder: "未选择",
    type: "picker",
    range: babyTypeMap.map((i) => i.label),
    mode: "custom",
    disabled: false,
  },
  {
    label: "性别",
    name: "babyGender",
    required: true,
    placeholder: "未选择",
    type: "picker",
    range: babyGenderMap.map((i) => i.label),
    mode: "custom",
  },
  {
    label: "喂养方式",
    name: "feedingType",
    required: true,
    placeholder: "未选择",
    type: "picker",
    range: ["奶粉喂养", "母乳喂养", "母乳奶粉混合喂养"],
    mode: "custom",
  },
  {
    label: "内容偏好",
    name: "contentPreference",
    required: false,
    placeholder: "未选择",
    type: "multi-picker",
    range: [],
    mode: "custom",
  },
  {
    label: "产品使用偏好",
    name: "productPreference",
    required: false,
    placeholder: "未选择",
    type: "multi-picker",
    range: [],
    mode: "custom",
  },
  {
    label: "特殊关注信息",
    name: "followInfo",
    required: false,
    placeholder: "未选择",
    type: "multi-picker",
    range: [],
    mode: "custom",
  },
  {
    label: "常购买渠道",
    name: "purchaseChannel",
    required: false,
    placeholder: "未选择",
    type: "picker",
    range: [],
    mode: "custom",
  },
]);

const clearFormFields = () => {
  formData.value.babyBirthday = "";
  formData.value.babyType = "";
  formData.value.babyGender = "";
  formData.value.feedingType = "";
  formData.value.contentPreference = "";
  formData.value.productPreference = "";
  formData.value.followInfo = "";
  formData.value.purchaseChannel = "";
};

const getPickerIndex = (item) => {
  const val = formData.value[item.name];
  if (item.name === "babyStage") {
    const idx = babyStageMap.findIndex((i) => i.value === val);
    return idx > -1 ? idx : 0;
  }
  if (item.name === "babyType") {
    const idx = babyTypeMap.findIndex((i) => i.value === val);
    return idx > -1 ? idx : 0;
  }
  if (item.name === "babyGender") {
    const idx = babyGenderMap.findIndex((i) => i.value === val);
    return idx > -1 ? idx : 0;
  }
  if (item.mode === "date") {
    if (typeof val === "string" && val.match(/^\d{4}-\d{2}-\d{2}$/)) {
      const [year, month, day] = val.split("-").map(Number);
      const yearIdx = year - 1970;
      const monthIdx = month - 1;
      const dayIdx = day - 1;
      return [yearIdx, monthIdx, dayIdx];
    }
    const currentYear = new Date().getFullYear();
    return [currentYear - 1970, 0, 0];
  } else if (Array.isArray(item.range?.[0])) {
    if (Array.isArray(val)) {
      return val.map((v, col) => item.range[col].indexOf(v));
    }
    return item.range.map(() => 0);
  } else {
    return val ? item.range.indexOf(val) : 0;
  }
};

const onPickerChange = (e, name) => {
  const item = formItems.value.find((i) => i.name === name);
  if (name === "babyStage") {
    // 当阶段变化时清空相关表单项
    if (formData.value[name] !== babyStageMap[e].value) {
      clearFormFields();
    }
    formData.value[name] = babyStageMap[e].value;
    return;
  }
  if (name === "babyType") {
    formData.value[name] = babyTypeMap[e].value;
    return;
  }
  if (name === "babyGender") {
    formData.value[name] = babyGenderMap[e].value;
    return;
  }
  if (item.mode === "date") {
    formData.value[name] = e;
  } else if (Array.isArray(e)) {
    formData.value[name] = e.map((idx, col) => item.range[col][idx]).join(" ");
  } else {
    formData.value[name] = item.range[e];
  }
};

const onSubmit = async (e) => {
  if (!agreementChecked.value) {
    uni.showToast({
      title: "请先同意用户协议",
      icon: "none",
    });
    return;
  }

  // 获取当前阶段需要校验的字段
  const fieldsToValidate = FormMap[formData.value.babyStage].filter(
    (field) => field !== "babyStage"
  );

  // 获取必填的表单项
  const requiredFields = formItems.value
    .filter((item) => fieldsToValidate.includes(item.name) && item.required)
    .map((item) => ({
      name: item.name,
      label: item.label,
    }));

  // 校验必填项
  for (const field of requiredFields) {
    if (!formData.value[field.name]) {
      uni.showToast({
        title: `请填写${field.label}`,
        icon: "none",
      });
      return;
    }
  }

  const data = {
    babyBirthday: formData.value.babyBirthday,
    babyType: formData.value.babyType,
    contentPreference: formData.value.contentPreference,
    followInfo: formData.value.followInfo,
    babyName: formData.value.babyName,
    feedingType: formData.value.feedingType,
    productPreference: formData.value.productPreference,
    purchaseChannel: formData.value.purchaseChannel,
    babyStage: formData.value.babyStage,
    babyGender: formData.value.babyGender,
  };

  // 移除空值属性
  Object.keys(data).forEach((key) => {
    if (data[key] === "") {
      delete data[key];
    }
  });

  console.log("提交数据", data);

  showLoading();

  try {
    const success = await userStore.createBabyInfo(data);
    console.log("success:", success);
    hideLoading();
    if (success) {
      emit("confirm", {
        date: formData.value.babyBirthday,
        gender: formData.value.babyGender,
        fetus: formData.value.babyType,
        status: formData.value.babyStage,
      });
      handleClose();
    }
  } catch (error) {
    hideLoading();
    uni.showToast({
      title: "提交失败，请重试",
      icon: "none",
    });
  }
};

const handleFormBottomBtn = () => {
  pageStatus.value.formStatus = pageStatus.value.formStatus == 1 ? 2 : 1;
};

function openAgreement(e) {
  const type = e.currentTarget.dataset.type;
  if (type === "member") {
    jump({
      type: JumpType.INNER,
      url: "/pages/webview/webview?type=MEMBER_URL"
    });
  } else if (type === "privacy") {
    jump({
      type: JumpType.INNER,
      url: "/pages/webview/webview?type=PRIVACY_URL"
    });
  }
}

function onDateStatusChange(status) {
  formData.value.babyStage = status;
  if (status !== formData.value.babyStage) {
    clearFormFields();
  }
  return true;
}

const getlabelFn = (item) => {
  if (item.name === "babyBirthday") {
    item.label = formData.value.babyStage == 1 ? "预产日期" : "宝宝出生日期";
  }
  return item.label;
};

// getLabelByValue 支持所有映射字段
const getLabelByValue = (item, value) => {
  if (item.name === "babyStage") {
    return babyStageMap.find((i) => i.value === value)?.label || "";
  }
  if (item.name === "babyType") {
    return babyTypeMap.find((i) => i.value === value)?.label || "";
  }
  if (item.name === "babyGender") {
    return babyGenderMap.find((i) => i.value === value)?.label || "";
  }
  if (item.name === "babyBirthday") {
    item.placeholder = formData.value.babyBirthday
      ? formData.value.babyBirthday
      : formData.value.babyStage == 1
        ? "请选择预产日期"
        : "请选择出生日期";
    return item.placeholder;
  }
  return value;
};

const multiPickerStatus = ref(false); // 控制弹窗显示
const currentMultiPickerName = ref(""); // 当前弹窗对应的item.name
const multiPickerSelected = ref({}); // 存储每个multi-picker的选中项

function handleMultiPickerOpen(item) {
  currentMultiPickerName.value = item.name;
  multiPickerStatus.value = true;
  // 初始化选中项
  let val = formData.value[item.name];
  if (typeof val === "string") {
    val = val ? val.split(",") : [];
  }
  multiPickerSelected.value[item.name] = val || [];
}

function handleMultiPickerConfirm(selected) {
  if (!currentMultiPickerName.value) return;
  formData.value[currentMultiPickerName.value] = selected.join(",");
  multiPickerStatus.value = false;
  currentMultiPickerName.value = "";
}

function handleMultiPickerCancel() {
  multiPickerStatus.value = false;
  currentMultiPickerName.value = "";
}

const isBtnActive = computed(() => {
  if (formData.value.babyStage === 0) {
    return agreementChecked.value;
  } else {
    const fieldsToValidate = FormMap[formData.value.babyStage].filter(
      (field) => field !== "babyStage"
    );
    const requiredFields = formItems.value
      .filter((item) => fieldsToValidate.includes(item.name) && item.required)
      .map((item) => item.name);

    const hasRequiredFields = requiredFields.every(field => formData.value[field]);
    return agreementChecked.value && hasRequiredFields;
  }
});

const initData = () => {
  const contentCfg = JSON.parse(JSON.stringify(pageCfgStore.contentCfg));

  contentLikeOptions.value = contentCfg.contentLikeOptions;
  productLikeOptions.value = contentCfg.productLikeOptions;
  specialAttentionOptions.value = contentCfg.specialAttentionOptions;
  channelOptions.value = contentCfg.channelOptions;

  // 更新表单项的选项数据
  formItems.value.forEach((item) => {
    if (item.name === "contentPreference") {
      item.range = contentLikeOptions.value;
    } else if (item.name === "productPreference") {
      item.range = productLikeOptions.value;
    } else if (item.name === "followInfo") {
      item.range = specialAttentionOptions.value;
    } else if (item.name === "purchaseChannel") {
      item.range = channelOptions.value;
    }
  });
};

onMounted(async () => {
  await pageCfgStore.fetchCfg();
  initData();
});
</script>

<style lang="less" scoped>
.register_baby_overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  z-index: 9999;

  .mask_overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.8);
  }

  .register_baby_container {
    position: relative;
    width: 100%;
    background: #F7F7F7;
    border-radius: 24rpx 24rpx 0 0;
    padding: 0rpx 30rpx 0rpx 30rpx;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
    animation: slideUp 0.3s ease-out;
    z-index: 2;

    .register_baby_header {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 26rpx;
      margin-bottom: 26rpx;
      position: relative;

      .register_baby_title {
        font-size: 40rpx;
        font-weight: bold;
        color: #D3A458;
        text-align: center;
      }

      .close_button {
        position: absolute;
        right: 0;
        bottom: 5rpx;
        width: 54rpx;
        height: 54rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .close_icon {
          font-size: 50rpx;
          color: #333333;
          font-weight: bold;
          line-height: 1;
        }
      }
    }

    .register_baby_description {
      margin-bottom: 30rpx;

      .description_text {
        font-size: 24rpx;
        color: #666666;
        line-height: 1.5;
      }
    }

    .register_baby_info {
      background: #fff;
      border-radius: 24rpx;
      margin-bottom: 40rpx;
      padding: 20rpx;
      box-sizing: border-box;

      .form_row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 90rpx;
        border-bottom: 1rpx solid #f2f2f2;

        &:last-child {
          border-bottom: none;
        }
      }

      .form_label {
        width: 250rpx;
        color: #222;
        font-size: 28rpx;

        .required {
          color: #b88a3a;
          margin-left: -4rpx;
        }
      }

      .form_input {
        flex: 1;
        color: #6f6d67;
        font-size: 28rpx;
        background: none;
        border: none;
        outline: none;
        text-align: right;
      }

      .form_input_box {
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .form_input_icon {
        font-size: 24rpx;
        color: #6f6d67;
        margin-left: 16rpx;
        display: block;
        opacity: 0.6;
      }

      .form_bottom_btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 80rpx;

        .form_bottom_text {
          font-size: 28rpx;
          color: #6f6d67;
        }

        .form_bottom_icon {
          width: 19rpx;
          height: 12rpx;
          margin-left: 13rpx;
          display: block;
        }
      }
    }

    .agreement_section {
      margin-bottom: 40rpx;

      .agreement_checkbox {
        display: flex;
        align-items: center;

        .checkbox {
          width: 32rpx;
          height: 32rpx;
          border: 2rpx solid #ddd;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16rpx;

          &.checked {
            background-color: #D3A458;
            border-color: #D3A458;

            .checkmark {
              color: #ffffff;
              font-size: 20rpx;
              font-weight: bold;
            }
          }
        }

        .agreement_text {
          font-size: 24rpx;
          color: #666666;
          line-height: 1.4;

          .agreement_link {
            color: #D3A458;
            text-decoration: underline;
          }
        }
      }
    }

    .form_btn {
      width: 100%;
      height: 94rpx;
      border-radius: 46rpx;
      background-color: #d3a358;
      color: #ffffff;
      font-size: 32rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 50rpx;
      border: none;
      outline: none;

      &.disabled {
        background-color: #ccc;
        color: #999;
      }
    }
  }
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }

  to {
    transform: translateY(0);
  }
}
</style>
