<script setup>
import { ref, reactive, onMounted } from "vue";
import { Plus } from "@element-plus/icons-vue";

import { getActivity, addActivity, updateActivity } from "@/api/activity";
import { uploadFile } from "@/utils/request";

const props = defineProps({
  editid: {
    type: Number,
    default: 0,
  },
});

const emit = defineEmits(["close"]);

const formType = ref("insert");

const loading = ref(false);
const formRef = ref(null);
const form = ref({
  id: 0,
  title1: "",
  title2: "",
  title3: "",
  imageList: [],
});

onMounted(async () => {
  if (props.editid) {
    let res = await getActivity(props.editid);
    if (res.code === 200) {
      form.value = res.data;
      formType.value = "update";
      fileList.value = res.data.imageList.map(item => {
        return {
          uid: item.uid,
          url: item.url,
        }
      })
    }
  }
});

const rules = reactive({
  // username: [{ required: true, message: "管理員帳號必填", trigger: 'blur' }],
})

const cancelForm = () => {
  emit("close", false);
};

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      let res;
      let message;
      if (formType.value === "update") {
        form.value.id = props.editid;
        res = await updateActivity(form.value);
        message = "修改成功.";
      } else {
        res = await addActivity(form.value);
        message = "新增成功.";
      }

      if (res.code === 200) {
        ElMessage({
          message: message,
          type: 'success',
        });
        emit("close", true);
      }
    } else {
      ElMessage({
        message: "操作失敗.",
        type: 'error',
      });
      return false
    }
  })
};

// 圖片上傳

const fileList = ref([
])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleUploadImage = async (file) => {
  const formData = new FormData();
  formData.append('file', file.file);

  loading.value = true;
  let res = await uploadFile('/activity/uploadImage', formData);
  if (res.code === 200) {

    form.value.imageList.push({
      uid: file.file.uid,
      url: res.data,
    });
    // form.value.avatar = res.data;
  } else {
    ElMessage.error('上傳失敗');
  }
  loading.value = false;
}

const handleRemove = (uploadFile, uploadFiles) => {
  // 移除form.value.imageList中符合的項目
  form.value.imageList = form.value.imageList.filter(item => item.uid !== uploadFile.uid);

}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
</script>

<template>
  <div>
    <el-form 
      ref="formRef" 
      :model="form" 
      status-icon 
      :rules="rules" 
      label-width="120px">
      <el-form-item label="標題(繁)" prop="title">
          <el-input v-model="form.title1" />
      </el-form-item>
      <el-form-item label="標題(簡)" prop="title">
          <el-input v-model="form.title2" />
      </el-form-item>
      <el-form-item label="標題(英)" prop="title">
          <el-input v-model="form.title3" />
      </el-form-item>
      <el-form-item label="活動照片" prop="content">
        <el-upload
          v-model:file-list="fileList"
          action="#"
          :http-request="handleUploadImage"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

      </el-form-item>
    </el-form>
    <div class="demo-drawer__footer" style="text-align: right;">
      <el-button @click="cancelForm">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitForm(formRef)">{{
        loading ? '提交中 ...' : '確認'
      }}</el-button>
    </div>
  </div>
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>  
</template>

<style lang="less" scoped>
:deep(.ck-editor__editable_inline) {
    height: 400px;
}
</style>