<template>
  <a-modal :open="state.visible" :title="options.title" :maskClosable="false" :confirmLoading="state.confirmLoading"
    :width="900" @cancel="cancelHandel">
    <a-row>
      <a-col :xs="24" :md="24" :style="{ height: '600px' }">

        <vue-cropper ref="cropper"
        :img="options.img"
        :info="true"
        :autoCrop="options.autoCrop"
        :autoCropWidth="options.autoCropWidth"
        :autoCropHeight="options.autoCropHeight"
        :fixedBox="options.fixedBox"
        :mode="cropperMode"
        @realTime="realTime">
        </vue-cropper>
      </a-col>
     <!-- <a-col :xs="24" :md="12" :style="{ height: '250px' }">
        <div
          :class="
            options.previewsCircle
              ? 'avatar-upload-preview'
              : 'avatar-upload-preview_range'
          "
        >
          <img :src="state.previews.url" :style="state.previews.img" />
        </div>
      </a-col> -->
    </a-row>
    <template v-slot:footer>
      <a-button key="back" @click="cancelHandel">取消</a-button>
      <a-button key="submit" type="primary" :loading="state.confirmLoading" @click="okHandel">保存</a-button>
    </template>
  </a-modal>
</template>

<script>
  import axios from "axios";
  import {
    upload
  } from "@/api/module/oss";
  import {
    VueCropper
  } from 'vue-cropper';
  import 'vue-cropper/dist/index.css';
    import {
    message
  } from '@hwork/ant-design-vue';
  //import { domainName } from "@/config/index";  // 后台服务器的域名
  import {
    reactive,
    createVNode,
    ref,
    toRaw
  } from 'vue';
  export default {
    components: {
      VueCropper
    },
    props: {
      //图片存储在oss上的上级目录名
      imgType: {
        type: String,
        default: "",
      },
      fileName: {
        type: String, // 文件名
        default: "",
      },
      cropperMode: { // 图片渲染方式
        type: String,
        default: 'contain'
      }
    },
    emit: ["cropper-no", "cropper-ok"],
   setup(props,context) {
      const cropper = ref();
      const options = reactive({
        img: "", //裁剪图片的地址
        autoCrop: true, //是否默认生成截图框
        autoCropWidth: 180, //默认生成截图框宽度
        autoCropHeight: 180, //默认生成截图框高度
        fixedBox: true, //是否固定截图框大小 不允许改变
        previewsCircle: false, //预览图是否是原圆形
        title: "修改图片",
      });
      const state = reactive({
        confirmLoading: false,
        visible: false,
        previews: {},
      })
      // 添加检查逻辑
      if (!options || !options.title) {
        console.error('Options or title is not defined.');
      }
      const edit = function(record) {
        const { options } = this;
        state.visible = true;
        this.options = Object.assign({}, options, record);
      }

      // 取消截图
      const cancelHandel = function() {
        state.confirmLoading = false;
        state.visible = false;
        context.emit("cropper-no");
      }
      // base 64 转成二进制文件流
      const dataURLtoFile = function(dataurl, filename) {
        var arr = dataurl.split(","),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {
          type: mime
        });
      }

      // 确认截图
      const okHandel = function() {
        console.log("okHandel 确认截图")
        const that = this;
        state.confirmLoading = true;
        //context.emit("close", false);
        // 获取截图的base64 数据
        //this.$refs.cropper.edit(target);
        cropper.value.getCropData((data) => {
          //nsole.log("data", data)
          // 处理裁剪后的图片，例如上传到服务器
          message.success('裁剪成功');
          let file = dataURLtoFile(data, props.fileName);
          let formData = new window.FormData();
          formData.append("file", file);
          //加工文件提交
          upload(formData).then((response) => {
            console.log("response.data",response.data)
            if (response.success) {
              message.success({
                content: '保存成功',
                key: "上传头像",
                duration: 1
              }).then(() => {
                context.emit("cropper-ok",response.data);
                console.log("保存成功 then")
              });
            } else {
              message.error({
                content: response.msg,
                key: "上传头像",
                duration: 1
              }).then(() => {
                // cancel();
              });
            }
          });
          state.visible = false;
          state.confirmLoading = false;
        });
        // this.$refs.cropper.getCropData((data) => {
        //   let file = this.dataURLtoFile(data, this.fileName);
        //   let formData = new window.FormData();
        //   formData.append("uploadFile", file);
        //   axios
        //     //.post(`${domainName}/admin/files/upload/images`, formData)
        //     .post(`127.0.0.1:9292/admin/files/upload/images`, formData)
        //     .then((res) => {
        //       if (res.data.code == 200) {
        //         state.visible = false;
        //         state.confirmLoading = false;
        //         this.$emit("cropper-ok", res.data.data);
        //       }
        //     });
        // });
      };
      //移动框的事件
      const realTime = function(data) {
        console.log("realTime", data)
        state.previews = data;
      };
      return {
        cropper,
        state,
        options,
        edit,
        cancelHandel,
        okHandel,
        realTime,
        dataURLtoFile
      };
    },

  };
</script>

<style lang="less" scoped>
  .avatar-upload-preview_range,
  .avatar-upload-preview {
    position: absolute;
    top: 50%;
    transform: translate(50%, -50%);
    width: 100%;
    height: 100%;
    border-radius: 50%;
    box-shadow: 0 0 4px #ccc;
    overflow: hidden;

    img {
      background-color: red;
      height: 100%;
    }
  }

  .avatar-upload-preview_range {
    border-radius: 0;
  }
</style>
