<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { FormRules, ElForm } from "element-plus";
import { onBeforeUnmount, reactive, shallowRef, ref } from "vue";
import { httpUpdate, httpAdd } from "/@/api/system/updates";
import { responseHandle } from "/@/utils/responseHandle";
import { useNav } from "/@/layout/hooks/useNav";
import { SYS_TYPE_OPTIONS } from "/@/config/status";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
enum FROM_TYPE {
  create = "create",
  edit = "edit",
  view = "view"
}
const mode = "default";
const { logout } = useNav();
const showModel = ref(false);
const currentMenuId = ref("");
const TYPE = ref<FROM_TYPE>(FROM_TYPE.create);
const formRef = ref<InstanceType<typeof ElForm>>(null);
const loading = ref(false);
const titleType = ref("");
const editorRef = shallowRef();
const emit = defineEmits(["reload"]);

const editorConfig = { placeholder: "请输入内容..." };
const initform = {
  sys_type: "",
  version: "",
  title: "",
  addtime: "",
  content: ""
};
const ruleForm = ref({ ...initform });
const rules = reactive<FormRules>({
  sys_type: [{ required: true, trigger: "change", message: "请选择类型" }],
  version: [{ required: true, trigger: "bulr", message: "请输入版本号" }],
  title: [{ required: true, trigger: "bulr", message: "请输入标题" }],
  addtime: [{ required: true, trigger: "change", message: "请选择时间" }],
  content: [{ required: true, trigger: "bulr", message: "请输入内容" }]
});

const handleCreated = editor => {
  editorRef.value = editor;
};
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
async function show(node: any, id: string, isCreate: string) {
  Object.keys(ruleForm.value).forEach(key => {
    // if (key === "menuid") {
    //   ruleForm.value[key] = menuid;
    // } else {
    ruleForm.value[key] =
      isCreate === "create"
        ? initform[key]
          ? initform[key] + ""
          : ""
        : node[key]
        ? node[key] + ""
        : "";
    // }
  });
  console.log(ruleForm.value);
  TYPE.value = isCreate;
  switch (TYPE.value) {
    case "create":
      titleType.value = "新建版本信息";
      break;
    case "edit":
      titleType.value = "编辑版本信息";
      break;
    case "view":
      titleType.value = "版本信息详情";
      break;
    default:
      titleType.value = "新建版本信息";
  }

  showModel.value = true;
}

function handleUpdate() {
  const data = {
    ...ruleForm.value
  };

  return {
    data,
    api: httpUpdate
  };
}

function handleCreate() {
  const data = {
    ...ruleForm.value
  };

  return {
    data,
    api: httpAdd
  };
}

function handleSave() {
  formRef.value.validate(async vaild => {
    if (vaild) {
      if (loading.value) return;
      const handler =
        TYPE.value === FROM_TYPE.create ? handleCreate : handleUpdate;

      loading.value = true;
      const { api, data } = handler();
      const { message, code } = await api(data);
      loading.value = false;
      responseHandle({
        code,
        message,
        logout,
        handler: () => {
          showModel.value = false;
          emit("reload");
        }
      });
    }
  });
}

defineExpose({
  show,
  changeCurrentMenuId: (id: string) => (currentMenuId.value = id)
});
</script>

<template>
  <el-dialog
    v-model="showModel"
    :close-on-press-escape="false"
    center
    append-to-body
    destroy-on-close
    :width="'1040px'"
    :title="titleType"
    v-loading="loading"
  >
    <el-form
      ref="formRef"
      :model="ruleForm"
      :rules="rules"
      label-width="90px"
      style="margin-top: -10px"
      class="demo-ruleForm"
      status-icon
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="类型" prop="sys_type">
            <el-select
              v-model="ruleForm.sys_type"
              style="width: 100%"
              :disabled="TYPE === 'view'"
              placeholder="类型"
            >
              <el-option
                v-for="(si, sii) in SYS_TYPE_OPTIONS"
                :key="'action_code' + si.id + sii"
                :label="si.label"
                :value="si.id + ''"
              />
            </el-select> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="版本号" prop="version">
            <ElInput
              placeholder="版本号"
              :disabled="TYPE === 'view'"
              v-model="ruleForm.version"
            /> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="标题" prop="title">
            <ElInput
              placeholder="标题"
              :disabled="TYPE === 'view'"
              v-model="ruleForm.title"
            /> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="时间" prop="addtime">
            <ElDatePicker
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model="ruleForm.addtime"
              type="datetime"
              :disabled="TYPE === 'view'"
              style="width: 100%"
              placeholder="时间"
            /> </el-form-item
        ></el-col>
        <el-col :span="24">
          <el-form-item label="内容" prop="content">
            <div style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :disabled="TYPE === 'view'"
                :mode="mode"
              />
              <Editor
                style="height: 400px; overflow-y: hidden"
                v-model="ruleForm.content"
                :disabled="TYPE === 'view'"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
              />
            </div> </el-form-item
        ></el-col>
      </el-row>
      <div class="flex justify-end">
        <el-button
          v-if="TYPE !== 'view'"
          :loading="loading"
          :disabled="loading"
          type="primary"
          @click="handleSave"
          >保存</el-button
        >
        <el-button @click="showModel = false">取消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
