<template>
  <div class="addAndEdit">
    <div class="formContent">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="学校logo" prop="sm_logo">
          <file-upload-progress v-if="tinymceShow" v-model:part="ruleForm.sm_logo" :limit="1" accept=".png,.jpg,.jpeg" :size-limit="2*1024">
            <template #default>
              <div class="flex_center w-65px h-65px border border-dashed border-hex-E4E6E8 bg-hex-F9F9F9 text-hex-9D9AB9">
                <i-akar-icons:plus class="text-xl" />
              </div>
            </template>
            <template #tip>
              <div class="mt-2">支持格式：jpg,png,jpeg（2M以内） 建议尺寸1:1</div>
            </template>
          </file-upload-progress>
        </el-form-item>
        <div class="flex">
          <el-form-item label="学校名称" prop="sm_name">
            <el-input v-model="ruleForm.sm_name" />
          </el-form-item>
          <el-form-item label="学校电话" prop="sm_lxr_contact">
            <el-input v-model="ruleForm.sm_lxr_contact" />
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="级别" prop="sm_period">
            <el-select v-model="ruleForm.sm_period" placeholder=" " size="default">
              <el-option v-for="item in periodData" :key="item.v" :label="item.n" :value="item.v" />
            </el-select>
          </el-form-item>
          <el-form-item label="学校地址" prop="sm_address">
            <el-input v-model="ruleForm.sm_address" />
          </el-form-item>
        </div>
        <el-form-item label="学校视频" prop="sm_video">
          <file-upload-progress v-if="tinymceShow" v-model:part="ruleForm.sm_video" :limit="1" accept=".mp4">
            <template #default>
              <div class="flex_center w-65px h-65px border border-dashed border-hex-E4E6E8 bg-hex-F9F9F9 text-hex-9D9AB9">
                <i-akar-icons:plus class="text-xl" />
              </div>
            </template>
            <template #tip>
              <div class="mt-2">支持格式：mp4</div>
            </template>
          </file-upload-progress>
        </el-form-item>
        <el-form-item label="学校风采" prop="sm_brief">
          <tinymce-vue v-if="tinymceShow" :modelValue="ruleForm.sm_brief" @update:modelValue="handleUpdate"></tinymce-vue>
        </el-form-item>
        <div class="btnDiv">
          <el-button @click="emit('update', 2)">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { schoolAdd, schoolEdit, schoolDetail } from "./api";
import { ElMessage } from "element-plus";

const timestamp = ref(Date.now());

const props = defineProps({
  periodData: {
    type: Array,
    default: [],
  },
  current: {
    type: String,
    default: "",
  },
  tinymceShow: {
    type: Boolean,
    default: true,
  },
});

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  sm_logo: "",
  sm_name: "",
  sm_lxr_contact: "",
  sm_period: "",
  sm_address: "",
  sm_brief: "",
  sm_video: "",
});

const rules = reactive<FormRules>({
  sm_logo: [{ required: true, message: "请上传学校logo", trigger: "submit" }],
  sm_name: [{ required: true, message: "请输入学校名称", trigger: "blur" }],
  sm_lxr_contact: [
    { required: true, message: "请输入学校电话", trigger: "blur" },
  ],
  sm_period: [{ required: true, message: "请选择级别", trigger: "change" }],
  sm_address: [{ required: true, message: "请输入学校地址", trigger: "blur" }],
  sm_brief: [{ required: true, message: "请输入学校风采", trigger: "blur" }],
});

const emit = defineEmits(["update", "load"]);
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let data = {
        school_main: ruleForm,
      };
      emit("load", true);
      if (props.current == "") {
        await schoolAdd(data);
      } else {
        data = Object.assign({ id: props.current }, data);
        await schoolEdit(data);
      }
      emit("load", false);
      ElMessage.success("保存成功！");
      emit("update", 1);
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

watch(
  () => props.current,
  (newVal, oldVal) => {
    if (newVal != "") {
      initDetailInfo(newVal);
    } else {
      resetForm(ruleFormRef.value);
    }
  },
  { immediate: true }
);

async function initDetailInfo(id: string) {
  emit("load", true);
  let data = await schoolDetail({ id });
  let key: keyof typeof ruleForm;
  for (key in ruleForm) {
    ruleForm[key] = data.one_info[key];
  }
  emit("load", false);
}

function handleUpdate(data: string) {
  ruleForm.sm_brief = data;
}
</script>

<style lang="scss" scoped>
.addAndEdit {
  .flex {
    width: 100%;
    display: flex;
  }
  .formContent {
    .flex {
      .el-form-item {
        flex: 1;
        .el-select {
          width: 100%;
        }
      }
    }
    .btnDiv {
      text-align: center;
    }
  }
}
</style>