<template>
  <el-dialog
    title="直接开卡"
    v-model="visible"
    width="500px"
    append-to-body
    align-center
    :center="true"
    :destroy-on-close="true"
  >
    <div class="apply-card-content">
      <el-form
        ref="applyCardFormRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <!-- 卡号段 -->
        <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="schoolId">
          <el-select
            v-model="form.schoolId"
            placeholder="请选择学校"
            :disabled="!form.province"
            style="width: 100%"
          >
            <el-option
              v-for="school in campusList"
              :key="school.id"
              :label="school.name"
              :value="school.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          <svg-icon
            icon-class="lightning"
            class="mr-1"
            style="font-size: 14px"
          />
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import {getAgentList, requestOpenCard} from "@/api/dz/cards";
import { listUniversity } from "@/api/dz/school";
import { associateCampus, getCampusSchoolList } from "@/api/dz/cards";
import {getPaperProvinces} from "@/api/dz/papers.js";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  selectedCards: {
    type: Array,
    default: () => [],
  },
});

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

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

const applyCardFormRef = ref();
const loading = ref(false);
const provinceList = ref([]); // 省份列表
const agentList = ref([]); // 代理商列表
const schoolList = ref([]);
const campusList = ref([]);

const form = ref({
  agentId: null,
  beginCardNo: "",
  endCardNo: "",
  schoolId: null,
});

const rules = {
  province: [{ required: true, message: "省份不能为空", trigger: "change" }],
  beginCardNo: [
    { required: true, message: "开始卡号不能为空", trigger: "blur" },
  ],
  endCardNo: [{ required: true, message: "结束卡号不能为空", trigger: "blur" }],
  schoolId: [{ required: true, message: "学校不能为空", trigger: "change" }],
};


// 获取代理商列表
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 getProvinceList() {
  try {
    const response = await getPaperProvinces();
    if (response.code === 200) {
      provinceList.value = response.data || [];
    }
    campusList.value = []
  } catch (error) {
    console.error("获取省份列表失败:", error);
  }
}

// 获取校区列表
async function getCampusListData() {
  try {
    const response = await getCampusSchoolList({ campus: false, location: form.value.province, pageNum: 1, pageSize: 1000 });
    if (response.code === 200) {
      campusList.value = response.data || [];
    }
  } catch (error) {
    console.error("获取校区列表失败:", error);
  }
}

// 获取所有学校列表
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 autoFillCardRange() {
  if (props.selectedCards && props.selectedCards.length > 0) {
    const cardNos = props.selectedCards
      .map((card) => card.cardNo || card.id)
      .filter((cardNo) => cardNo && cardNo !== "未知")
      .sort();

    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 resetForm() {
  form.value = {
    beginCardNo: "",
    endCardNo: "",
    agentId: null,
    schoolId: null,
  };
}

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

// 提交申请
async function handleSubmit() {
  applyCardFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        const begin = form.value.beginCardNo;
        const end = form.value.endCardNo;
        const schoolId = form.value.schoolId;
        const province = form.value.province;
        const agentId = form.value.agentId;

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

        await requestOpenCard(agentId, province, schoolId, begin, end);
        emit("success", "申请开卡成功!");
        visible.value = false;
        resetForm();
      } catch (error) {
        console.error("申请开卡失败:", error);
        emit("confirm", { error: error.message });
      } finally {
        loading.value = false;
      }
    }
  });
}

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

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

<style scoped>
.apply-card-content {
  padding: 20px 0;
}

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