<template>
  <el-dialog
    :title="title"
    v-model="showDia"
    width="1200px"
    append-to-body
    class="dialog_box"
    :style="{ overflowX: 'hiden', overflowY: 'auto', maxHeight: '80%' }"
  >
    <el-form
      ref="diaRef"
      :model="form"
      label-width="100px"
      :rules="rules"
      :inline="true"
      v-loading="loading"
    >
      <h2>基础信息</h2>
      <el-row
        ><el-col :span="8">
          <el-form-item
            v-if="useUserStore().showAllTenant"
            label="学校名称"
            prop="tenantId"
          >
            <SchoolSelect
              v-model="form.tenantId"
              @updateData="handleUpdateSchool"
            /> </el-form-item></el-col
      ></el-row>
      <el-row :gutter="12">
        <el-col :span="8">
          <el-form-item label="学生姓名:" prop="stuName">
            <el-input
              maxlength="50"
              placeholder="请输入"
              clearable
              v-model="form.stuName"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学号:" prop="stuNo">
            <el-input
              placeholder="请输入"
              clearable
              v-model="form.stuNo"
              maxlength="18"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="性别:">
            <el-select
              v-model="form.sex"
              placeholder="请选择"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="dict in selectOption.sexOption"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="8">
          <el-form-item label="班级:">
            <el-tree-select
              v-model="form.classId"
              :data="gradeClassTreeList"
              :render-after-expand="false"
              :props="gradeDataTreeProps"
              style="width: 240px"
              @change="changeSelectTree"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学段:">
            <el-select
              v-model="form.education"
              placeholder="请选择"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="dict in selectOption.educationDict"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue * 1"
                >{{ dict.dictLabel }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出生日期:">
            <el-date-picker
              v-model="form.birthday"
              type="date"
              placeholder="请选择"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="8">
          <el-form-item label="身份证号:">
            <el-input
              maxlength="100"
              placeholder="请输入"
              clearable
              v-model="form.idNo"
              @blur="blurValidateIdNO"
            ></el-input>
            <span class="el-form-item__error" v-if="!validIDNO"
              >请输入正确的身份证号</span
            >
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="籍贯:">
            <el-input
              maxlength="100"
              placeholder="请输入"
              clearable
              v-model="form.origionPlace"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="政治面貌:">
            <el-input
              maxlength="50"
              placeholder="请输入"
              clearable
              v-model="form.politicsStatus"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="居住地址:" class="address_input">
        <el-input
          :rows="2"
          maxlength="200"
          type="textarea"
          placeholder="请输入"
          v-model="form.address"
        />
      </el-form-item>
      <h2>家庭成员信息</h2>
      <template v-for="(i, index) in form.scFamilyBo" :key="index">
        <div class="family_box">
          <div class="delete_btn" @click="handleDeleteFamily(index)">
            <Delete style="width: 2em; height: 2em" />
          </div>
          <el-row :gutter="12">
            <el-col :span="8">
              <el-form-item
                maxlength="50"
                label="家长姓名:"
                :prop="`scFamilyBo[${index}][name]`"
                :rules="rules.name"
              >
                <el-input
                  maxlength="100"
                  placeholder="请输入"
                  clearable
                  v-model="i.name"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="称谓:">
                <el-select
                  v-model="i.sysFamilyDictValue"
                  placeholder="请选择"
                  clearable
                  style="width: 200px"
                >
                  <el-option
                    v-for="dict in selectOption.relationOption"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="联系电话:"
                :prop="`scFamilyBo[${index}][phone]`"
                :rules="rules.phone"
              >
                <el-input
                  maxlength="100"
                  placeholder="请输入"
                  v-model="i.phone"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="工作单位:">
            <el-input
              maxlength="200"
              placeholder="请输入"
              v-model="i.workUnit"
              clearable
            ></el-input>
          </el-form-item>
        </div>
      </template>
      <div class="add_btn">
        <span @click="handleAddFamily">
          <Plus style="width: 1em; height: 1em" />添加家庭成员
        </span>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { cloneDeep } from "lodash-es";
import {
  validatePhone,
  validateIdNumber,
  validatePositiveNum,
} from "@/utils/validate";
import useUserStore from "@/store/modules/user";
import {
  updateStudentApi,
  addStudentApi,
  getRegionInfo,
  getStudentDetailsApi,
} from "@/api/smartCampus/index";
import { useFetchGradeClassTree } from "@/utils/dropDownData";
import { computed, watch } from "vue";
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  detailInfo: {
    type: Object,
  },
  selectOption: {
    type: Object,
  },
  gradeClassTree: {
    type: Array,
  },
});
const emits = defineEmits(["update:modelValue", "success", "cancel"]);
const { proxy } = getCurrentInstance();
const gradeClassTreeList = ref([]);
const gradeDataTreeProps = {
  label: "name",
  value: "id",
  children: "children",
};
const loading = ref(false);
const form = ref({});
const title = ref();
const validIDNO = ref(true); // 输入身份证时才校验
const regionsList = ref([]); //籍贯地区
const educationList = ref([]); //学段
const rules = ref({
  tenantId: [
    { required: true, message: "学校名称不能为空", trigger: "change" },
  ],
  stuName: [{ required: true, message: "学生姓名不能为空", trigger: "blur" }],
  stuNo: [{ required: true, message: "学号不能为空", trigger: "blur" }],
  sex: [{ required: true, message: "性别不能为空", trigger: "change" }],
  gradeId: [{ required: true, message: "年级不能为空", trigger: "change" }],
  classId: [{ required: true, message: "班级不能为空", trigger: "change" }],
  education: [{ required: true, message: "学段不能为空", trigger: "change" }],
  birthday: [
    { required: true, message: "出生日期不能为空", trigger: "change" },
  ],
  origionPlace: [{ required: true, message: "籍贯不能为空", trigger: "blur" }],
  politicsStatus: [
    { required: true, message: "政治面貌不能为空", trigger: "blur" },
  ],
  address: [{ required: true, message: "居住地址不能为空", trigger: "blur" }],
  name: [{ required: true, message: "家长姓名不能为空", trigger: "blur" }],
  sysFamilyDictValue: [
    { required: true, message: "称谓不能为空", trigger: "change" },
  ],
  phone: [
    { required: true, message: "联系电话不能为空", trigger: "blur" },
    {
      required: true,
      validator: validatePhone,
      trigger: "blur",
    },
  ],
});
const chooseClassGrade = ref({
  chooseClass: "",
  chooseGrade: "",
});
const regionsProps = ref({
  multiple: false,
  label: "name",
  value: "name",
  children: "childList",
});

const showDia = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emits("update:modelValue", val);
  },
});
// 输入身份证号时检验
function blurValidateIdNO() {
  if (!form.value.idNo || !form.value.idNo.replace(/\s*/g, "")) {
    validIDNO.value = true;
    return;
  }
  let reg =
    /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[X])$)$/;
  validIDNO.value = reg.test(form.value.idNo);
}
// 班级列表
async function fetchClassTree() {
  let arr = await useFetchGradeClassTree({
    tenantId: form.value.tenantId,
  });
  gradeClassTreeList.value = arr[0]?.children;
}
// 超管
function handleUpdateSchool() {
  form.value.classId = "";
  fetchClassTree();
}
// 选择班级
function changeSelectTree(val) {
  let arr = props.selectOption.gradeDataTree[0].children;
  for (let i in arr) {
    if (arr[i].children) {
      let _arr = arr[i].children;
      for (let o in _arr) {
        if (_arr[o].id === val) {
          form.value.gradeId = _arr[o].gradeId;
          break;
        }
      }
    } else {
      //有年级无班级
      if (arr[i].id === val) {
        form.value.gradeId = arr[i].id;
        form.value.classId = "";
      }
    }
  }
}

//重置
function reset() {
  form.value = {
    tenantId: undefined,
    id: undefined,
    stuName: undefined,
    stuNo: undefined,
    sex: undefined,
    gradeId: undefined,
    classId: undefined,
    birthday: undefined,
    idNo: undefined, //"446225200006060265"
    origionPlace: undefined,
    politicsStatus: undefined,
    address: undefined,
    deleteFlag: undefined,
    roomId: undefined,
    gradeName: undefined,
    className: undefined,
    status: undefined,
    groupId: undefined,
    subject: undefined,
    groupName: undefined,
    education: undefined,
    scFamilyBo: [],
  };
  proxy.resetForm("diaRef");
}
// 提交
function submitForm() {
  proxy.$refs["diaRef"].validate((valid) => {
    if (valid && validIDNO.value) {
      if (form.value.id !== undefined) {
        updateStudentApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          showDia.value = false;
          emits("success", false);
        });
      } else {
        addStudentApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          showDia.value = false;
          emits("success", false);
        });
      }
    }
  });
}

//取消
function cancel() {
  emits("cancel", false);
  reset();
}

//删除家庭成员
function handleDeleteFamily(index) {
  form.value.scFamilyBo.splice(index, 1);
}
// 添加家庭成员
function handleAddFamily() {
  form.value.scFamilyBo.push({
    name: undefined,
    sysFamilyDictValue: undefined,
    phone: undefined,
    workUnit: undefined,
  });
}

// function handleTree() {
//   let arr = props.selectOption.gradeDataTree[0]?.children;
//   for (let i in arr) {
//     if (arr[i].children) {
//       arr[i].disabled = false;
//     } else {
//       arr[i].disabled = true;
//     }
//   }
//   gradeClassTree.value = arr;
//   console.log("arr", gradeClassTree.value);
// }

watch(
  () => props.detailInfo,
  (val) => {
    if (val && val.id) {
      title.value = "学生管理/编辑";
      loading.value = true;
      reset();
      getStudentDetailsApi(val.id)
        .then((res) => {
          if (res.code === 200) {
            loading.value = false;
            if ("scFamilyBo" in res.data && res.data.scFamilyBo) {
              form.value = res.data;
            } else {
              form.value = {
                ...res.data,
                scFamilyBo: [],
              };
            }
            fetchClassTree();
          }
        })
        .catch((err) => {
          loading.value = false;
        });
    } else {
      title.value = "学生管理/添加";
      reset();
      fetchClassTree();
    }
  },
  {
    deep: true,
    immediate: true,
  }
);
</script>
<style>
.el-select-dropdown__list {
  max-width: 400px !important;
}
.el-dialog:not(.is-fullscreen) {
  overflow-x: hidden;
}
</style>
<style lang="scss" scoped>
:deep(.el-input) {
  .el-input__wrapper {
    width: 220px !important;
  }
}
.el-select {
  width: 220px !important;
}

.dialog_box {
  .family_box {
    margin-bottom: 12px;
    padding: 12px 12px 12px 6px;
    border: 1px solid #ccc;
    .delete_btn {
      display: flex;
      justify-content: flex-end;
      cursor: pointer;
    }
  }
  .address_input {
    width: 100%;
  }
  .add_btn {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 24px;
    span {
      cursor: pointer;
    }
  }
}
</style>
