<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 { getBanner, addBanner, updateBanner } from "@/api/home.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 getBanner(props.editid);
    if (res.code === 200) {
      form.value = res.data;
      formType.value = "update";
    }
  }
});

// const validatePass = (rule, value, callback) => {
//   if (form.cfm_password !== '') {
//     if (!formRef.value) return
//     formRef.value.validateField('cfm_password', () => null)
//   }
//   callback()
// }

// const validatePass2 = (rule, value, callback) => {
//   console.log('value', value);
//   if (value && value !== form.value.password) {
//       callback(new Error("二個密碼不一致!"))
//   }else{
//     callback()
//   }
// }

const rules = ref({
  imageurl1: [{ required: true, message: "電腦版背景圖必填", trigger: 'blur' }],
  imageurl2: [{ 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: 2,
})

const myCrop = ref(null)

const beforeAvatarUpload = (rawFile, type) => {
  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);
  if(type === 1){
    crop.value.type = 1;
    crop.value.ratio = 2;
  }else{
    crop.value.type = 2;
    crop.value.ratio = 0.5;
  }

  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('/index/uploadBannerImage', imgFile);

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

  return;
};

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

const onClose = () => {
  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 updateBanner(form.value);
        message = "修改成功.";
      } else {
        res = await addBanner(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="標語">
          <el-input v-model="form.slogon" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.describe" />
        </el-form-item>
        <el-form-item label="電腦版背景圖" prop="imageurl1">
          <el-upload class="avatar-uploader" action="#" accept="image/*" :show-file-list="false" :auto-upload="true"
            :on-success="handleAvatarSuccess" :before-upload="(file) => beforeAvatarUpload(file, 1)">
            <img v-if="form.imageurl1" :src="form.imageurl1" class="avatar1" id="imageurl1" />
            <el-icon v-else class="avatar-uploader-icon1">
              <Plus />
            </el-icon>
            <!-- <template #tip>
              <small class="el-upload__tip"> ※ 請上傳500kb以內jpg檔案。</small>
            </template> -->
          </el-upload>
        </el-form-item>
        <el-form-item label="手機版背景圖" prop="imageurl2">
          <el-upload class="avatar-uploader" action="#" accept="image/*" :show-file-list="false" :auto-upload="true"
            :on-success="handleAvatarSuccess" :before-upload="(file) => beforeAvatarUpload(file, 2)">
            <img v-if="form.imageurl2" :src="form.imageurl2" class="avatar2" id="imageurl1" />
            <el-icon v-else class="avatar-uploader-icon2">
              <Plus />
            </el-icon>
            <!-- <template #tip>
              <small class="el-upload__tip"> ※ 請上傳500kb以內jpg檔案。</small>
            </template> -->
          </el-upload>
        </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 .avatar1 {
  width: 178px;
  height: 89px;
  display: block;
}

.avatar-uploader .avatar2 {
  width: 89px;
  height: 178px;
  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-icon1 {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 89px;
  text-align: center;
}

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

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

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