<script setup lang="ts">
import { ElForm, ElMessage, UploadProps } from "element-plus";
import { reactive, ref } from "vue";
import { receipt_rules } from "../../config/configs";
import { httpImageUpload, baseUrl } from "/@/api/other";
import { useResponseHandle } from "/@/hooks";
import { useUserStore } from "/@/store/modules/user";

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

const formData = reactive({
  return_image: "",
  return_time: ""
});

const types = ["image/png", "image/jpg", "image/bmp", "image/jpeg"];

const formRef = ref<InstanceType<typeof ElForm>>(null);
const responseHandle = useResponseHandle();
const userStore = useUserStore();

const onBeforeReturnImageUpload: UploadProps["beforeUpload"] = ({
  type,
  size
}) => {
  if (!types.includes(type)) {
    ElMessage.error("请上传jpg.png.bmp.jpeg类型图片");
    return false;
  }

  if (size / 1024 / 1024 > 1) {
    ElMessage.error("图片大小超过1M");
    return false;
  }
};

const handleRequeset: UploadProps["httpRequest"] = async ({ file }) => {
  const _formData = new FormData();
  _formData.append("img", file);
  _formData.append("token", userStore.token);
  const { message, code, data } = await httpImageUpload(_formData);

  responseHandle({
    message,
    code,
    handler: () => (formData.return_image = baseUrl + "/" + data[0].url)
  });
};

//付款回执 状态为4
const handlePaymentReceipt = () => {
  formRef.value.validate(
    isValid => isValid && emit("changeStatus", "4", formData)
  );
};
</script>

<template>
  <el-form ref="formRef" :model="formData" :rules="receipt_rules">
    <el-form-item label="回执图片" prop="return_image">
      <div>
        <el-upload
          class="upload"
          :before-upload="onBeforeReturnImageUpload"
          :http-request="handleRequeset"
          :show-file-list="false"
        >
          <img
            class="avatar"
            v-if="formData.return_image"
            :src="formData.return_image"
          />
          <div class="text" v-else>点击上传</div>
        </el-upload>
        <span>大小:小于1M; 尺寸:100*100; 类型:jpg.png.bmp.jpeg</span>
      </div>
    </el-form-item>

    <el-form-item label="回执时间" prop="return_time">
      <el-date-picker
        type="datetime"
        value-format="YYYY-MM-DD HH:mm:ss"
        v-model="formData.return_time"
        placeholder="请输入回执时间"
      />
    </el-form-item>

    <el-form-item w-full flex justify-end>
      <el-button type="primary" @click="handlePaymentReceipt">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<style lang="scss">
.upload {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px dashed var(--el-border-color);

  .text {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    font-size: 22px;
    line-height: 178px;
  }

  &:hover {
    border-color: var(--el-color-primary);
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
