<template>
  <el-dialog
    :title="title"
    v-model="showDia"
    width="1200px"
    append-to-body
    class="dialog_box"
    :style="{ overflowY: 'auto', overflowX: 'hiden', maxHeight: '80%' }"
  >
    <el-form
      ref="diaRef"
      :model="form"
      label-width="100px"
      v-loading="loading"
      :rules="rules"
      :inline="true"
    >
      <el-row :gutter="12">
        <el-col :span="8">
          <el-form-item label="家长姓名:" prop="name">
            <el-input
              maxlength="20"
              placeholder="请输入"
              clearable
              v-model="form.name"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系电话:" prop="phone">
            <el-input
              maxlength="100"
              placeholder="请输入"
              clearable
              v-model="form.phone"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="称谓:" prop="sysFamilyDictValue">
            <el-select
              v-model="form.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-row>
      <el-form-item label="工作单位:" class="work_input" prop="workUnit">
        <el-input
          :rows="1"
          maxlength="200"
          type="textarea"
          placeholder="请输入"
          v-model="form.workUnit"
        />
      </el-form-item>
      <h2>关联学生</h2>
      <div class="relate_student">
        <template v-for="(i, index) in form.stuList" :key="index">
          <div class="relate_student_item">
            <span class="name">
              <span v-if="!useUserStore().showAllTenant" style="color: red"
                >*</span
              >
              关联学生{{ index + 1 }}:
            </span>
            <el-form-item
              v-if="useUserStore().showAllTenant"
              label="学校名称"
              :rules="rules.tenantId"
              :prop="`stuList[${index}][tenantId]`"
            >
              <SchoolSelect
                v-model="i.tenantId"
                @updateData="updateSchool(index)"
              />
            </el-form-item>
            <el-form-item
              :rules="rules.stuId"
              :prop="`stuList[${index}][stuId]`"
              class="student_select"
            >
              <el-select
                v-model="i.stuId"
                filterable
                placeholder="请输入年级或班级或学号或姓名进行搜索选择"
                style="width: 240px"
                remote
                reserve-keyword
                remote-show-suffix
                :remote-method="(val) => remoteMethod(val, index)"
                :loading="searchloading"
                class="student_opt"
                @focus="handleShowStudentList(index)"
              >
                <el-option
                  v-for="item in relativeStudentList[index]"
                  :key="item.id"
                  :label="`${item.gradeName}/${item.className}/${item.stuNo}/${item.stuName}`"
                  :value="item.id"
                >
                  <span>{{ item.gradeName }}</span
                  >/<span>{{ item.className }}</span
                  >/ <span>{{ item.stuNo }}</span
                  >/
                  <span>{{ item.stuName }}</span>
                </el-option>
              </el-select>
              <div class="delete_btn" @click="handleDeleteFamily(index)">
                <Delete style="width: 2em; height: 2em" />
              </div>
            </el-form-item>
          </div>
        </template>
        <div class="add_btn" @click="handleAddStudent">
          <span> <Plus style="width: 1em; height: 1em" />添加 </span>
        </div>
      </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 { ElMessage } from "element-plus";
import { validatePhone } from "@/utils/validate";
import {
  addPatriarchApi,
  updatePatriarchApi,
  getPatriarchDetailsApi,
  getStudentsInfoApi,
} from "@/api/smartCampus/index";
import useUserStore from "@/store/modules/user";
import { computed, watch } from "vue";
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  detailInfo: {
    type: Object,
  },
  selectOption: {
    type: Object,
  },
});
const emits = defineEmits(["update:modelValue", "success", "cancel"]);
const { proxy } = getCurrentInstance();
const loading = ref(false);
const searchloading = ref(false); //搜索加载
const form = ref({});
const title = ref();

const relativeStudentList = ref([]); //关联学生
const rules = ref({
  name: [{ required: true, message: "家长姓名不能为空", trigger: "blur" }],
  phone: [
    { required: true, message: "联系电话不能为空", trigger: "blur" },
    {
      required: true,
      validator: validatePhone,
      trigger: "blur",
    },
  ],
  sysFamilyDictValue: [
    { required: true, message: "称谓不能为空", trigger: "change" },
  ],
  tenantId: [
    { required: true, message: "学校名称不能为空", trigger: "change" },
  ],
  stuId: [{ required: true, message: "关联学生不能为空", trigger: "change" }],
});
const chooseClassGrade = ref({
  chooseClass: "",
  chooseGrade: "",
});

const showDia = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emits("update:modelValue", val);
  },
});

// 更新学校
async function updateSchool(index) {
  form.value.stuList[index].stuId = "";
  relativeStudentList.value[index] = await fetchStudentInfo({
    tenantId: form.value.stuList[index].tenantId,
  });
  if (relativeStudentList.value[index].length === 0) {
    ElMessage.warning("当前学校暂无添加学生");
  }
}
//重置
function reset() {
  form.value = {
    id: undefined,
    name: undefined,
    phone: undefined,
    workUnit: undefined,
    stuName: undefined,
    sysFamilyDictValue: undefined,
    stuList: [
      {
        tenantId: undefined,
        stuId: undefined,
      },
    ],
  };

  proxy.resetForm("diaRef");
}
// 提交
function submitForm() {
  proxy.$refs["diaRef"].validate((valid) => {
    if (valid) {
      if (form.value.id !== undefined) {
        updatePatriarchApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          showDia.value = false;
          emits("success", false);
        });
      } else {
        addPatriarchApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          showDia.value = false;
          emits("success", false);
        });
      }
    }
  });
}

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

//删除家庭成员
function handleDeleteFamily(index) {
  form.value.stuList.splice(index, 1);
}
// 添加家庭成员
function handleAddStudent() {
  form.value.stuList.push({ stuId: undefined });
  if (!useUserStore().showAllTenant) {
    let len = form.value.stuList.length;
    relativeStudentList.value[len - 1] = relativeStudentList.value[0];
  }
}
// 获取关联学生
async function fetchStudentInfo(info) {
  let result = [];
  searchloading.value = true;
  let res = await getStudentsInfoApi({
    search: info.search,
    tenantId: info.tenantId,
  });
  result = res.rows;
  searchloading.value = false;
  return result;
}
function remoteMethod(query, index) {
  if (query)
    relativeStudentList.value[index] = fetchStudentInfo({
      search: query,
      tenantId: form.value.stuList[index].tenantId,
    });
}
// 下拉框出现或隐藏
function handleShowStudentList(index) {
  if (!form.value.stuList[index].tenantId && useUserStore().showAllTenant) {
    ElMessage.warning("请先选择学校名称");
  }
}
//
watch(
  () => props.detailInfo,
  async (val) => {
    if (val && val.id) {
      title.value = "家长管理/编辑";
      loading.value = true;
      getPatriarchDetailsApi(val.id)
        .then(async (res) => {
          if (res.code === 200) {
            let stuLength = res.data.stuList.length;
            if ("stuList" in res.data && stuLength) {
              if (useUserStore().showAllTenant) {
                // 超管
                for (let i in res.data.stuList) {
                  relativeStudentList.value[i] = await fetchStudentInfo({
                    tenantId: res.data.stuList[i].tenantId,
                  });
                }
              } else {
                const studentList = await fetchStudentInfo({});
                relativeStudentList.value = Array.from(
                  { length: stuLength },
                  () => studentList
                );
              }
              form.value = res.data;
            } else {
              form.value = {
                ...res.data,
                stuList: [
                  {
                    stuId: undefined,
                  },
                ],
              };
            }
            loading.value = false;
          }
        })
        .catch((err) => {
          loading.value = false;
        });
    } else {
      title.value = "家长管理/添加";
      if (!useUserStore().showAllTenant) {
        const studentList = await fetchStudentInfo({});
        relativeStudentList.value = Array.from(
          { length: 1 },
          () => studentList
        );
      }
      reset();
    }
  },
  {
    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 {
  :deep(.el-dialog) {
    height: 80%;
    overflow-y: auto;
  }
  .relate_student {
    &_item {
      display: flex;
      align-items: center;

      .name {
        display: inline-block;
        margin-bottom: 18px;
        color: #606266;
        font-weight: 500;
      }
    }
    .student_select {
      display: flex;
      align-items: center;
      margin-left: 16px;
      :deep(.el-select) {
        width: 370px !important;
      }

      .delete_btn {
        display: flex;
        margin-left: 20px;
        cursor: pointer;
      }
    }
    .add_btn {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 472px;
      margin-top: 24px;
      line-height: 36px;
      border: 1px dashed #d9d9d9;
      cursor: pointer;
    }
  }
  .work_input {
    width: 100%;
  }
}
</style>
