<template>
  <el-dialog
    title="分配卡"
    v-model="visible"
    width="500px"
    append-to-body
    align-center
    :center="true"
    :destroy-on-close="true"
  >
    <el-form
      ref="assignCardFormRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <!-- 卡类型 -->
      <el-form-item label="卡类型" prop="cardType" :required="true">
        <el-select
          v-model="form.cardType"
          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="卡号段" :required="true">
        <div style="display: flex; align-items: center; gap: 10px">
          <el-form-item prop="beginCardNo" style="flex: 1; margin-bottom: 0">
            <el-input
              v-model="form.beginCardNo"
              placeholder="开始卡号"
              style="width: 100%"
            />
          </el-form-item>
          <span>-</span>
          <el-form-item prop="endCardNo" style="flex: 1; margin-bottom: 0">
            <el-input
              v-model="form.endCardNo"
              placeholder="结束卡号"
              style="width: 100%"
            />
          </el-form-item>
        </div>
      </el-form-item>

      <!-- 代理商 -->
      <el-form-item label="代理商" prop="agentId" :required="true">
        <el-select
          v-model="form.agentId"
          placeholder="请选择代理商"
          style="width: 100%"
        >
          <el-option
            v-for="agent in agentList"
            :key="agent.id"
            :label="agent.name"
            :value="agent.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 省份 -->
      <el-form-item label="省份" prop="province">
        <el-select
          v-model="form.province"
          placeholder="请选择省份"
          style="width: 100%"
        >
          <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="学校" prop="school">
        <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="studentCategory">
        <el-select
          v-model="form.studentCategory"
          placeholder="请选择考生类别"
          style="width: 100%"
        >
          <el-option label="全部" value="all"></el-option>
          <el-option label="普通考生" value="normal"></el-option>
          <el-option label="艺术考生" value="art"></el-option>
          <el-option label="体育考生" value="sports"></el-option>
        </el-select>
      </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>
        <el-button @click="handleReassign">重新分配</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { assignCard } from "@/api/dz/cards";
import { getPaperProvinces } from "@/api/dz/papers";
import { listUniversity } from "@/api/dz/school";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  agentList: {
    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 assignCardFormRef = ref();
const provinceList = ref([]); // 省份列表
const schoolList = ref([]); // 学校列表

const form = ref({
  cardType: null,
  beginCardNo: "",
  endCardNo: "",
  agentId: null,
  province: "all",
  school: "all",
  studentCategory: "all",
});

const rules = {
  cardType: [{ required: true, message: "卡类型不能为空", trigger: "change" }],
  beginCardNo: [
    { required: true, message: "开始卡号不能为空", trigger: "blur" },
  ],
  endCardNo: [{ required: true, message: "结束卡号不能为空", trigger: "blur" }],
  agentId: [{ required: true, message: "代理商不能为空", trigger: "change" }],
};

// 重置表单
function resetForm() {
  form.value = {
    cardType: null,
    beginCardNo: "",
    endCardNo: "",
    agentId: null,
    province: "all",
    school: "all",
    studentCategory: "all",
  };
}

// 获取省份列表
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 handleCancel() {
  visible.value = false;
  resetForm();
}

// 提交
async function handleSubmit() {
  assignCardFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 获取开始号和结束号
        const begin = form.value.beginCardNo;
        const end = form.value.endCardNo;

        if (!begin || !end) {
          throw new Error("请填写完整的卡号段");
        }

        // 调用分配卡API
        await assignCard(form.value.agentId, begin, end);

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

// 重新分配
function handleReassign() {
  resetForm();
  emit("success", "已重置分配表单，请重新填写");
}

// 监听弹窗关闭，重置表单
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>
