<template>
  <div>
    <el-form
      ref="classesAddForm"
      :model="form"
      :label-width="formLabelWidth"
      clearable
    >
      <el-form-item label="学校" prop="SchoolId" :rules="ruleRequired">
        <el-select
          v-model="form.SchoolId"
          filterable
          placeholder="学校"
          style="width: 100%"
        >
          <el-option
            v-for="(item, id) in schoolList"
            :key="id"
            autocomplete="off"
            :label="item.text"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="年级" prop="Grade" :rules="ruleRequired">
        <el-select
          v-model="form.Grade"
          filterable
          placeholder="年级"
          style="width: 100%"
        >
          <el-option
            v-for="(item, i) in gradeList"
            :key="i"
            autocomplete="off"
            :label="item.text"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="班级类型" prop="Type" :rules="ruleRequired">
        <el-select
          v-model="form.Type"
          filterable
          placeholder="班级类型"
          style="width: 100%"
        >
          <el-option
            v-for="(item, i) in TypeList"
            :key="i"
            autocomplete="off"
            :label="item.text"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="选修方向">
        <el-col :span="24">
          <div style="display: flex; gap: 10px">
            <el-select
              v-model="form.Elective1"
              clearable
              filterable
              placeholder="历史/地理"
              style="width: 180px"
            >
              <el-option
                v-for="(item, id) in subject1"
                :key="id"
                :label="item.text"
                :value="item.value"
              />
            </el-select>

            <el-select
              v-model="form.Elective2"
              clearable
              filterable
              placeholder="小学科"
              style="width: 180px"
            >
              <el-option
                v-for="(item, id) in subject2"
                :key="id"
                :label="item.text"
                :value="item.value"
              />
            </el-select>

            <el-select
              v-model="form.Elective3"
              clearable
              filterable
              placeholder="小学科"
              style="width: 180px"
            >
              <el-option
                v-for="(item, id) in subject2"
                :key="id"
                :label="item.text"
                :value="item.value"
              />
            </el-select>
          </div>
        </el-col>
      </el-form-item>

      <el-form-item
        label="班级名称"
        v-if="isEdit"
        prop="Name"
        :rules="ruleRequired"
      >
        <el-select
          v-model="form.Name"
          filterable
          placeholder="班级名称"
          style="width: 100%"
        >
          <el-option
            v-for="(item, i) in ClassNameList"
            :key="i"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="添加班级" v-if="!isEdit">
        <el-col :span="21">
          <el-select
            v-model="form.Name"
            filterable
            placeholder="班级名称"
            style="width: 100%"
          >
            <el-option
              v-for="(item, i) in filteredClassNameList"
              :key="i"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-col>
        <el-col :span="1">
          <el-button type="success" @click="ClassNameAdd" round>添加</el-button>
        </el-col>
      </el-form-item>

      <el-form-item label="班级列表" :rules="ruleRequired" v-if="!isEdit">
        <span v-show="ClassNames.length === 0">暂未添加!</span>
        <el-tag
          v-for="tag in ClassNames"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="TagClose(tag)"
        >
          {{ tag }}
        </el-tag>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="loading" @click="handleSubmitForm">
          立即提交
        </el-button>
        <el-button @click="handleResetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance } from "element-plus";
import { getenum } from "@/api/enum";
import { hTableAPI } from "@/api/hTable";
import { ruleRequired } from "@/utils/rules";
import { addClasses } from "@/api/userCenter";
import { ComboModel } from "@/components/hTable/hTable";

interface Formdata {
  Id: number;
  Name: string;
  SchoolId: string;
  Grade: string;
  Type: number;
  Elective1: string;
  Elective2: string;
  Elective3: string;
}

const props = defineProps<{
  id: number;
}>();

const emit = defineEmits(["handlePagedCallback"]);

// 表单引用
const classesAddForm = ref<FormInstance>();

// 数据定义
const form = ref<Formdata>({
  Id: props.id,
  Name: "",
  SchoolId: "",
  Grade: "",
  Type: 0,
  Elective1: "",
  Elective2: "",
  Elective3: ""
});

const subject1 = ref<ComboModel[]>([
  { value: 4, text: "物理" },
  { value: 8, text: "历史" }
]);

const subject2 = ref<ComboModel[]>([
  { value: 5, text: "化学" },
  { value: 6, text: "生物" },
  { value: 9, text: "地理" },
  { value: 7, text: "政治" }
]);

const formLabelWidth = "120px";
const size = "small";
const loading = ref(false);
const ClassNames = ref<string[]>([]);
const ClassNameList = ref<string[]>([]);
const schoolList = ref<ComboModel[]>([]);
const TypeList = ref<ComboModel[]>([]);
const gradeList = ref<ComboModel[]>([]);

// 计算属性
const isEdit = computed(() => props.id > 0);
const filteredClassNameList = computed(() =>
  ClassNameList.value.filter(s => !ClassNames.value.includes(s))
);

// 方法
const TagClose = (tag: string) => {
  ClassNames.value = ClassNames.value.filter(t => t !== tag);
};

const ClassNameAdd = () => {
  if (form.value.Name === "") {
    ElMessage.error("添加的班级名称不能为空");
    return;
  }
  ClassNames.value.push(form.value.Name);
  form.value.Name = "";
};

const handlePagedCallback = () => {
  emit("handlePagedCallback");
};

const handleSubmitForm = async () => {
  debugger;
  if (props.id <= 0 || ClassNames.value.length < 1) {
    ElMessage.error("班级列表为空！");
    return;
  }

  if (!classesAddForm.value) return;

  await classesAddForm.value.validate(valid => {
    if (valid) {
      loading.value = true;
      let dataf = {
        ...form.value,
        Id: props.id,
        Name: ClassNames.value.join()
      };
      addClasses(dataf).then(res => {
        loading.value = false;
        if (res.code === 200) {
          ElMessage.success("操作成功");
          handlePagedCallback();
        } else {
          ElMessage.error(res.message);
        }
      });
    }
  });
};

const handleResetForm = () => {
  ClassNames.value = [];
  classesAddForm.value?.resetFields();
};

const SchoolApi = new hTableAPI("usercenter/back/schools");
const fetchInitdata = async () => {
  // 初始化班级列表
  ClassNameList.value = Array.from({ length: 500 }, (_, i) => `${i + 1}班`);

  // 获取年级枚举
  const gradeRes = await getenum("GradeEnum");
  gradeList.value = gradeRes.data.map((s: ComboModel) => ({
    text: s.text,
    value: s.text
  }));

  // 获取学校数据
  SchoolApi.querycombo({ TextName: "Name", ValueName: "Id" }).then(res => {
    if (res.code === 200) {
      schoolList.value = res.data;
    }
  });

  // 获取班级类型
  const typeRes = await getenum("ClassTypeEnum");
  TypeList.value = typeRes.data;
};

const fetchFormdata = () => {
  handleResetForm();
};

// 生命周期
onMounted(() => {
  fetchInitdata();
  fetchFormdata();
});

// 监听props变化
watch(
  () => props.id,
  newVal => {
    form.value.Id = newVal;
    fetchFormdata();
  }
);
</script>

<style scoped>
.el-tag {
  margin-top: 4px;
  margin-right: 10px;
}
</style>
