<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%"
          clearable
        >
          <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%"
          clearable
        >
          <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%"
          clearable
        >
          <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"
          clearable
        >
          <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%"
          clearable
        >
          <el-option label="全部" value="all"></el-option>
          <el-option
            v-for="examType in examTypeList"
            :key="examType.dictValue"
            :label="examType.dictLabel"
            :value="examType.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit" :loading="loading"
          >分配</el-button
        >
        <el-button @click="handleCancel">取消</el-button>
        <!--        <el-button @click="handleReassign" :loading="reassignLoading"-->
<!--          >重新分配</el-button-->
<!--        >-->
      </div>
    </template>
  </el-dialog>
</template>

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

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  selectedCards: {
    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 loading = ref(false);
const reassignLoading = ref(false);
const provinceList = ref([]); // 省份列表
const schoolList = ref([]); // 学校列表
const examTypeList = ref([]); // 考生类型列表
const agentList = ref([]); // 代理商列表

const form = ref({
  cardType: null,
  beginCardNo: "",
  endCardNo: "",
  agentId: null,
  province: null,
  school: null,
  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: null,
    school: null,
    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 getExamTypeList(location) {
  try {
    const response = await getExamTypes(location);
    if (response.code === 200) {
      examTypeList.value = response.data || [];
    }
  } catch (error) {
    console.error("获取考生类型列表失败:", error);
  }
}

// 获取代理商列表
async function getAgentListData() {
  try {
    const response = await getAgentList({});
    if (response.code === 200) {
      // 处理代理商数据，映射字段名
      agentList.value = (response.data || []).map((item) => ({
        id: item.agentId,
        name: item.name,
        agentId: item.agentId,
        deptId: item.deptId,
        phonenumber: item.phonenumber,
        schoolName: item.schoolName,
      }));
    }
  } catch (error) {
    console.error("获取代理商列表失败:", error);
  }
}

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

    const response = await getCampusSchoolList({
      campus: false,
      location: province,
      pageNum: 1,
      pageSize: 9999,
    });
    if (response.code === 200) {
      // 处理API返回的数据结构
      let schoolData = [];

      // 检查是否有data字段
      if (response.data) {
        schoolData = Array.isArray(response.data) ? response.data : [];
      }
      // 检查是否有rows字段
      else if (response.rows) {
        schoolData = response.rows;
      }
      // 检查是否有list字段
      else if (response.list) {
        schoolData = response.list;
      }

      // 确保数据格式符合配置要求
      schoolData = schoolData.map((item) => {
        // 如果API返回的是 {id, name, ...} 格式，直接使用
        if (item.id && item.name) {
          return item;
        }
        // 如果是其他格式，需要转换
        return {
          id: item.id || item.value || item.schoolId,
          name: item.name || item.label || item.schoolName || item.title,
        };
      });

      schoolList.value = schoolData;
      console.log("学校数据:", schoolData); // 添加调试日志
    }
  } catch (error) {
    console.error("获取学校列表失败:", error);
    schoolList.value = [];
  }
}

// 自动填充卡号段
function autoFillCardRange() {
  console.log("autoFillCardRange called, selectedCards:", props.selectedCards);
  if (props.selectedCards && props.selectedCards.length > 0) {
    const cardNos = props.selectedCards
      .map((card) => card.cardNo || card.id)
      .filter((cardNo) => cardNo && cardNo !== "未知")
      .sort();

    console.log("cardNos:", cardNos);
    if (cardNos.length > 0) {
      const minCardNo = cardNos[0];
      const maxCardNo = cardNos[cardNos.length - 1];

      // 开始卡号段是最小卡号段的整十数部分
      const minCardNoNum = parseInt(minCardNo);
      const beginCardNo = Math.floor(minCardNoNum / 10) * 10;

      // form.value.beginCardNo = beginCardNo.toString();
      // form.value.endCardNo = maxCardNo;
    }
  }
}

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

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

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

        // 调用分配卡API，传递所有参数
        // 将 "all" 转换为 null，因为后端 ExamType 枚举不接受 "all" 值
        const examType =
          form.value.studentCategory === "all"
            ? null
            : form.value.studentCategory;

        await assignCard(
          form.value.cardType,
          form.value.agentId,
          begin,
          end,
          form.value.province,
          examType,
          form.value.school
        );

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

// 重新分配
async function handleReassign() {
  assignCardFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        reassignLoading.value = true;
        // 获取开始号和结束号
        const begin = form.value.beginCardNo;
        const end = form.value.endCardNo;

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

        // 再次调用分配卡API
        // 将 "all" 转换为 null，因为后端 ExamType 枚举不接受 "all" 值
        const examType =
          form.value.studentCategory === "all"
            ? null
            : form.value.studentCategory;

        await assignCard(
          form.value.cardType,
          form.value.agentId,
          begin,
          end,
          form.value.province,
          examType,
          form.value.school
        );

        emit("success", "重新分配卡成功!");
        visible.value = false;
        resetForm();
      } catch (error) {
        console.error("重新分配卡失败:", error);
        throw error;
      } finally {
        reassignLoading.value = false;
      }
    } else {
      // 如果表单验证失败，提示用户
      console.warn("表单验证失败，请检查必填项");
    }
  });
}

// 监听弹窗关闭，重置表单
watch(visible, (newVal) => {
  console.log("AssignCardDialog visible changed to:", newVal);
  if (!newVal) {
    resetForm();
  } else {
    console.log("AssignCardDialog opened, selectedCards:", props.selectedCards);
    // 弹窗打开时获取省份列表
    getProvinceList();
    // 获取默认考生类型列表（可以根据需要调整）
    getExamTypeList("湖南省"); // 默认获取湖南省的考生类型
    // 获取代理商列表
    getAgentListData();
    // 自动填充卡号段
    autoFillCardRange();
  }
});

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

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