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

import { useRouter, useRoute } from "vue-router";
const route = useRoute();
const router = useRouter();

import ClassicEditor from "ckeditor5-custom-build/build/ckeditor.js";
const editor = ClassicEditor;
const editorConfig = ref({
  simpleUpload: {
    // The URL that the images are uploaded to.
    uploadUrl: '/adminapi/article/uploadImage',
    // // Headers sent along with the XMLHttpRequest to the upload server.
    headers: {
      'X-CSRF-TOKEN': 'CSFR-Token',
      'Authorization': `${sessionStorage.getItem('token')}`
    }
  },
  image: {
    resize: true,
    toolbar: [
      "imageTextAlternative",
      "|",
      "imageStyle:alignLeft",
      "imageStyle:alignRight",
      "|",
      "imageStyle:alignBlockLeft",
      "imageStyle:block",
      "imageStyle:alignBlockRight",
    ],
    styles: [
      'full',
      'alignLeft',
      'alignRight',
    ],
  },
  // table: {
  //   // Set the palettes for tables.
  //   tableProperties: {
  //     defaultProperties: {
  //       width: '100%',
  //     },
  //   },
  // },
});

import { getProduct, addProduct, updateProduct } from "@/api/product";
import { getCateList } from "@/api/category";

const props = {
  emitPath: false,
}

const formType = ref("insert");

const CateOptions = ref([])

const loading = ref(false);
const formRef = ref(null);
const form = ref({
  id: 0,
  cat_id: 0,
  name: "",
  imageurl: "",
  description: "",
  content: ""
});

onMounted(async () => {
  let res = await getCateList();
  if (res.code === 200) {
    CateOptions.value = res.data.map((item) => {
      return {
        value: item.id,
        label: item.name,
        children: item.children.map((item2) => {
          return {
            value: item2.id,
            label: item2.name,
          };
        }),
      };
    });
  }

  if (route.query.id) {
    let res = await getProduct(route.query.id);
    if (res.code === 200) {
      form.value = res.data;
      formType.value = "update";
    } else {
      ElMessage({
        message: "取得資料失敗.",
        type: 'error',
      });
      router.push('/product/list');
    }
  }
});

const rules = reactive({
  name: [{ required: true, message: "產品名稱必填", trigger: 'blur' }],
  cat_id: [{ required: true, message: "產品類別必填", trigger: 'change' }],
})

const cancelForm = () => {
  router.push('/product/list');
};

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

      if (res.code === 200) {
        ElMessage({
          message: message,
          type: 'success',
        });
        router.push('/product/list');
      }
    } else {
      ElMessage({
        message: "操作失敗.",
        type: 'error',
      });
      return false
    }
  })
};

// START: 圖片上傳
import { uploadFile } from "@/utils/request";

const beforeUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/jpg') {
    ElMessage.error('圖片格式只能是jpeg/png/jpg!');
    return false;
  }
  // if (rawFile.size / 1024 / 1024 > 2) {
  //     ElMessage.error('檔案大小請勿超過2MB!')
  //     return false
  // }
  return true;
}

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

  loading.value = true;
  let res = await uploadFile('/product/uploadImage', formData);

  if (res.code === 200) {
    form.value.imageurl = res.data;
  } else {
    ElMessage.error('上傳失敗');
  }

  loading.value = false;
}

const handleUploadSuccess = (res, file) => {
  // if (res.code === 200) {
  //   form.value.imageurl = res.data;
  //   ElMessage.success('上傳成功');
  // } else {
  //   ElMessage.error('上傳失敗');
  // }
}
</script>

<template>
  <div class="main">
    <!-- Breadcrumb: Start -->
    <div class="breadcrumb-section">
      <div>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item> 產品管理 </el-breadcrumb-item>
          <el-breadcrumb-item> 產品表單 </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div>
        <el-button type="primary" @click="$router.back()">回產品列表</el-button>
      </div>
    </div>
    <!-- Breadcrumb: End -->

    <el-card>
      <el-form ref="formRef" :model="form" status-icon :rules="rules" label-width="120px">
        <el-form-item label="產品名稱" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="產品類別" prop="cat_id">
          <el-cascader v-model="form.cat_id" :options="CateOptions" :props="props" @change="handleChange" />
        </el-form-item>
        <el-form-item label="產品圖片" prop="imageurl">
          <el-upload class="avatar-uploader" action="#" accept="image/*" :http-request="handleUpload"
            :show-file-list="false" :auto-upload="true" :on-success="handleUploadSuccess"
            :before-upload="(file) => beforeUpload(file)">
            <img v-if="form.imageurl" :src="form.imageurl" class="avatar" id="imageurl" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="產品簡述" prop="description">
          <el-input type="textarea" v-model="form.description" :row="4" />
        </el-form-item>
        <div class="">
          <ckeditor :editor="editor" v-model="form.content" :config="editorConfig"></ckeditor>
        </div>
      </el-form>
      <div class="demo-drawer__footer" style="text-align: right;margin-top: 20px;">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submitForm(formRef)">{{
          loading ? '提交中 ...' : '確認'
        }}</el-button>
      </div>
    </el-card>
  </div>
</template>

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

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}

:deep(.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: 120px;
  height: 120px;
  text-align: center;
}

:deep(.el-dialog) {
  width: 40% !important;
}

.crop-btn {
  text-align: right;
  margin-top: 10px;
}
</style>