<template>
  <el-dialog
    title="编辑"
    v-model="visible"
    width="500px"
    append-to-body
    align-center
    :center="true"
    :destroy-on-close="true"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <!-- 学校 -->
      <el-form-item label="学校" prop="schoolId">
        <el-select
          v-model="form.schoolId"
          placeholder="请选择学校"
          style="width: 100%"
        >
          <el-option
            v-for="school in schoolList"
            :key="school.id"
            :label="school.name"
            :value="school.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 班级 -->
      <el-form-item label="班级" prop="classId">
        <el-select
          v-model="form.classId"
          placeholder="请选择班级"
          style="width: 100%"
        >
          <el-option
            v-for="classItem in classList"
            :key="classItem.id"
            :label="classItem.name"
            :value="classItem.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 姓名 -->
      <el-form-item label="姓名" prop="nickName">
        <el-input v-model="form.nickName" placeholder="请输入姓名" />
      </el-form-item>

      <!-- 手机号 -->
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>

      <!-- 语数英 -->
      <el-form-item label="语数英" prop="chineseMathEnglish">
        <el-input
          v-model="form.chineseMathEnglish"
          placeholder="请输入语数英成绩"
        />
      </el-form-item>

      <!-- 职业技能 -->
      <el-form-item label="职业技能" prop="vocationalSkills">
        <el-input
          v-model="form.vocationalSkills"
          placeholder="请输入职业技能成绩"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">保 存</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { getCards, addCards, updateCards } from "@/api/dz/cards";
import { listUniversity } from "@/api/dz/school";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  cardId: {
    type: [String, Number],
    default: null,
  },
  schoolList: {
    type: Array,
    default: () => [],
  },
  classList: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update:modelValue", "success"]);

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});

const formRef = ref();
const schoolList = ref([]); // 学校列表

const form = ref({
  cardId: null,
  schoolId: null,
  classId: null,
  nickName: "",
  phone: "",
  chineseMathEnglish: "",
  vocationalSkills: "",
});

const rules = {
  schoolId: [{ required: true, message: "学校不能为空", trigger: "change" }],
  classId: [{ required: true, message: "班级不能为空", trigger: "change" }],
  nickName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  phone: [
    { required: true, message: "手机号不能为空", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  chineseMathEnglish: [
    { required: true, message: "语数英成绩不能为空", trigger: "blur" },
  ],
  vocationalSkills: [
    { required: true, message: "职业技能成绩不能为空", trigger: "blur" },
  ],
};

// 重置表单
function resetForm() {
  form.value = {
    cardId: null,
    schoolId: null,
    classId: null,
    nickName: "",
    phone: "",
    chineseMathEnglish: "",
    vocationalSkills: "",
  };
}

// 获取所有学校列表
async function getAllSchools() {
  try {
    const response = await listUniversity({
      pageNum: 1,
      pageSize: 1000,
    });
    if (response.code === 200) {
      // 处理API返回的数据结构
      let schoolData = [];

      // 检查是否有rows字段（直接在response中）
      if (response.rows) {
        schoolData = response.rows;
      }
      // 检查是否有data.rows字段
      else if (response.data && response.data.rows) {
        schoolData = response.data.rows;
      }
      // 检查是否有data数组
      else if (response.data && Array.isArray(response.data)) {
        schoolData = response.data;
      }
      // 检查是否有data对象
      else if (response.data && response.data.id) {
        schoolData = [response.data];
      }

      schoolList.value = schoolData;
      console.log("所有学校数据:", schoolData);
    }
  } catch (error) {
    console.error("获取所有学校列表失败:", error);
    schoolList.value = [];
  }
}

// 取消
function handleCancel() {
  visible.value = false;
  resetForm();
}

// 提交
async function handleSubmit() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.value.cardId != null) {
          await updateCards(form.value);
        } else {
          await addCards(form.value);
        }

        emit("success", "保存成功!");
        visible.value = false;
        resetForm();
      } catch (error) {
        console.error("保存失败:", error);
        throw error;
      }
    }
  });
}

// 获取卡片数据
async function fetchCardData() {
  if (props.cardId) {
    try {
      const response = await getCards(props.cardId);
      form.value = response.data;
    } catch (error) {
      console.error("获取卡片数据失败:", error);
    }
  }
}

// 监听弹窗打开，获取数据
watch(visible, (newVal) => {
  if (newVal && props.cardId) {
    fetchCardData();
    getAllSchools(); // 获取所有学校列表
  } else if (!newVal) {
    resetForm();
  }
});
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
