<template>
  <view class="task_person_overlay" v-if="visible">
    <!-- 遮罩层 -->
    <view class="mask_overlay"></view>
    
    <!-- 弹窗内容 -->
    <view class="task_person_container" @click.stop>
      <view class="task_person_header">
        <text class="task_person_title">选择你当前的状态</text>
        <view class="close_button" @click="handleClose">
          <text class="close_icon">×</text>
        </view>
      </view>

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

      <form @submit="onSubmit">
        <view class="task_person_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'
                  : '1rpx solid #f2f2f2',
            }">
              <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" />
              <!-- 只读展示类型 -->
              <view v-else-if="item.type === 'display'" class="form_input_box">
                <view class="form_input" style="color: #222">{{
                  formData[item.name] || item.placeholder
                  }}</view>
              </view>
              <view v-else-if="item.type === 'display-obj'" class="form_input_box">
                <view class="form_input" style="color: #222">{{
                  getLabelByValue(item, formData[item.name])
                  }}</view>
              </view>
              <!-- 选择器类型 -->
              <picker-custom 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>
                  <image class="form_input_icon" :src="$baseUrl + 'person/icon_arrow_yellow_right.png'" />
                </view>
              </picker-custom>
              <!-- 多选弹窗类型 -->
              <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>
                  <image class="form_input_icon" :src="$baseUrl + 'person/icon_arrow_yellow_right.png'" />
                </view>
              </view>
              <!-- 单选类型 -->
              <radio-group v-else-if="item.type === 'radio'" @change="(e) => onRadioChange(e, item.name)">
                <label v-for="opt in item.options" :key="opt.value" class="form_radio">
                  <radio :value="opt.value" :checked="formData[item.name] === opt.value" />
                  {{ opt.label }}
                </label>
              </radio-group>
            </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 + 'person/icon_arrow_yellow_up.png'" mode="aspectFit" />
            <image v-else class="form_bottom_icon" :src="$baseUrl + 'person/icon_arrow_yellow_down.png'"
              mode="aspectFit" />
          </view>
        </view>

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

        <button v-if="pageStatus.btnStatus" form-type="submit" class="form_btn" :class="{ disabled: !agreementChecked }">
          完成
        </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, onMounted, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { useUserStore } from "../../stores/user.js";
import PickerCustom from "../PickerCustom.vue";
import MultiSelectLayer from "../MultiSelectLayer.vue";
import { uploadImage } from "../../api/common.js";
import { showLoading, hideLoading } from "../../utils/index.js";
import { updateBabyInfo, getGestationalWeeks } from "../../api/user.js";
import { usePageCfgStore } from "../../stores/pageCfg";
import md from "../../md.js";
import { jump, JumpType } from "../../utils/index.js";

// Props 定义
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});

// Emits 定义
const emit = defineEmits(['close', 'success']);

const userStore = useUserStore();
const pageType = ref("add");
const babyId = ref("");

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

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

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

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",
    "gestationalWeeks",
    "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 MAX_babyName_LENGTH = 10;

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

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

// 表单项配置
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: false,
    placeholder: "未选择",
    type: "picker",
    range: ["奶粉喂养", "母乳喂养", "母乳奶粉混合喂养"],
    mode: "custom",
  },
  {
    label: "孕周",
    name: "gestationalWeeks",
    required: false,
    placeholder: "",
    type: "display",
  },
  {
    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 = "";
  if (!userStore.babyInfo.content?.babyType) {
    formData.value.babyType = "";
  }
  formData.value.babyGender = "";
  formData.value.feedingType = "";
  formData.value.contentPreference = "";
  formData.value.productPreference = "";
  formData.value.followInfo = "";
  formData.value.purchaseChannel = "";
  formData.value.gestationalWeeks = "";
};

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 (
      pageType.value === "edit" &&
      babyStageMap[e].value < userStore.babyInfo.babyStage
    ) {
      uni.showToast({
        title: "不能选择更早的阶段",
        icon: "none",
      });
      return;
    }

    // 当阶段变化时清空相关表单项
    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 onRadioChange = (e, name) => {
  formData.value[name] = e.detail.value;
};

const sleep = (delay) => {
  return new Promise((resolve) => {
    setTimeout(() => resolve(), delay);
  });
};

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

  md.sensorLogTake({
    xcxClick: "任务页面-信息完善页点击",
    pageName: "任务页面-信息完善页",
    buttonName: "完成",
  });

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

  console.log("fieldsToValidate", formData.value);

  // 获取必填的表单项
  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,
    babyAvatar: formData.value.babyAvatar,
    backgroundImg: formData.value.backgroundImg,
    babyGender: formData.value.babyGender,
  };

  if (babyId.value) {
    data.id = babyId.value;
  }

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

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

  const pregnancyStatus = babyStageMap.find((i) => i.value === formData.value.babyStage)?.label || "";
  md.sensorUserLogTake({
    memberid: uni.getStorageSync('memberId'),
    pregnancyStatus: pregnancyStatus,
  })
  showLoading();

  const res = await updateBabyInfo(data);

  hideLoading();

  if (res.success) {
    data?.id && userStore.setBabyNickCache(data?.id, formData.value.babyName);

    showLoading();
    await sleep(3000);
    await userStore.loadUserInfo();
    await userStore.loadBabyInfo();
    await userStore.loadHomeInfo();
    hideLoading();

    uni.showToast({
      title: "提交成功",
      icon: "success",
    });
    
    // 触发成功事件
    emit('success');
    // 关闭弹窗
    handleClose();
  } else {
    uni.showToast({
      title: res.message,
      icon: "none",
    });
  }
};

const handleClose = () => {
  emit('close');
};

const handleFormBottomBtn = () => {
  md.sensorLogTake({
    xcxClick: "任务页面-信息完善页点击",
    pageName: "任务页面-信息完善页",
    buttonName: pageStatus.value.formStatus == 1 ? "收起" : "展开",
  });

  pageStatus.value.formStatus = pageStatus.value.formStatus == 1 ? 2 : 1;
};

const toggleAgreement = () => {
  agreementChecked.value = !agreementChecked.value;
};

function onDateStatusChange(status) {
  if (pageType.value === "edit" && status < userStore.babyInfo.babyStage) {
    uni.showToast({
      title: "不能超过当前时间哦～",
      icon: "none",
    });
    return false;
  }
  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") {
    // console.log("🚀 ~ getLabelByValue ~ formData:", formData.value, item)
    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 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;
    } else if (
      pageType.value == "edit" &&
      item.name === "babyType" &&
      userStore.babyInfo.content?.babyType
    ) {
      item.type = "display-obj";
    } else if (item.name === "babyBirthday") {
      item.label = formData.value.babyStage == 2 ? "宝宝出生日期" : "预产日期";
      item.placeholder =
        formData.value.babyStage == 2 ? "请选择出生日期" : "请选择预产日期";
    }
  });
};

onMounted(async() => {
  md.sensorLogTake({
    xcxPage: "任务页面-信息完善页浏览",
    pageName: "任务页面-信息完善页",
  });

  await pageCfgStore.fetchCfg();

  initData();
});

// 监听 babyStage 和 dueDate
watch(
  () => [formData.value.babyStage, formData.value.babyBirthday],
  async ([stage, dueDate], [oldStage, oldDueDate]) => {
    if (stage === 1) {
      // 1. 没有孕周
      // 2. 预产期变化
      if (!formData.value.gestationalWeeks || dueDate !== oldDueDate) {
        if (dueDate) {
          const res = await getGestationalWeeks(dueDate);
          if (res.success) {
            formData.value.gestationalWeeks = res.data.gestationalWeeks;
          }
        }
      }
    }
  }
);
</script>

<style lang="less" scoped>
@import './TaskPerson.less';
</style>
