<script setup>
import { ref, reactive, onMounted, watch } from "vue";

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

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

import { Plus } from "@element-plus/icons-vue";

import { getSupplier, addSupplier, updateSupplier } from "@/api/supplier.js";

const formType = ref("insert");

const loading = ref(false);

const formRef = ref(null);
const form = ref({
  id: 0,
});

onMounted(async () => {
  if (props.editid) {
    let res = await getSupplier(props.editid);
    if (res.code === 200) {
      form.value = res.data;
      formType.value = "update";
    }
  }
});

const rules = ref({
  imageurl: [{ required: true, message: "供應商LOGO必需要有", trigger: 'blur' }],
  name: [{ required: true, message: "供應商名稱必填", trigger: 'blur' }],
})

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

import { Cropper } from 'vue-advanced-cropper';
import "vue-advanced-cropper/dist/style.css";

const crop = ref({
  show: false,
  img: null,
  ratio: 3.012,
})

const myCrop = ref(null)

const beforeAvatarUpload = (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
  // }
  crop.value.show = true

  crop.value.img = URL.createObjectURL(rawFile);

  return false;
}

const onCrop = () => {
  const { canvas } = myCrop.value.getResult();
  if (canvas) {
    const imgFile = new FormData();
    canvas.toBlob(async (blob) => {
      let ufile = new File([blob], "image.jpg");
      imgFile.append("fileType", "IMAGE");
      imgFile.append("file", ufile);

      crop.value.show = false;

      loading.value = true;

      let res = await uploadFile('/supplier/uploadSupplierImage', imgFile);

      if (res.code === 200) {
        form.value.imageurl = res.data;
        ElMessage.success('上傳成功');
      } else {
        ElMessage.error('上傳失敗');
      }
      loading.value = false;
      
    }, "image/jpeg");
  }

  return;
};

const handleClose = () => {
  crop.value.show = false
}

// END: 圖片剪裁


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 updateSupplier(form.value);
        message = "修改成功.";
      } else {
        res = await addSupplier(form.value);
        message = "新增成功.";
      }

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

<template>
  <div>
    <el-card>
      <el-form ref="formRef" :model="form" status-icon :rules="rules" label-width="120px">
        <el-form-item label="供應商LOGO" prop="imageurl">
          <el-upload class="avatar-uploader" action="#" accept="image/*" :show-file-list="false" :auto-upload="true"
            :on-success="handleAvatarSuccess" :before-upload="(file) => beforeAvatarUpload(file)">
            <img v-if="form.imageurl" :src="form.imageurl" class="avatar" id="imageurl" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <!-- <template #tip>
              <small class="el-upload__tip"> ※ 請上傳500kb以內jpg檔案。</small>
            </template> -->
          </el-upload>
        </el-form-item>
        <el-form-item label="供應商名稱(繁)" prop="name1">
          <el-input v-model="form.name1" />
        </el-form-item>
        <el-form-item label="供應商名稱(簡)" prop="name2">
          <el-input v-model="form.name2" />
        </el-form-item>
        <el-form-item label="供應商名稱(英)" prop="name3">
          <el-input v-model="form.name3" />
        </el-form-item>
      </el-form>
    </el-card>
    <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>

  <div>
    <el-dialog
      v-model="crop.show"
      title="Tips"
      :before-close="handleClose"
    >
      <div class="cropper-section" v-if="crop.show">
      <div class="crop-area">
        <cropper class="cropper" ref="myCrop" :src="crop.img" :stencil-props="{
          aspectRatio: crop.ratio,
        }" :auto-zoom="true" />
      </div>
      <div class="crop-btn">
          <el-button type="primary" size="small" text @click="handleClose">取消</el-button>
          <el-button type="primary" size="small" @click="onCrop">剪裁</el-button>
      </div>
    </div>
    </el-dialog>    
  </div>

</template>

<style lang="less" scoped>
.avatar-uploader .avatar {
  width: 250px;
  height: 83px;
  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: 250px;
  height: 83px;
  text-align: center;
}

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

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