<template>
  <el-dialog
    title="制卡"
    v-model="visible"
    width="500px"
    append-to-body
    align-center
    :center="true"
    :destroy-on-close="true"
  >
    <el-form
      ref="cardGenerationFormRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <!-- 机构 -->
      <el-form-item label="机构" prop="institutionId" :required="true">
        <el-select
          v-model="form.institutionId"
          placeholder="请选择机构"
          style="width: 100%"
        >
          <el-option
            v-for="institution in institutionList"
            :key="institution.deptId"
            :label="institution.deptName"
            :value="institution.deptId"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 卡类型 -->
      <el-form-item label="卡类型" prop="type" :required="true">
        <el-select
          v-model="form.type"
          placeholder="请选择卡类型"
          style="width: 100%"
        >
          <el-option
            v-for="dict in cardTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 省份 -->
      <!-- <el-form-item label="省份">
        <el-select
          v-model="form.province"
          placeholder="请选择省份"
          style="width: 100%"
        >
          <el-option label="全部" value="all"></el-option>
          <el-option
            v-for="province in provinceList"
            :key="province.dictValue"
            :label="province.dictLabel"
            :value="province.dictValue"
          ></el-option>
        </el-select>
      </el-form-item> -->

      <!-- 学校 -->
      <!-- <el-form-item label="学校">
        <el-select
          v-model="form.school"
          placeholder="请选择学校"
          style="width: 100%"
          :disabled="form.province === 'all'"
        >
          <el-option label="全部" value="all"></el-option>
          <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="cardQuantity" :required="true">
        <el-input-number
          v-model="form.cardQuantity"
          :min="1"
          :max="1000"
          placeholder="请输入卡数量"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">开始制卡</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { issueCard } from "@/api/dz/cards";
import { getPaperProvinces } from "@/api/dz/papers";
import { listUniversity } from "@/api/dz/school";
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  institutionList: {
    type: Array,
    default: () => [],
  },
  schoolList: {
    type: Array,
    default: () => [],
  },
  cardTypeOptions: {
    type: Array,
    default: () => [],
  },
});

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

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

const cardGenerationFormRef = ref();
const provinceList = ref([]); // 省份列表
const schoolList = ref([]); // 学校列表
const form = ref({
  institutionId: null,
  type: null,
  province: "all",
  school: "all",
  cardQuantity: 1,
});

const rules = {
  institutionId: [
    { required: true, message: "机构不能为空", trigger: "change" },
  ],
  type: [{ required: true, message: "卡类型不能为空", trigger: "change" }],
  cardQuantity: [
    { required: true, message: "卡数量不能为空", trigger: "blur" },
    {
      type: "number",
      min: 1,
      max: 1000,
      message: "请输入正确的卡数量",
      trigger: "blur",
    },
  ],
};

// 获取卡类型枚举
function getCardTypeEnum(typeValue) {
  const cardTypeMap = {
    6: "Platform",
    2: "Dept",
    7: "ECard",
    8: "Test",
  };
  return cardTypeMap[typeValue] || "ECard"; // 默认返回电子卡
}

// 获取省份列表
async function getProvinceList() {
  try {
    const response = await getPaperProvinces();
    if (response.code === 200) {
      provinceList.value = response.data || [];
    }
  } catch (error) {
    console.error("获取省份列表失败:", error);
  }
}

// 根据省份获取学校列表
async function getSchoolListByProvince(province) {
  try {
    if (province === "all" || !province) {
      schoolList.value = [];
      return;
    }

    const response = await listUniversity({
      location: province,
      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 resetForm() {
  form.value = {
    institutionId: null,
    type: null,
    province: "all",
    school: "all",
    cardQuantity: 1,
  };
}

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

// 提交
async function handleSubmit() {
  cardGenerationFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const cardData = {
          institutionId: form.value.institutionId,
          type: form.value.type,
          count: parseInt(form.value.cardQuantity),
        };
        await issueCard(
          cardData.institutionId,
          getCardTypeEnum(cardData.type),
          cardData.count
        );

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

// 监听弹窗关闭，重置表单
watch(visible, (newVal) => {
  if (!newVal) {
    resetForm();
  } else {
    // 弹窗打开时获取省份列表
    // getProvinceList(); // 暂时屏蔽
  }
});

// 监听省份变化，获取对应学校
// watch(
//   () => form.value.province,
//   (newProvince) => {
//     // 重置学校选择
//     form.value.school = "all";
//     // 获取对应省份的学校列表
//     getSchoolListByProvince(newProvince);
//   }
// );
</script>

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