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

import { getParentCateList, getCategory, addCategory, updateCategory } from "@/api/category";

// import { getAminUser, addAdminUser, updateAdminUser } from "@/api/adminuser";

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,
  parent_id: 0,
});

const options = ref([]);

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

  let pcateRes = await getParentCateList();
  if (pcateRes.code === 200) {
    options.value = pcateRes.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
  }
});


const rules = reactive({
  username: [{ 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.6,
})

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('/cate/uploadImage', 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 updateCategory(form.value);
        message = "修改成功.";
      } else {
        res = await addCategory(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-form ref="formRef" :model="form" status-icon :rules="rules" label-width="120px">
      <el-form-item label="分類名稱" prop="name">
        <el-input v-model="form.name" type="text" v-if="form.parent_id === 0"/>
        <el-input v-model="form.name" :rows="4" type="textarea" v-else/>
      </el-form-item>
      <el-form-item label="上級分類">
        <el-select v-model="form.parent_id" class="m-2" placeholder="Select">
          <el-option label="最上層" :value="0" />
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="類別圖片" prop="imageurl" v-if="form.parent_id === 0">
          <el-upload class="avatar-uploader" 
          action="#" 
          accept="image/*" 
          :show-file-list="false" 
          :auto-upload="true"
          :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>
          </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>

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

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

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