<template>
  <div>
    <el-dialog
      title="上传文件"
      :visible.sync="localuploadingPOP"
      width="400px"
      @close="handleClose"
    >
      <div class="UPcondition">
        <p>文件类型:</p>
        <el-select
          v-model="superior"
          clearable
          @change="handleSelectClick"
          placeholder="请选择"
        >
          <el-option
            v-for="item in superiorOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div class="UPcondition" v-show="JXshow">
        <p>机型信息:</p>
        <el-select v-model="jixingval" clearable placeholder="请选择">
          <el-option
            v-for="item in millTypeCodeOptions"
            :key="item.millTypeCode"
            :label="item.machineTypeCode"
            :value="item.millTypeCode"
          >
          </el-option>
        </el-select>
      </div>
      <div v-if="fileShow">
        <el-alert
          title="请点击模板下载文件附件"
          type="success"
          :closable="false"
        >
        </el-alert>
        <p class="model-center" @click="download">模板下载</p>
        <el-upload
          class="upload-demo"
          :file-list="fileList"
          drag
          action
          :multiple="false"
          :before-upload="beforeUpload"
          :limit="1"
          :auto-upload="false"
          :on-change="handleOnChange"
          accept=".xlsx"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            只能上传xlsx文件，且不超过5MB
          </div>
        </el-upload>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="filesubmit" size="small"
            >提交</el-button
          >
        </span>
      </div>
      <div v-if="resourceShow">
        <el-upload
          class="uploaddemo2"
          :file-list="resourcefileList"
          :action="uploadUrl"
          :multiple="false"
          :before-upload="resourcebeforeUpload"
          :limit="1"
          :auto-upload="false"
          :on-change="resourcehandleOnChange"
          accept=".jpg,.png,.pdf,.docx"
          ref="upload"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <div class="el-upload__tip" slot="tip">
          只能上传jpg,png,pdf,docx文件，且不超过5MB
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="resourcefilesubmit" size="small"
            >提交</el-button
          >
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  powerWordContractImportData,
  saveWindFieldResource,
  getWindEngineMillList,
} from "@/api/ledger.js";

export default {
  props: {
    uploadingPOP: {
      type: Boolean,
      default: false,
    },
    rowdata: {
      type: Object,
      default: () => {},
    },
    AllTemplateurlDR: {
      type: Object,
      default: () => {},
    },
  },
  computed: {
    localuploadingPOP: {
      get() {
        return this.uploadingPOP;
      },
      set(value) {
        // 在这里不进行任何修改
      },
    },
  },
  data() {
    return {
      superior: "",
      uploadUrl: process.env.VUE_APP_UPLOAD,
      superiorOptions: [
        {
          value: "1",
          label: "合同功率曲线",
        },
        {
          value: "2",
          label: "资源文件",
        },
      ],
      fileList: [],
      resourcefileList: [],
      fileShow: true,
      resourceShow: false,
      globalFileList: [],
      succeed: {},
      jixingval: "",
      millTypeCodeOptions: [],
      JXshow: false,
    };
  },
  watch: {
    superior(newVal) {
      if (newVal === "1" || newVal === "") {
        this.fileShow = true;
        this.resourceShow = false;
      } else {
        this.fileShow = false;
        this.resourceShow = true;
      }
    },
  },
  created() {
    this.relevancy();
  },
  methods: {
    rowStyle() {
      return "text-align:center";
    },
    // 下载附件
    download() {
      if (this.AllTemplateurlDR.htPower) {
        const link = document.createElement("a");
        link.href = this.AllTemplateurlDR.htPower;
        link.download = ""; // 可以设置默认下载文件名
        link.target = "_blank"; // 新窗口打开
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } else {
      }
    },
    beforeUpload(fileList) {
      const isXLSX =
        fileList.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      if (!isXLSX) {
        this.$message.error("只能上传xlsx文件");
      }
      const isLt5MB = fileList.size / 1024 / 1024 < 5;
      if (!isLt5MB) {
        this.$message.error("文件大小不能超过5MB");
      }

      return isXLSX && isLt5MB;
    },
    handleOnChange(fileList) {
      this.globalFileList = fileList.raw;
      console.log(fileList);
    },

    // 附件提交
    filesubmit() {
      let filedata = {
        fieldCode: this.rowdata.fieldCode,
        file: this.globalFileList,
        millTypeCode: this.jixingval,
        machineTypeCode: this.millTypeCodeOptions.find(
          (option) => option.millTypeCode === this.jixingval
        ).machineTypeCode,
      };

      if (
        !this.superior ||
        this.superior === "" ||
        this.superior === undefined
      ) {
        this.$message({
          message: "请选择文件类型",
          type: "warning",
        });
        return;
      }
      let contractPowerCurveOption = this.superiorOptions.find(
        (opt) => opt.label === "合同功率曲线"
      );
      if (
        contractPowerCurveOption &&
        this.superior === contractPowerCurveOption.value &&
        this.jixingval === ""
      ) {
        this.$message({
          message: "请选择机型信息",
          type: "warning",
        });
        return;
      }
      if (!filedata.file || filedata.file.length === 0) {
        this.$message({
          message: "上传附件不能为空",
          type: "warning",
        });
        return;
      }
      powerWordContractImportData(filedata).then((res) => {
        this.$message.success("上传成功");
        // this.$emit("handleClose", false, "tolead");
        this.$emit("handleClose", false, "uploadingPOP");
      });
    },

    handleClose() {
      this.superior = "";
      this.fileList = [];
      this.jixingval = "";
      this.globalFileList = null;
      this.$emit("handleClose", false, "uploadingPOP");
    },

    // 资源文件
    resourcebeforeUpload(file) {
      const allowedTypes = [
        "image/jpeg", // jpg
        "image/png", // png
        "application/pdf", // pdf
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // docx
      ];
      const isAllowedType = allowedTypes.includes(file.type);
      if (!isAllowedType) {
        this.$message.error("只能上传jpg, png, pdf, docx文件");
        return false; // 阻止文件上传
      }
      const isLt5MB = file.size / 1024 / 1024 < 5;
      if (!isLt5MB) {
        this.$message.error("文件大小不能超过5MB");
        return false; // 阻止文件上传
      }

      return true; // 允许文件上传
    },
    resourcehandleOnChange(file, fileList) {
      this.globalFileList = file.raw;
      this.succeed = file.response;
      // 手动触发上传
      if (file.status === "ready") {
        this.$refs.upload.submit();
      }
    },

    resourcefilesubmit() {
      let filedata = {
        fieldCode: this.rowdata.fieldCode,
        fileName: this.globalFileList.name,
        resourceUrl: this.succeed.data,
        type: this.globalFileList.type,
      };
      if (
        !this.superior ||
        this.superior === "" ||
        this.superior === undefined
      ) {
        this.$message({
          message: "请选择文件类型",
          type: "warning",
        });
        return;
      }
      if (filedata.resourceUrl == "") {
        this.$message({
          message: "请先上传附件在点击提交",
          type: "warning",
        });
        return;
      }
      saveWindFieldResource(filedata)
        .then((res) => {
          this.$message.success("上传成功");
          this.$emit("handleClose", false, "tolead");
        })
        .catch((error) => {});
    },
    handleSelectClick(value) {
      const selectedOption = this.superiorOptions.find(
        (option) => option.value === value
      );
      if (selectedOption && selectedOption.label === "合同功率曲线") {
        this.JXshow = true;
      } else {
        this.JXshow = false;
      }
    },

    // 选择机型
    async relevancy() {
      try {
        const res = await getWindEngineMillList();
        this.millTypeCodeOptions = res.data;
      } catch (error) {
        console.error("Error fetching wind engine mill list:", error);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.UPcondition {
  display: flex;

  p {
    width: 74px;
    text-align: right;
    line-height: 40px;
  }

  .el-select {
    width: 100%;
    margin-bottom: 20px;
  }

  .el-input {
    margin-bottom: 20px;
  }
}

.model-center {
  color: #409eff;
  cursor: pointer;
  line-height: 40px;
  height: 40px;
  font-size: 14px;
}
.uploaddemo2 {
  width: 360px;
  height: 200px;
  border: 1px dashed rgb(196, 196, 196);
  text-align: center;
  padding-top: 50px;
  .el-icon-upload {
    font-size: 50px;
  }
}
.uploaddemo2:hover {
  border: 1px dashed #409eff;
}
</style>
