<template>
  <div>
    <el-dialog title="问卷管理" v-model="dialogVisible">
      <div>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          label-width="120px"
          status-icon
        >
          <el-form-item
            label="问卷名称"
            prop="name"
            :rules="[
              {
                required: true,
                message: '请输入问卷名称',
                trigger: 'blur'
              }
            ]"
          >
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="问卷封面">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="simpleImgHttpUpload"
            >
              <img v-if="ruleForm.cover" :src="ruleForm.cover" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="问卷介绍：" prop="ruleForm.description">
            <div class="border border-solid border-gray-200">
              <Toolbar
                :editor="editorRef"
                :defaultConfig="{}"
                mode="default"
                class="border-b border-solid border-gray-200"
              />
              <div class="h-96">
                <Editor
                  v-model="ruleForm.description"
                  :defaultConfig="editorConfig"
                  mode="default"
                  @onCreated="editorCreated"
                />
              </div>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSubmit(ruleFormRef)"
              >确定</el-button
            >
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {
  shallowRef,
  ref,
  reactive,
  computed,
  defineProps,
  defineEmits,
  watch
} from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import { request, uploadToOSS } from "@/utils";
import type { UploadProps } from "element-plus";

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => {}
  }
});
const emits = defineEmits(["update:show", "success"]);
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  name: "",
  cover: "",
  description: ""
});

const editorRef = shallowRef();
const editorCreated = editor => {
  editorRef.value = editor;
};

const editorConfig = {
  placeholder: '请输入内容....',
  MENU_CONF: {
    uploadImage: {
      // 自定义上传
      async customUpload(file, insertFn) {
        console.log(file);
        // file 即选中的文件
        const url = await uploadToOSS(file, file.name);
        // 最后插入图片
        insertFn(url, 'image');
      }
    }
  }
};
const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(n) {
    emits("update:show", n);
  }
});

watch(
  () => dialogVisible.value,
  n => {
    if (n) {
      if (props.rowData.id) {
        ruleForm.value.name = props.rowData.name;
        ruleForm.value.cover = props.rowData.cover;
        ruleForm.value.description = props.rowData?.description;
      }
    } else {
    }
  }
);

const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
  console.log(rawFile);

  if (!["image/png", "image/jpeg"].includes(rawFile.type)) {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

const simpleImgHttpUpload = options => {
  console.log("options", options);
  uploadToOSS(options.file, options.file.name).then(resp => {
    ruleForm.value.cover = resp;
  });
};
const onSubmit = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid, fields) => {
    if (!valid) return;
    let params = ruleForm.value;
    request
      .post("/surveyService/mechanism/survey/update", {
        ...params,
        id: props.rowData.id
      })
      .then(resp => {
        ElMessage.success(resp.message);
        dialogVisible.value = false;
        emits("success");
      });
  });
};
const onReset = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.resetFields();
};
</script>
<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.ql-editor {
  min-height: 200px;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
