<template>
  <div class="dialog">
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="580px"
      @close="closeDialog()"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item prop="templateName" label="模板名称">
              <el-input v-model="formData.templateName" />
            </el-form-item>
            <el-form-item prop="viewThumbPath" label="预览图上传">
              <div>
                <el-upload
                  ref="uploadThumb"
                  :multiple="false"
                  class="avatar-uploader"
                  action="apis10/upload/bucketFile"
                  :headers="headers"
                  :show-file-list="false"
                  accept=".jpg,.png"
                  :on-exceed="handleExceedThumb"
                  :before-upload="beforeUploadThumb"
                  :on-success="successFileThumb"
                  :data="uploadParams"
                >
                  <template #trigger>
                    <el-button type="primary">
                      <i-ep-Picture />&nbsp;&nbsp;上传预览图
                    </el-button>

                    <span style="margin-left: 10px">
                      <img
                        v-if="formData.viewThumbPath"
                        height="60px"
                        style="
                          cursor: pointer;
                          border: 1px solid #ddd;
                          height: 60px;
                          max-width: 500px;
                        "
                        :src="formData.viewThumbPath"
                      />
                    </span>
                  </template>
                </el-upload>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button v-throttle type="primary" @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog()">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import {
  FormInstance,
  genFileId,
  UploadInstance,
  UploadProps,
  UploadRawFile,
  UploadUserFile,
} from "element-plus";
import { getToken } from "@/utils/js-cookie";
import {addDesignFont, getDesignTemplateImposition, updateDesignTemplateThumb} from "@/api/design";

const uploadThumb = ref<UploadInstance>();

const headers = ref({
  "X-ERP-User-From": 10,
  "X-ERP-DataSource-Id": getToken("dataBaseAlias"),
  "X-ERP-Supplier-Code": getToken("shardingKey"),
  "X-Token": getToken("shardingKey"),
});
const uploadParams = reactive({
  srcfilename: "",
  chunks: 1,
  bucketName: "webImage",
});
const handleExceedThumb: UploadProps["onExceed"] = (files) => {
  uploadThumb.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  uploadThumb.value!.handleStart(file);
};

function beforeUploadThumb(file) {
  console.log(file);
  uploadParams.srcfilename = file.name;
  return new Promise((resolve, reject) => {
    if (file.size > 307200) {
      ElMessage.warning(
        "图片大小不能大于300KB,请您注意图片的长和宽,网页图片的分辨率为72"
      );
      reject();
    } else {
      resolve(file);
    }
  });
}

function successFileThumb(res, file, fileList) {
  // console.log(res);
  // formData.posterLocationImage = res.fileLink
  formData.viewThumbPath = res.fileLink;

  ElMessage.success("上传成功");
}

let dialogVisible = ref(false);
let dialogTitle = ref("");
const formRef = ref<FormInstance>();
const emit = defineEmits(["dialogChange"]);
const formData = reactive({
  templateName: "",
  viewThumbPath: "",
  id: 0,
});
const rules = reactive({
  templateName: [{ required: true, message: "请输入名称", trigger: "blur" }],
});

function handleSubmit() {
  formRef.value.validate((valid: any) => {
    if (valid) {
      const itemId = formData.id;
      if (itemId) {
        //修改
        const postData = JSON.stringify(formData);
        const params = {
          template: postData,
        };
        updateDesignTemplateThumb(params).then((response) => {
          dialogVisible.value = false;
          if (response.httpCode == 200) {
            emit("dialogChange");
            ElMessage.success("操作成功");
          }
        });
      }
    }
  });
}

function getItemData(item) {
  const data = {
    id: item,
  };
  getDesignTemplateImposition(data).then((response) => {
    if (response.httpCode == 200) {
      const data = response.data;
      formData.id = data.id;
      formData.viewThumbPath = data.viewThumbPath;
      formData.templateName = data.templateName;
    }
  });
}

/**  重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formData.id = undefined;
}

/**关闭弹窗 */
function closeDialog() {
  dialogVisible.value = false;
  formRef.value.resetFields();
  formData.id = undefined;
}

defineExpose({
  dialogVisible,
  dialogTitle,
  getItemData,
  resetForm,
});
</script>
