<template>
  <el-dialog
    v-model="dialogVisible"
    title="绑定父母"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">

      <el-form-item label="父亲">
        <div class="parent-selector">
          <el-select
            v-model="formData.father_id"
            placeholder="请输入手机号或者账号"
            clearable
            filterable
            remote
            reserve-keyword
            :remote-method="(query) => handleSearchUser(query, 1)"
            :loading="searchLoading"
            style="width: 100%"
          >
            <template #default>
              <div class="search-tip">支持账号/手机号搜索</div>
              <el-option
                v-for="user in maleUsers"
                :key="user.id"
                :label="user.name || user.account"
                :value="user.id"
              >
                <div class="user-option">
                  <span class="user-name">{{ user.name || user.account }}</span>
                  <span class="user-phone">{{ user.phone }}</span>
                </div>
              </el-option>
            </template>
          </el-select>
          <el-button link type="primary" @click="handleSearchUser('', 1)">
            <i class="fa-solid fa-refresh"></i> 刷新列表
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="母亲">
        <div class="parent-selector">
          <el-select
            v-model="formData.mother_id"
            placeholder="请输入手机号或者账号"
            clearable
            filterable
            remote
            reserve-keyword
            :remote-method="(query) => handleSearchUser(query, 2)"
            :loading="searchLoading"
            style="width: 100%"
          >
            <template #default>
              <div class="search-tip">支持账号/手机号搜索</div>
              <el-option
                v-for="user in femaleUsers"
                :key="user.id"
                :label="user.name || user.account"
                :value="user.id"
              >
                <div class="user-option">
                  <span class="user-name">{{ user.name || user.account }}</span>
                  <span class="user-phone">{{ user.phone }}</span>
                </div>
              </el-option>
            </template>
          </el-select>
          <el-button link type="primary" @click="handleSearchUser('', 2)">
            <i class="fa-solid fa-refresh"></i> 刷新列表
          </el-button>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { bindParent, getParents, getUserList } from '@/api/babyhealth';

interface Baby {
  id: number;
  name: string;
  nickname: string;
  avatar: string;
}

interface User {
  id: number;
  name: string;
  account: string;
  phone: string;
  sex: number;
}

const props = defineProps<{
  visible: boolean;
  babyData?: Baby | null;
}>();

const emit = defineEmits<{
  'update:visible': [value: boolean];
  success: [];
}>();

const dialogVisible = ref(false);
const loading = ref(false);
const searchLoading = ref(false);
const formRef = ref<FormInstance>();
const users = ref<User[]>([]);
const allUsers = ref<User[]>([]);
const parents = ref<User[]>([]);

const formData = reactive<{
  father_id: number | null;
  mother_id: number | null;
}>({
  father_id: null,
  mother_id: null,
});

const formRules: FormRules = {};

// 过滤男性用户
const maleUsers = computed(() => {
  return users.value.filter(user => user.sex === 1);
});

// 过滤女性用户
const femaleUsers = computed(() => {
  return users.value.filter(user => user.sex === 2);
});

// 拼接接口路径
const getEnvUrl = (path: string) => {
  const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
  return `${API_BASE_URL}${path}`;
};

// 重置表单
const resetForm = () => {
  formData.father_id = null;
  formData.mother_id = null;
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

// 监听 visible 变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val;
  if (val) {
    fetchUsers();
  }
});

// 监听对话框关闭，重置搜索结果
watch(dialogVisible, (val) => {
  if (!val) {
    users.value = parents.value;
  }
});

// 监听 dialogVisible 变化
watch(dialogVisible, (val) => {
  emit('update:visible', val);
});

// 获取用户列表和已有父母数据
const fetchUsers = async () => {
  try {
    // 获取所有用户列表
    const res = await getUserList();
    if (res.code === 200) {
      allUsers.value = res.data || [];
      users.value = res.data || [];
    }

    // 获取当前宝贝已绑定的父母数据
    if (props.babyData?.id) {
      const parentsRes = await getParents(props.babyData.id);
      if (parentsRes.code === 200 && parentsRes.data) {
        formData.father_id = parentsRes.data.father_id || null;
        formData.mother_id = parentsRes.data.mother_id || null;

        // 如果已绑定父亲但不在用户列表中，添加进去以便显示名称
        if (parentsRes.data.father_id && parentsRes.data.father) {
          const fatherExists = allUsers.value.some(u => u.id === parentsRes.data.father_id);
          if (!fatherExists) {
            allUsers.value.push({
              id: parentsRes.data.father_id,
              name: parentsRes.data.father,
              account: '',
              phone: '',
              sex: 1
            });
          }
        }

        // 如果已绑定母亲但不在用户列表中，添加进去以便显示名称
        if (parentsRes.data.mother_id && parentsRes.data.mother) {
          const motherExists = allUsers.value.some(u => u.id === parentsRes.data.mother_id);
          if (!motherExists) {
            allUsers.value.push({
              id: parentsRes.data.mother_id,
              name: parentsRes.data.mother,
              account: '',
              phone: '',
              sex: 2
            });
          }
        }

        // 更新用户列表
        users.value = allUsers.value;
      }
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败');
  }
};

// 搜索用户
const handleSearchUser = async (query: string, sex: number) => {
  searchLoading.value = true;
  try {
    if (!query) {
      // 如果查询为空，显示所有对应性别的用户
      users.value = allUsers.value.filter(user => user.sex === sex);
    } else {
      // 通过账号或手机号搜索
      const filteredUsers = allUsers.value.filter(user => {
        const isTargetSex = user.sex === sex;
        const matchAccount = user.account?.toLowerCase().includes(query.toLowerCase());
        const matchPhone = user.phone?.includes(query);
        const matchName = user.name?.toLowerCase().includes(query.toLowerCase());
        return isTargetSex && (matchAccount || matchPhone || matchName);
      });
      users.value = filteredUsers;
    }
  } catch (error) {
    console.error('搜索用户失败:', error);
    ElMessage.error('搜索用户失败');
  } finally {
    searchLoading.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  if (!props.babyData?.id) {
    ElMessage.error('宝贝信息不存在');
    return;
  }

  loading.value = true;
  try {
    const submitData: Record<string, any> = {};
    if (formData.father_id) {
      submitData.father_id = formData.father_id;
    }
    if (formData.mother_id) {
      submitData.mother_id = formData.mother_id;
    }

    const res = await bindParent(props.babyData.id, submitData);

    if (res.code === 200) {
      ElMessage.success('绑定成功');
      dialogVisible.value = false;
      resetForm();
      emit('success');
    } else {
      ElMessage.error(res.msg || '绑定失败');
    }
  } catch (error) {
    console.error('绑定失败:', error);
    ElMessage.error('绑定失败');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped lang="less">
.baby-info-display {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: var(--el-fill-color-light);
  border-radius: 8px;

  .baby-avatar-mini {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    object-fit: cover;
  }

  .baby-info-text {
    flex: 1;

    .baby-name {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }

    .baby-nickname {
      font-size: 14px;
      color: var(--el-text-color-regular);
    }
  }
}

.parent-selector {
  display: flex;
  gap: 8px;
  align-items: center;
  width: 100%;

  .el-select {
    flex: 1;
  }
}

.search-tip {
  padding: 8px 12px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  border-bottom: 1px solid var(--el-border-color-lighter);
  background: var(--el-fill-color-lighter);
}

.user-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;

  .user-name {
    flex: 1;
  }

  .user-phone {
    margin-left: 12px;
    color: var(--el-text-color-secondary);
    font-size: 12px;
  }
}
</style>
