<template>
  <div class="contract">
    <div class="lay">
      <div class="flex">
        <el-button type="text">境内合同:</el-button>
        <el-button type="primary" icon="el-icon-upload " @click="openDialog(1)">
          上传境内合同
        </el-button>
        <el-button
          type="success"
          v-if="contractObj.domestic"
          @click="downloadWord(1)"
        >
          下载境内合同
        </el-button>
      </div>
      <div class="flex">
        <el-button type="text">境外合同:</el-button>
        <el-button
          type="danger"
          icon="el-icon-s-promotion"
          @click="openDialog(2)"
        >
          上传境外合同
        </el-button>
        <el-button
          type="success"
          v-if="contractObj.abroad"
          @click="downloadWord(2)"
        >
          下载境外合同
        </el-button>
      </div>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      @open="onOpen"
      @close="onClose"
      :title="dialogTitle"
    >
      <el-form ref="elForm" :model="formData" size="medium" label-width="120px">
        <el-form-item label="上传" prop="trip_info" required>
          <el-upload
            ref="field105"
            action=""
            :before-upload="wordBeforeUpload"
            :http-request="handlesAvatarSuccess"
            :on-success="handleWordSuccess"
            :on-error="handleUploadError"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :file-list="fieldFileList"
            accept=".pdf,.docx,.xlsx"
          >
            <el-button size="small" type="primary" icon="el-icon-upload"
              >点击上传</el-button
            >
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getContractListsApi,
  postSubmitContractApi,
  postDownloadContractApi,
} from "@/api/admin";
import { getToken } from "@/utils/auth";
export default {
  data() {
    return {
      contractObj: {},
      dialogVisible: false,
      dialogTitle: "",
      fieldFileList: [],
      formData: {
        domestic: "",
        abroad: "",
      },
      uploadPercent: 0,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async getList() {
      const res = await getContractListsApi();
      this.contractObj = res.data;
    },
    async downloadWord(type) {
      const res = await postDownloadContractApi();
      if (res.error === 0) {
        let fileUrl = type === 1 ? res.data.domestic : res.data.abroad;
        if (fileUrl) {
          fetch(fileUrl)
            .then((response) => response.blob())
            .then((blob) => {
              const link = document.createElement("a");
              const objectUrl = URL.createObjectURL(blob);
              link.href = objectUrl;
              link.download = fileUrl.split("/").pop(); // Extract filename from URL
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
              URL.revokeObjectURL(objectUrl);
            })
            .catch((error) => {
              this.$message({
                showClose: true,
                message: "下载失败",
                type: "error",
              });
              console.error("Download error:", error);
            });
        } else {
          this.$message({
            showClose: true,
            message: "暂无下载链接",
            type: "warning",
          });
        }
      }
      console.log(res, "下载合同");
    },
    onOpen() {},
    onClose() {
      this.$refs["elForm"].resetFields();
      this.$refs.field105.uploadFiles = []; // 删除该条数据
      this.fieldFileList = [];
      this.formData = {
        domestic: "",
        abroad: "",
      };
    },
    close() {
      console.log("1111", this.$refs.field105.uploadFiles);
      this.dialogVisible = false;
      this.$refs.field105.uploadFiles = []; // 删除该条数据
    },
    openDialog(num) {
      this.dialogTitle = num === 1 ? "境内合同" : "境外合同";
      this.dialogVisible = true;
    },
    async handelConfirm() {
      const isDomestic = this.dialogTitle === "境内合同";
      const fileField = isDomestic ? "domestic" : "abroad";
      const errorMessage = `请上传${isDomestic ? "境内" : "境外"}合同`;
      if (!this.formData[fileField]) {
        return this.$message.error(errorMessage);
      }

      const res = await postSubmitContractApi(this.formData);
      if (res.error === 0) {
        this.$message.success("上传成功");
        this.getList();
      }
      this.close();
      console.log(res, "wwww");
    },
    async handlesAvatarSuccess(file) {
      try {
        var formdata = new FormData();
        formdata.append("file", file.file);
        const res = await this.$axios.post("/admin/upload/index", formdata, {
          headers: {
            "Content-type": "multipart/form-data",
            "X-Token": getToken(),
          },
        });
        console.log(res, "收拾收拾");
        if (res.error === 0) {
          file.onSuccess(res);
        }
      } catch (error) {
        console.log(file, "error--handlesAvatarSuccess");
        let uid = file.file.uid;
        let idx = this.$refs.field105.uploadFiles.findIndex(
          (item) => item.uid === uid
        );
        this.$refs.field105.uploadFiles.splice(idx, 1);
        this.$message.error(`上传失败`);
      }
    },
    handleWordSuccess(res, file, fileList, index) {
      console.log(res, file, fileList, "成功了");
      if (res) {
        const isDomestic = this.dialogTitle === "境内合同";
        const fileUrl = `${window.location.protocol}//${window.location.host}${res.data}`;
        isDomestic
          ? (this.formData.domestic = fileUrl)
          : (this.formData.abroad = fileUrl);
        this.fieldFileList = [
          {
            name: file.name,
            uid: file.uid,
            url: fileUrl,
          },
        ];
        this.$message.success("上传成功");
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList, "handleRemove");
      this.formData.abroad = "";
      this.formData.domestic = "";
      this.fieldFileList.map((item, index) => {
        if (item.uid === file.uid) {
          this.fieldFileList.splice(index, 1);
        }
      });
    },
    handleUploadError(err, file) {
      this.$message.error(`上传失败: ${file.name}`);
      console.log(this.fieldFileList, "失败了");
      this.fieldFileList.map((item, index) => {
        if (item.uid === file.uid) {
          this.fieldFileList.splice(index, 1);
        }
      });
    },
    wordBeforeUpload(file) {
      const isRightType = [
        "application/pdf",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      ].includes(file.type);
      const isRightSize = file.size / 1024 / 1024 < 500;

      if (!isRightType) {
        this.$message.error("只允许上传 PDF、DOCX、XLSX 格式的文件");
      }
      if (!isRightSize) {
        this.$message.error("文件大小超过 500MB");
      }

      return isRightType && isRightSize;
    },
  },
};
</script>
<style scoped lang="scss">
.contract {
  padding-top: 20px;
  .lay {
    width: 100%;
    .flex {
      display: flex;
      align-items: center;
      padding-left: 20px;
      margin-bottom: 20px;
    }
    .word {
      margin: 0 50px;
    }
  }
}
</style>
