<template>
  <div>
    <el-form ref="userEditForm" :model="form" :label-width="formLabelWidth" clearable>
      <el-row>
        <el-col :span="12">
          <el-form-item label="电话号码" :rules="rulePhone" prop="phone">
            <el-input type="text" v-model="form.phone" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名：" prop="realName" :rules="ruleRequired">
            <el-input
              type="text"
              v-model="form.realName"
              autocomplete="off"
              maxlength="20"
              :show-word-limit="true"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="职务：" prop="studentId">
            <el-input
              type="text"
              v-model="form.studentId"
              autocomplete="off"
              maxlength="16"
              :show-word-limit="true"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="任教信息：" prop="positionList" :rules="ruleRequired">
            <el-button type="success" @click="AddPosition()">添加职位</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="max-h-[400px] overflow-auto pb-1">
        <span class="pl-[120px]"
          >提示:任职信息所有项值<span class="text-red-500">必填</span>,
          如若查询不到对应班级,请先添加
        </span>
        <el-form :model="positionList" inline ref="positionEditForm">
          <div
            v-for="(position, index) in positionList"
            :key="index"
            class="subjectTagEnableDiv"
            style=""
          >
            <el-form-item>
              <el-button
                title="删除职位"
                class="mr-[5px]!"
                type="danger"
                :icon="Delete"
                @click="positionClose(position)"
                circle
              />
            </el-form-item>
            <el-form-item :prop="`${index}.positionLevel`" :rules="ruleRequired">
              <el-select
                :disabled="position.id != undefined"
                class="w-[100px]!"
                v-model="position.positionLevel"
                placeholder="类型"
                clearable
                filterable
              >
                <el-option
                  v-for="item in positionEnumList"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item :prop="`${index}.schoolId`" :rules="ruleRequired">
              <el-select
                :disabled="position.id != undefined"
                class="w-[250px]!"
                v-model="position.schoolId"
                placeholder="学校"
                clearable
                filterable
                @change="() => schoolChange(position)"
              >
                <el-option
                  v-for="item in schoolList"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item :prop="`${index}.grade`" :rules="ruleRequired">
              <el-select
                :disabled="position.id != undefined"
                class="w-[150px]!"
                v-model="position.grade"
                placeholder="年级"
                clearable
                filterable
                @change="() => gradeChange(position)"
              >
                <el-option
                  v-for="item in gradeList"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              :prop="`${index}.classId`"
              :rules="position.positionLevel > 3 ? ruleRequired : []"
            >
              <el-select
                :disabled="position.id != undefined"
                v-show="position.positionLevel > 3"
                class="w-[120px]!"
                v-model="position.classId"
                placeholder="班级"
                clearable
                filterable
              >
                <el-option
                  v-for="item in position.classList"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              :prop="`${index}.subjectId`"
              :rules="position.positionLevel == 5 ? ruleRequired : []"
            >
              <el-select
                :disabled="position.id != undefined"
                v-show="position.positionLevel == 5"
                class="w-[100px]!"
                v-model="position.subjectId"
                placeholder="学科"
                clearable
                filterable
              >
                <el-option
                  v-for="item in subjectList"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <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, reactive, onMounted } from "vue";
import {} from "@/api/user";
import {
  cloudSchoolCombo,
  getUserInfo,
  editUser,
  Position,
  getSchoolData,
  getClassCombo,
} from "@/api/userCenter";
import PositionForm from "./positionForm.vue";
import { getenum, getenumDic } from "@/api/enum";
import { PosititonIds } from "@/api/student";
import { ruleRequired, rulePhone } from "@/utils/rules";
import { ElMessage, FormInstance } from "element-plus";
import { ComboModel, gradeComboModel } from "@/components/hTable/hTable";
import { Check, Delete, Edit, Message, Search, Star } from "@element-plus/icons-vue";
import { de } from "element-plus/es/locales.mjs";

interface FormData {
  id: number;
  account: string;
  userType: number;
  level: number;
  passWord: string;
  realName: string;
  studentId: string;
  templateId: number;
  phone: string | number;
  cloudSchoolId: number;
  subjectLevels: any[];
  subjectLevel: Record<string, any>;
  positionIds: number[];
  positionList: Position[];
  positionFormIds?: number[];
  gLSubject?: number;
  gSubject1?: number;
  gSubject2?: number;
  idCard?: string;
  pointPenSN?: string;
}

interface DialogConfig {
  close: boolean;
  title: string;
  visible: boolean;
  width: string;
}
defineOptions({
  name: "UserEditForm",
});

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

const formLabelWidth = "120px";
const size = "small";
const loading = ref(false);

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 emit = defineEmits(["handlePagedCallback"]);
const userTypeList = ref<ComboModel[]>([]);
const userLevelList = ref<ComboModel[]>([]);
const subjectLEnum = ref<Record<string, string>>({});
const positionList = ref<Position[]>([]);
const CloudSchoolArr = ref<ComboModel[]>([]);
const Template = ref<any[]>([]);
const PositionFormIds = ref<number[]>([]);
const positionEditForm = ref<FormInstance>();

const schoolList = ref<ComboModel[]>([]);
const classList = ref<ComboModel[]>([]);
const gradeList = ref<ComboModel[]>(gradeComboModel());
const subjectList = ref<ComboModel[]>([]);
const positionEnumList = ref<ComboModel[]>([
  { text: "年级主任", value: 3 },
  { text: "班主任", value: 4 },
  { text: "科任老师", value: 5 },
]);
function schoolChange(p: Position) {
  p.graduationYear = null;
  p.grade = "";
  p.classId = null;
  p.subjectId = null;
  getClass(p);
}
function gradeChange(p: Position) {
  p.classId = null;
  p.subjectId = null;
  getClass(p);
}

function getClass(p: Position) {
  const data = {
    schoolId: p.schoolId || 0,
    graduationYear: p.graduationYear || 0,
    grade: p.grade,
  };
  getClassCombo(data).then((res) => {
    if (res.code === 200) {
      p.classList = res.data;
    }
  });
}

const defaultSubjectLevel = reactive({
  UserId: 0,
  Level: 0,
  Subject1: 0,
  Subject2: 0,
  Subject3: 0,
  Subject4: 0,
  Subject5: 0,
  Subject6: 0,
  Subject7: 0,
  Subject8: 0,
  Subject9: 0,
  CreatePositionId: 1,
});

const form = ref<FormData>({
  id: props.id,
  account: "",
  userType: 2,
  level: 0,
  passWord: "",
  realName: "",
  studentId: "",
  templateId: 0,
  phone: "",
  cloudSchoolId: 0,
  positionList: [],
  subjectLevels: [],
  subjectLevel: { ...defaultSubjectLevel },
  positionIds: [],
  positionFormIds: [],
});

const dialog = reactive<DialogConfig>({
  close: false,
  title: "",
  visible: false,
  width: "1200px",
});

const customeRules = reactive({
  mobile: [
    { required: false, message: "手机号必填", trigger: "blur" },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: "手机号码格式不正确",
      trigger: "blur",
    },
  ],
});

function positionClose(p: Position) {
  positionList.value = positionList.value.filter((s) => s != p);
}

const AddPositionArr: Position[] = [];
function AddPosition() {
  let p = {
    userId: form.value.id,
    schoolId: null,
    enable: false,
    graduationYear: null,
    gradeLevel: "",
    classId: null,
    subjectId: null,
    positionType: 2,
    positionLevel: null,
    status: true,
  };
  let p1 = (p as unknown) as Position;
  form.value.positionList.push(p1);
  AddPositionArr.push(p1);
  positionList.value.push(p1);
}

const handlePagedCallback = () => {
  emit("handlePagedCallback");
};
const userEditForm = ref<FormInstance>();
const handleSubmitForm = async () => {
  try {
    const valid1 = await userEditForm.value.validate();
    const valid = await positionEditForm.value.validate();
    if (!valid || !valid1) return;
  } catch (error) {
    ElMessage.warning("表单验证未通过,请检查!");
    return;
  }
  try {
    loading.value = true;
    debugger;
    const postIdArr = positionList.value.map((s) => s.id).filter((s) => s != null);

    const addPArr = positionList.value
      .filter((s) => s.id == null)
      .map((s) => {
        return {
          positionLevel: s.positionLevel,
          subjectId: s.subjectId,
          schoolId: s.schoolId,
          classId: s.classId,
          positionType: 2,
          gradeLevel: s.grade[0],
          graduationYear: parseInt(s.grade.slice(1, 5)),
        };
      });
    if (addPArr.length > 0) {
      const resPId = await PosititonIds(addPArr);
      if (
        resPId.code != 200 ||
        resPId.data.length == 0 ||
        resPId.data.length != addPArr.length
      ) {
        ElMessage.warning("校验添加的职位数据异常,请删除后重新选择!");
        return;
      }
      postIdArr.push(...resPId.data);
    }

    const formData = {
      ...form.value,
      account: form.value.phone || "",
      positionIds: postIdArr,
    };

    const res = await editUser(formData);
    loading.value = false;
    if (res.code === 200) {
      ElMessage.success("操作成功");
      handlePagedCallback();
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    ElMessage.error("请求失败!" + (error.message ?? JSON.stringify(error)));
    loading.value = false;
  }
};

const handleResetForm = () => {
  Object.assign(form, {
    id: props.id,
    account: "",
    userType: 1,
    level: 0,
    passWord: "",
    realName: "",
    studentId: "",
    subjectLevels: [],
    subjectLevel: { ...defaultSubjectLevel },
    positionIds: [],
    idCard: "",
    phone: "",
    cloudSchoolId: "",
    pointPenSN: "",
  });
  positionList.value = [];
};
const fetchInitData = async () => {
  // 用户层次
  const levelRes = await getenum("StudentLevelEnum");
  userLevelList.value = levelRes.data;

  const typeRes = await getenum("UserTypeEnum");
  userTypeList.value = typeRes.data;

  schoolList.value = (await getSchoolData()).data;
  subjectList.value = (await getenum("SubjectEnum")).data.filter((s) => s.value < 10);

  // // 云校
  // const schoolRes = await cloudSchoolCombo();
  // if (schoolRes.code === 200) {
  //   CloudSchoolArr.value = schoolRes.data;
  // }

  const enumDicRes = await getenumDic("SubjectEnum");
  subjectLEnum.value = enumDicRes.data;
};

const fetchFormData = () => {
  handleResetForm();
  if (props.id !== 0) {
    getUserInfo(props.id).then((res) => {
      if (res.code === 200) {
        if (res.data.SubjectLevel && res.data.SubjectLevel.CreatePositionId) {
          delete res.data.SubjectLevel.CreatePositionId;
        }

        positionList.value = res.data.positions
          .filter((s: Position) => s.enable)
          .map((s: Position) => {
            if (s.positionLevel > 2)
              s.grade = (s.gradeLevel ?? s.grade[0]) + s.graduationYear + "届";
            return s;
          });
        Object.assign(form.value, {
          id: res.data.id,
          userType: res.data.userType,
          level: res.data.level,
          account: res.data.account,
          passWord: res.data.passWord,
          realName: res.data.realName,
          studentId: res.data.studentId,
          templateId: res.data.templateId,
          subjectLevels: res.data.subjectLevels,
          subjectLevel: res.data.subjectLevel,
          positionIds: res.data.positions
            .filter((s: any) => s.enable !== false)
            .map((w: any) => w.id),
          gLSubject: res.data.gLSubject,
          gSubject1: res.data.gSubject1,
          gSubject2: res.data.gSubject2,
          idCard: res.data.idCard,
          phone: res.data.phone,
          cloudSchoolId: res.data.cloudSchoolId,
          pointPenSN: res.data.pointPenSN,
          positionList: positionList.value ?? [],
        });
        positionList.value = res.data.positions
          .filter((s: Position) => s.enable)
          .map((s: Position) => {
            if (s.positionLevel > 2)
              s.grade = (s.gradeLevel ?? s.grade[0]) + s.graduationYear + "届";
            return s;
          });
        PositionFormIds.value = res.data.positions
          .filter((s: Position) => s.enable)
          .map((s: any) => s.id);
        for (const element of positionList.value) {
          if (element.positionLevel > 3) getClass(element);
        }
      }
    });
  }
};

const userTypeChange = () => {
  if (form.value.userType === 2) {
    form.value.studentId = "";
  }
  customeRules.mobile[0].required = form.value.userType !== 1;
};

const CheckPosition = () => {
  dialog.title = "选择职位";
  dialog.visible = true;
  PositionFormIds.value = positionList.value
    .filter((s) => s.enable !== false)
    .map((s) => s.id);
};

const handleCheckCallback = (checkPosition: Position[]) => {
  dialog.visible = false;
  positionList.value = checkPosition.map((s) => {
    s.enable = true;
    return s;
  });
  form.value.positionIds = positionList.value.map((w) => w.id);
};

onMounted(async () => {
  await fetchInitData();
  fetchFormData();
});
</script>

<style scoped>
.userform_ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.userform_ul li {
  margin-bottom: 10px;
}

.subjectTagEnableDiv {
  margin-top: 5px;
  padding-left: 120px !important;
}

.subjectTagEnableDiv .el-form-item {
  margin-right: 0px !important;
  margin-bottom: 10px !important;
}
.subjectTagEnableDiv .el-select {
  margin-right: 5px;
}

.classTag {
  background-color: #409eff;
  color: white;
}

.subjectTag {
  background-color: #909399;
  color: white;
}
.classTag {
  color: #a3bf08 !important;
  background-color: #f4fbd1 !important;
  border-color: #f4fbd1 !important;
}
.subjectTagEnableDiv {
  padding: 1px;
}
.subjectTag {
  color: #eb0de4 !important;
  background-color: #fbd9ff !important;
  border-color: #fbd9ff !important;
}

.userform_ul {
  list-style: none;
}
</style>
