<template>
  <div id="studentProjectWordDetail" v-loading="loading || downloadWordDig">
    <studentProjectWord
      v-if="isupload == 0"
      :wordData="wordData"
      :reversedMessage="reversedMessage"
			:signData="signData"
			:download="loading"
			@getFile="getFile"
			@getFile2="getFile2"
			@fileOption="fileOption"
			@fileOption2="fileOption2"
			@saveFile="saveFile"
    />
    <studentProjectWordShow
      ref="myChild"
      v-if="isupload != 0 || downloadWordDig"
      :downWordData="downWordData"
      :reversedMessage="reversedMessage"
			:signData="signData"
			:download="loading"
			@getFile="getFile"
			@fileOption="fileOption"
			@saveFile="saveFile"
    />
		<div style="position: fixed; bottom: 5%; right: 2%">
			<!-- <el-button
        style="width: 140px; margin: 10px"
        @click="downloadWordDig = true"
        type="primary"
        >下载文件</el-button
      > -->
      <!-- <el-button
        style="width: 140px; margin: 1cqh"
        @click="downloadDig = true"
        type="primary"
        >下载PDF</el-button
      > -->
      <el-button
        style="width: 120px; margin: 10px"
        @click="test"
        type="primary"
        v-if="isupload == 0"
        >保存修改</el-button
      >
    </div>
    <!-- <div
      style="
        width: 500px;
        margin: 20px auto;
        display: flex;
        justify-content: space-between;
      "
    >	
			<el-button
        style="width: 140px; margin: 20px auto"
        @click="downloadWordDig = true"
        type="primary"
        >下载文档(Word)</el-button
      >
      <el-button
        style="width: 140px; margin: 20px auto"
        @click="downloadDig = true"
        type="primary"
        >下载文档(PDF)</el-button
      >
      <el-button
        style="width: 120px; margin: 20px auto"
        @click="test"
        type="primary"
        v-if="isupload == 0"
        >立即修改</el-button
      >
    </div> -->
    <!-- 立即修改开始 -->
    <el-dialog
      title="立即修改"
      :visible.sync="updatedWordDig"
      width="600px"
      class="pageSubmitData"
    >
      <div class="deleteContent">确定提交修改?</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updatedWord" class="AllDialogBtn"
          >确认</el-button
        >
        <el-button @click="updatedWordDig = false" class="AllDialogBtn"
          >取消</el-button
        >
      </span>
    </el-dialog>
    <!-- 立即修改结束-->

    <!-- 下载文档开始 -->
    <el-dialog
      title="下载PDF"
      :visible.sync="downloadDig"
      width="600px"
      class="pageSubmitData"
    >
      <div class="deleteContent">确定下载文档?</div>
      <span slot="footer" class="dialog-footer" v-loading="loading">
        <el-button type="primary" @click="downloadPDFFile" class="AllDialogBtn"
          >确认</el-button
        >
        <el-button @click="downloadDig = false" class="AllDialogBtn"
          >取消</el-button
        >
      </span>
    </el-dialog>

		<el-dialog
      title="下载Word"
      :visible.sync="downloadWordDig"
      width="600px"
      class="pageSubmitData"
    >
      <div class="deleteContent">确定下载文档?</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="downloadWordFile" class="AllDialogBtn"
          >确认</el-button
        >
				<!-- <el-button type="primary" @click="downloadWord2" class="AllDialogBtn"
          >确认2</el-button
        > -->
        <el-button @click="()=>{downloadWordDig = false;loading = false}" class="AllDialogBtn"
          >取消</el-button
        >
      </span>
    </el-dialog>
    <!-- 下载文档结束-->
		<!-- 展示文件 -->
		<el-dialog
      title="展示文件"
      :visible.sync="showFile"
      top="1vh"
      width="80vw"
      append-to-body
    >
      <div class="showFileArea" style="height: 80vh">
        <!-- <vpdf v-if="/^\s*$/g.test(showFileUrl)&&showFileUrl.split('.')[showFileUrl.split('.').length-1]=='pdf'" :pdfUrl="showFileUrl"></vpdf> -->
        <div
          class="workd_media"
          style="width: 90%; height: 90%"
          v-if="videoDetail.sources"
        >
          <video-player
            class="video-player vjs-custom-skin"
            :playsinline="true"
            :options="videoDetail"
            @play="onPlayerPlay($event)"
            style="width: 90%; height: 90%; margin: 0 auto"
          ></video-player>
        </div>
        <vword
          style="width: 100%; height: 100%; overflow: auto"
          class="fullStyle"
          v-else-if="Wordss['type'] != 'pdf' && Wordss['name'] != '图片'"
          :pdfUrl="
            'https://view.officeapps.live.com/op/view.aspx?src=' + showFileUrl
          "
        ></vword>
        <vpdf
          style="width: 100%; height: 100%; overflow: auto"
          class="fullStyle"
          :pdfUrl="showFileUrl"
          v-else-if="Wordss['type'] == 'pdf'"
        ></vpdf>
        <img
          :src="showFileUrl"
          alt="图片哦"
          v-else-if="Wordss['name'] == '图片'"
          style="width: auto; height: auto; max-width: 100%; max-height: 100%"
        />
      </div>
      <!-- <el-button type="primary" size="mini" @click="downFile(showFileUrl)">下载文件</el-button> -->
    </el-dialog>
		<!-- 修改文件名称 -->
		<el-dialog
      title="修改名称"
      :visible.sync="dialogVisibleUpdateFile"
      :append-to-body="true"
      width="500px"
      class="dialog_diy"
    >
      <div
        style="
          width: 100%;
          display: flex;
          flex-direction: row;
          flex-wrap: nowrap;
          align-items: center;
          justify-content: center;
        "
      >
        <div style="min-width: fit-content">文件名称：</div>
        <el-input
          v-model="updateFile.fileName"
          placeholder="请输入要修改的名称"
        ></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleUpdateFile = false">取 消</el-button>
        <el-button type="primary" @click="updateFileName">确 定</el-button>
      </span>
    </el-dialog>

		<!-- 修改文件名称2-->
		<el-dialog
      title="修改名称"
      :visible.sync="dialogVisibleUpdateFile2"
      :append-to-body="true"
      width="500px"
      class="dialog_diy"
    >
      <div
        style="
          width: 100%;
          display: flex;
          flex-direction: row;
          flex-wrap: nowrap;
          align-items: center;
          justify-content: center;
        "
      >
        <div style="min-width: fit-content">文件名称：</div>
        <el-input
          v-model="updateFile.fileName"
          placeholder="请输入要修改的名称"
        ></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleUpdateFile2 = false">取 消</el-button>
        <el-button type="primary" @click="updateFileName2">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
      
    <script>
import { getNowDate } from "@/components/tool/Date.js";
import { getWord2 } from "@/components/tool/getWord2";
import studentProjectWord from "./studentProjectWord.vue";
import studentProjectWordShow from "./studentProjectWordShow.vue";
import { downloadPDF } from "@/components/tool/pdf";
import vpdf from "@/components/vpdf.vue";
import vword from "@/components/vword.vue";
import "@/components/common/aws-sdk-2.235.1.min.js"
const getFile = (url) => {
  return new Promise((resolve, reject) => {
    var credentials = {
        accessKeyId: "AKIATLPEDU37QV5CHLMH",
        secretAccessKey: "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",
      }; //秘钥形式的登录上传
      window.AWS.config.update(credentials);
      window.AWS.config.region = "cn-northwest-1"; //设置区域
      let url2 = url;
      let _url2 = "";
      if (
        url2.indexOf("https://view.officeapps.live.com/op/view.aspx?src=") != -1
      ) {
        _url2 = url2.split(
          "https://view.officeapps.live.com/op/view.aspx?src="
        )[1];
      } else {
        _url2 = url2;
      }
      var s3 = new window.AWS.S3({ params: { Bucket: "ccrb" } });
      let name = decodeURIComponent(_url2.split("https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/")[1])
      var params = {
        Bucket: "ccrb",
        Key: name
      };
      s3.getObject(params, function (err, data) {
        if (err) {
          console.log(err, err.stack)
          resolve({ data: 1 });
        }else {
          resolve({ data: data.Body });
          console.log(data); 
        }          // sxuccessful response

      });
  //     var credentials = {
  //       accessKeyId: "AKIATLPEDU37QV5CHLMH",
  //       secretAccessKey: "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",
  //     }; //秘钥形式的登录上传
  //     window.AWS.config.update(credentials);
  //     window.AWS.config.region = "cn-northwest-1"; //设置区域
  //     let url2 = url;
  //     let _url2 = "";
  //     if (
  //       url2.indexOf("https://view.officeapps.live.com/op/view.aspx?src=") != -1
  //     ) {
  //       _url2 = url2.split(
  //         "https://view.officeapps.live.com/op/view.aspx?src="
  //       )[1];
  //     } else {
  //       _url2 = url2;
  //     }
  //     let _this = this;

  //     var s3 = new window.AWS.S3({ params: { Bucket: "ccrb" } });
  //     let name = decodeURIComponent(_url2.split("https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/")[1])
  //     var params = {
  //       Bucket: "ccrb",
  //       Key: name
  //     };
  //     s3.getObject(params, function (err, data) {
  //       if (err) console.log(err, err.stack); // an error occurred
  //       else {
  //         let url = window.URL.createObjectURL(new Blob([data.Body]));
  //         let a = document.createElement("a");
  //         a.name = name;
  //         a.href = url;
  //         a.download = name;
  //         a.click();
  //         console.log(data);
  //       }     // sxuccessful response

  //     });
  });
};
export default {
  components: { studentProjectWord, studentProjectWordShow,vword,vpdf },
  data() {
    return {
      isupload: 1,
      DepartmentData: [], //部门学院
			loading:false,
      downloadDig: false, //下载文档对话框
			downloadWordDig:false,
      updatedWordDig: false, //立即修改对话框
			showFile:false,// 展示文件弹窗
			dialogVisibleUpdateFile:false,//修改文件弹窗
			dialogVisibleUpdateFile2:false,//修改文件弹窗2
      downWordData: {
        applicationDate: getNowDate(1), //申请日期
        projectName: "",
        radio: "",
        checkList: [],
        schoolRadio: [],
        applyParsonRadio: [],
        applyParsonName: "",
        college: "",
        tel: "",
        beginTime: "",
        endTime: "",
        studentS: [
          { name: "", collage: "", work: "" },
          { name: "", collage: "", work: "" },
          { name: "", collage: "", work: "" },
          { name: "", collage: "", work: "" },
          { name: "", collage: "", work: "" },
          { name: "", collage: "", work: "" },
        ],
        teacherS: [
          { name: "", collage: "", work: "" },
          { name: "", collage: "", work: "" },
        ],
        brief: "",
        introduce: {
          back: "",
          innovate: "",
          path: "",
          scene: "",
          worth: "",
          team: "",
          cost: "",
          expectResults: "",
          expectResultsTeacher: "",
          expectConversion: "",
          plan: "",
        },
        total: 0,
        fund: {
          device: "",
          Material: "",
          processing: "",
          APPRAISAL: "",
          Collaboration: "",
          Transaction: "",
          activities: "",
          entery: "",
        },
				opinion:[],
      },
      wordData: {
        applicationDate: getNowDate(1), //申请日期
        projectName: "",
        radio: "",
        checkList: [],
        schoolRadio: [],
        applyParsonRadio: [],
        applyParsonName: "",
        college: "",
        tel: "",
        beginTime: "",
        endTime: "",
        studentS: [
          { name: "", collage: "", work: "" },
          { name: "", collage: "", work: "" },
          { name: "", collage: "", work: "" },
          { name: "", collage: "", work: "" },
          { name: "", collage: "", work: "" },
          { name: "", collage: "", work: "" },
        ],
        teacherS: [
          { name: "", collage: "", work: "" },
          { name: "", collage: "", work: "" },
        ],
        brief: "",
        introduce: {
          back: "",
          innovate: "",
          path: "",
          scene: "",
          worth: "",
          team: "",
          cost: "",
          expectResults: "",
          expectResultsTeacher: "",
          expectConversion: "",
          plan: "",
        },
        total: 0,
        fund: {
          device: "",
          Material: "",
          processing: "",
          APPRAISAL: "",
          Collaboration: "",
          Transaction: "",
          activities: "",
          entery: "",
        },
				attachment:[],//附件上传
				opinion:[],
      },
			signData:[],
			word: [
        "DOC",
        "DOCX",
        "DOCM",
        "DOTM",
        "DOTX",
        "PPTX",
        "PPSX",
        "PPT",
        "PPS",
        "PPTM",
        "POTM",
        "PPAM",
        "POTX",
        "PPSM",
        "XLSX",
        "XLS",
      ],
      pdf: ["PDF"],
      image: [
        "BMP",
        "PJP",
        "APNG",
        "PNG",
        "JPG",
        "GIF",
        "SVG",
        "JPEG",
        "JPG",
        "ICO",
        "PGPEG",
        "AVIF",
      ],
      vedio: [
        "AVI",
        "NAVI",
        "MPEG",
        "ASF",
        "MOV",
        "WMV",
        "3GP",
        "RM",
        "RMVB",
        "FLV",
        "F4V",
        "H.264",
        "H.265",
        "REAL VIDEO",
        "MKV",
        "WebM",
        "HDDVD",
        "MP4",
        "MPG",
        "M4V",
        "MGV",
        "OGV",
        "QTM",
        "STR",
        "AMC",
        "DVX",
        "EVO",
        "DAT",
        "OGG",
        "OGM",
      ],
      playerOptions: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: "video/mp4", //这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目   || "video/ogg"|| "video/webm"
            src: "", //url地址require("../../assets/media/aaa.mp4")
          },
        ],
        // poster: require("../../assets/tu31.png"), //你的封面地址
        // poster: dataRes.imgUrl, //你的封面地址
        notSupportedMessage: "此视频暂无法播放，请稍后再试", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, //当前时间和持续时间的分隔符
          durationDisplay: true, //显示持续时间
          remainingTimeDisplay: false, //是否显示剩余时间功能
          fullscreenToggle: true, //全屏按钮
        },
      },
      playerO: {},
      videoDetail: {},
			Wordss:{},
			showFileUrl:"",
			canonical: {
        Image:
          /^https?:\/\/(.+\/)+.+(\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i,
        File: /^https?:\/\/(.+\/)+.+(\.(docx|xlsx|ppt|pdf))$/i,
      },
			updateFile:{
				url:"",
				fileName:""
			},
    };
  },
  methods: {
    getText(value) {
      //电话验证
      let verify =
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/; //获取正则表达式 存放到verify变量中
      let result = verify.test(value.trim()); //判断输入框内容是否符合 正则表达式
      if (!result) return this.$message.error("请输入正确联系号码格式");
    },
    addTeacher() {
      //添加老师
      // if (this.wordData.teacherS.length >= 3)
      //   return this.$message.error("指导老师最多三人");
      this.wordData.teacherS.push({ name: "", collage: "", work: "" });
    },
    DelTeacher(index) {
      //删除老师
      this.wordData.teacherS.splice(index, 1);
    },
    addStudent() {
      //添加学生
      this.wordData.studentS.push({ name: "", collage: "", work: "" });
    },
    DelStudent(index) {
      //删除学生
      this.wordData.studentS.splice(index, 1);
    },
    getProjectDepartmentData() {
      //获取项目立项申请基础信息页面所在部门数据
      this.ajax
        .post(this.$store.state.api + "/SelectAllDepartment", {
          uid: this.$store.state.userInfo.userid,
        })
        .then(
          (res) => {
            this.DepartmentData = res.data[0];
          },
          (err) => {
            console.log(err);
          }
        );
    },
    getData() {
			if(this.loading)return;
			this.loading = true;
      let param = {
        uid: this.$store.state.userInfo.userid,
        cid: this.$route.query["pid"],
      };

      this.ajax.get(this.$store.state.api + "/studentProjectData", param).then(
        (res) => {
          let data = res.data[0][0];
          this.wordData.projectName = data.title;
          this.wordData.radio = data.typeName;
          this.wordData.checkList = JSON.parse(data.multiSelectProject);
          this.wordData.schoolRadio = JSON.parse(data.schoolRemould);
          this.wordData.applyParsonRadio = JSON.parse(data.projectApplyperson);
          this.wordData.applyParsonName = data.pro_leader;
          this.wordData.college = data.classid;
          this.wordData.tel = data.phone;
          this.wordData.beginTime = data.bTime;
          this.wordData.endTime = data.eTime;
          this.wordData.studentS = JSON.parse(data.course_student);
          this.wordData.teacherS = JSON.parse(data.course_teacher);
          this.wordData.brief = data.brief;
          this.wordData.introduce = JSON.parse(data.chapters);
          this.wordData.fund = JSON.parse(data.money);
					this.wordData.opinion = data.opinion?JSON.parse(data.opinion):[];
					this.wordData.attachment = data.attachment?JSON.parse(data.attachment):[];
          this.downWordData = {
            ...this.wordData,
            ...{ etime: data.eTime, btime: data.bTime, dp: data.className },
          };
          this.isupload = data["isupload"];
					this.loading = false;
        },
        (err) => {
          console.log(err);
        }
      );
    },
		//  获取评审数据
		getSignData(){
			let params = {
				pid:this.$route.query['pid']
			}
			this.ajax.get(this.$store.state.api+'/selectSign',params).then(res=>{
				let signData = res.data[0]
				signData.sort((a,b)=>new Date(b.create_at) - new Date(a.create_at))
				this.signData = signData
			})
		},
    test() {
      //验证
      const cEmpty = /^\s*$/g;
      for (let i in this.wordData) {
        // console.log(this.wordData[i],i);
        switch (i) {
          case "projectName":
            if (cEmpty.test(this.wordData[i])) {
              this.$message.error("请输入项目名称");
              // this.$refs.projectName.style.background='rgb(236, 141, 141)'
              // setTimeout(() => {
              //   this.$refs.projectName.style.background='#ffffff'
              // }, 2000);
              document
                .querySelector("#projectName")
                .scrollIntoView({ behavior: "smooth" });
              return false;
            }
            break;
          case "radio":
            if (cEmpty.test(this.wordData[i])) {
              this.$message.error("请选择项目分组");
              document
                .querySelector("#radio")
                .scrollIntoView({ behavior: "smooth" });
              return false;
            }
            break;
          // case "checkList":
          //   if (this.wordData[i].length == 0) {
          //     this.$message.error("优先支持项目");
          //     document
          //       .querySelector("#checkList")
          //       .scrollIntoView({ behavior: "smooth" });
          //     return false;
          //   }
          //   break;
          // case "schoolRadio":
          //   if (cEmpty.test(this.wordData[i])) {
          //     this.$message.error("请选择美丽校园改造项目");
          //     document
          //       .querySelector("#schoolRadio")
          //       .scrollIntoView({ behavior: "smooth" });
          //     return false;
          //   }
          //   break;
          // case "applyParsonRadio":
          //   if (cEmpty.test(this.wordData[i])) {
          //     this.$message.error("请选择项目申请人");
          //     document
          //       .querySelector("#applyParsonRadio")
          //       .scrollIntoView({ behavior: "smooth" });
          //     return false;
          //   }
          //   break;
          case "applyParsonName":
            if (cEmpty.test(this.wordData[i])) {
              this.$message.error("请填写申请人姓名");
              document
                .querySelector("#applyParsonName")
                .scrollIntoView({ behavior: "smooth" });
              return false;
            }
            break;
          case "college":
            if (cEmpty.test(this.wordData[i])) {
              this.$message.error("请选择所在学院");
              document
                .querySelector("#applyParsonName")
                .scrollIntoView({ behavior: "smooth" });
              return false;
            }
            break;
          case "tel":
            if (cEmpty.test(this.wordData[i])) {
              this.$message.error("请填写联系方式");
              document
                .querySelector("#applyParsonName")
                .scrollIntoView({ behavior: "smooth" });
              return false;
            }
            break;
          case "beginTime":
            if (cEmpty.test(this.wordData[i])) {
              this.$message.error("请选择项目起始时间");
              document
                .querySelector("#beginTime")
                .scrollIntoView({ behavior: "smooth" });
              return false;
            }
            break;
          case "endTime":
            if (cEmpty.test(this.wordData[i])) {
              this.$message.error("请选择计划完成时间");
              document
                .querySelector("#beginTime")
                .scrollIntoView({ behavior: "smooth" });
              return false;
            }
            break;
          // case "studentS":
          //   let snum = 0;
          //   this.wordData[i].forEach((item) => {
          //     if (cEmpty.test(item["name"])) snum++;
          //     // for(let j in item){
          //     //   if(cEmpty.test(item[j])){
          //     //     snum++;
          //     //   }
          //     // }
          //   });
          //   if (snum > 0) {
          //     this.$message.error("学生姓名请不要留空");
          //     document
          //       .querySelector("#studentS")
          //       .scrollIntoView({ behavior: "smooth" });
          //     return false;
          //   }
          //   // }
          //   break;
          // case "teacherS":
          //   let num = 0;
          //   this.wordData[i].forEach((item) => {
          //     if (cEmpty.test(item["name"])) num++;
          //     // for(let j in item){
          //     //   if(cEmpty.test(item[j])){
          //     //     num++;
          //     //   }
          //     // }
          //   });
          //   if (num > 0) {
          //     this.$message.error("老师姓名请不要留空");
          //     document
          //       .querySelector("#teacherS")
          //       .scrollIntoView({ behavior: "smooth" });
          //     return false;
          //   }
          //   break;
          // case 'brief':
          //     if (cEmpty.test(this.wordData[i])) {
          //       this.$message.error('请填写项目简介')
          //       // this.$refs.brief.style.background='rgb(236, 141, 141)'
          //       // setTimeout(() => {
          //       //   this.$refs.brief.style.background='#ffffff'
          //       // }, 2000);
          //       document.querySelector('#brief').scrollIntoView({ behavior: "smooth" });
          //       return false
          //     }
          // break;
          case "fund":
            let mon =
              this.wordData.fund.device * 1 +
              this.wordData.fund.Material * 1 +
              this.wordData.fund.processing * 1 +
              this.wordData.fund.APPRAISAL * 1 +
              this.wordData.fund.Collaboration * 1 +
              this.wordData.fund.Transaction * 1 +
              this.wordData.fund.activities * 1 +
              this.wordData.fund.entery * 1;
            if (mon == 0) {
              document
                .querySelector("#fund")
                .scrollIntoView({ behavior: "smooth" });
              return this.$message.error("请输入经费");
            }
            break;
        }
      }
      this.wordData["total"] =
        this.wordData.fund.device * 1 +
        this.wordData.fund.Material * 1 +
        this.wordData.fund.processing * 1 +
        this.wordData.fund.APPRAISAL * 1 +
        this.wordData.fund.Collaboration * 1 +
        this.wordData.fund.Transaction * 1 +
        this.wordData.fund.activities * 1 +
        this.wordData.fund.entery * 1;

      this.updatedWordDig = true;
    },
    updatedWord() {
      let param = {
        uid: this.$store.state.userInfo.userid, //用户ID
        cid: this.$route.query["pid"],
        tid: "5e21b204-c206-11ed-a4cd-509a4c5b67cf", //特色创客空间建设项目分类ID
        tit: encodeURIComponent(this.wordData["projectName"]), //项目名称
        radio: this.wordData["radio"], //项目分组
        checkList: encodeURIComponent(JSON.stringify(this.wordData["checkList"])), //优先支持项目
        schoolRadio: encodeURIComponent(JSON.stringify(this.wordData["schoolRadio"])), //美丽校园改造项目
        applyParsonRadio: encodeURIComponent(JSON.stringify(this.wordData["applyParsonRadio"])), //项 目 申 请 人
        applyParsonName: encodeURIComponent(this.wordData["applyParsonName"]), //申请人姓名
        coid: this.wordData["college"], //学院ID,
        tel: this.wordData["tel"], //联系电话
        beh: this.wordData["beginTime"], //项目开始时间,
        planEnd: this.wordData["endTime"], //计划完成时间,
        cs: encodeURIComponent(JSON.stringify(this.wordData["studentS"])), //学生组,
        ct: encodeURIComponent(JSON.stringify(this.wordData["teacherS"])), //教师组,
        bf: encodeURIComponent(this.wordData["brief"]), //项目简介
        introduce: encodeURIComponent(JSON.stringify(this.wordData["introduce"])), //项目详细
        mon: encodeURIComponent(JSON.stringify(this.wordData["fund"])), //预算经费
        f: this.wordData["total"], //总经费
        apply: this.wordData["applicationDate"], //申请日期
        mem:this.wordData["teacherS"].filter(i=>i.name!='').length + this.wordData["studentS"].filter(i=>i.name!='').length,
				attachment:encodeURIComponent(JSON.stringify(this.wordData["attachment"])),//附件上传
      };
      this.ajax
        .post(this.$store.state.api + "/updateStudentProjectData", param)
        .then(
          (res) => {
            // console.log(res.data);
            if (res.data) {
              this.updatedWordDig = false;
              return this.$message.success("修改成功");
            } else {
              this.$message.error("修改失败");
            }
          },
          (err) => {
            console.log(err);
          }
        );
    },
		downloadWordFile(){
			this.loading = true;
            // var credentials = {
            //     accessKeyId: "AKIATLPEDU37QV5CHLMH",
            //     secretAccessKey: "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",
            // }; //秘钥形式的登录上传
            // window.AWS.config.update(credentials);
            // window.AWS.config.region = "cn-northwest-1"; //设置区域
            // let url2 = "https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E6%94%B6%E5%85%A5%E6%A8%A1%E5%BC%8F1712047315470.jpg";
            // let _url2 = "";
            // if (
            //     url2.indexOf("https://view.officeapps.live.com/op/view.aspx?src=") != -1
            // ) {
            //     _url2 = url2.split(
            //         "https://view.officeapps.live.com/op/view.aspx?src="
            //     )[1];
            // } else {
            //     _url2 = url2;
            // }
            // let _this = this;

            // var s3 = new window.AWS.S3({ params: { Bucket: "ccrb" } });
            // let name = decodeURIComponent(_url2.split("https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/")[1])
            // var params = {
            //     Bucket: "ccrb",
            //     Key: name
            // };
            // s3.getObject(params, function (err, data) {
  
            //     if (err) console.log(err, err.stack); // an error occurred
            //     else {
            //         let url = window.URL.createObjectURL(new Blob([data.Body]));
            //         let a = document.createElement("a");
            //         a.name = name;
            //         a.href = url;
            //         a.download = name;
            //         a.click();
            //         console.log(data);
            //     }          // sxuccessful response

            // });
			// getFile("https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8711711980299371.jpg").then(res=>{
			// 	console.log(res)
			// })
			// return
			this.$nextTick(async ()=>{
				this.$message.info("正在下载，请稍等...")
				let elementList = this.$refs.myChild.$refs.pdfShow.querySelectorAll('.downImage')
				let fontSize = [];
				let pFontSize = [];
				let promises = []
				let fontType = {
					'1':"13pt",
					'2':"16.9pt",
					'3':"20.9pt",
					'4':"23.5pt",
					'5':"31.3pt",
					'6':"41.8pt",
					'7':"62.6pt"
				}
				elementList.forEach((el,elIndex) => {
				  let img = el.getElementsByTagName('img');
					for(let i=0;i<img.length;i++){
						img[i].setAttribute('crossOrigin',"*")
						// let src = img[i].getAttribute("src");
						// promises.push(getFile(src).then(async res=>{
						// 	await new Promise(resolve => {
						// 	  if (res.data != 1) {
						// 			let blob = new Blob([res.data]);
						// 			// blob = new Blob([res.data],{type:res.headers['content-type']});
						// 			let reader = new FileReader();
						// 			reader.readAsDataURL(blob);
						// 			reader.onload = function(e){
						// 				img[i].setAttribute("src",this.result);
						// 				resolve();
						// 			}
          	// 		}
						// 	})
							
						// }))
						
						// img[i].setAttribute("crossOrigin","*");
					}
					let font = el.getElementsByTagName('font');
					for(let i=0;i<font.length;i++){
						fontSize.push(font[i].getAttribute("size"))
						font[i].removeAttribute("size")
						font[i].setAttribute("style",`font-size:${fontType[fontSize[i]]}`)
					}

					// 替换p标签的font-size
					// let p = el.getElementsByTagName('p');
					let p = el.querySelectorAll("*")
					for(let i=0;i<p.length;i++){
						let pStyle = p[i].getAttribute("style")
						if(!pStyle)continue;
						let matchArr = pStyle.match(/font-size: (\d+)px/);
						if(!matchArr)continue;
						pFontSize.push({style:pStyle,index:`${elIndex}:${i}`})
						let originalSize = pStyle.match(/font-size: (\d+)px/)[1];
						
						let newSize = parseInt(originalSize)*1.3;
						let newStyle = pStyle.replace(/font-size: (\d+)px/,`font-size: ${newSize}pt`)
						p[i].setAttribute("style",newStyle)
					}
				})
				// return
				// return await Promise.all(promises)
				Promise.all(promises).then(()=>{
					let newData = JSON.parse(JSON.stringify(this.downWordData))
					getWord2({...newData,signData:this.signData,elementList}).then(_=>{
						elementList.forEach((el,elIndex) => {
					  	let img = el.getElementsByTagName('img');
							for(let i=0;i<img.length;i++){
								img[i].removeAttribute('crossOrigin')
							}
							let font = el.getElementsByTagName('font');
							for(let i=0;i<font.length;i++){
								font[i].removeAttribute("style")
								font[i].setAttribute("size",fontSize[i])
							}
							// 替换p标签的font-size
							let p = el.querySelectorAll("*")
							for(let i=0;i<p.length;i++){
								let oldStyle = pFontSize.find(p=>p.index==`${elIndex}:${i}`)
								if(!oldStyle)continue;
								p[i].setAttribute("style",oldStyle.style)
								// let pStyle = p[i].getAttribute("style")
							
								// if(!pStyle)continue
								// let matchArr = pStyle.match(/font-size: (\d+)px/);
								// console.log(matchArr)
								// if(!matchArr)continue;
								// console.log(pFontSize[i])
								// p[i].setAttribute("style",pFontSize[i])
							}
						})
						this.downloadWordDig = false;
						this.loading = false;
					})
				})
				
			})
			
			
			// getWord2({...this.downWordData,elementList:this.$refs.myChild.$refs.pdfShow.querySelectorAll('.downImage')})
			// getWord2({...this.downWordData,signData:this.signData});
			
		},
    downloadPDFFile() {
			// let elementList = this.$refs.myChild.$refs.pdfShow.querySelectorAll('.downImage')
			// elementList.forEach(el => {
			//   let img = el.getElementsByTagName('img');
			// 	for(let i=0;i<img.length;i++){
			// 		img[i].crossOrigin = "*"
			// 	}
			// })
      downloadPDF(
        this.$refs.myChild.$refs.pdfShow,
        "附件2：2023年学生创客项目申报书"
      );
      // this.wordData['total']=this.wordData.fund.facility*1 + this.wordData.fund.materials*1+this.wordData.fund.process*1+ this.wordData.fund.assist*1+this.wordData.fund.authenticate*1+ this.wordData.fund.match*1+this.wordData.fund.activity*1+this.wordData.fund.affair*1
      // return console.log(this.wordData);
			// let elementList = this.$refs.myChild.$refs.pdfShow.querySelectorAll('.downImage')
			// elementList.forEach(el => {
			//   let img = el.getElementsByTagName('img');
			// 	for(let i=0;i<img.length;i++){
			// 		img[i].crossOrigin = "*"
			// 	}
			// })
			// return console.log(elementList)
      // getWord({...this.downWordData,elementList:this.$refs.myChild.$refs.pdfShow.querySelectorAll('.downImage')})
      // getWord(this.downWordData)

      this.downloadDig = false;
    },
		// 上传专家文件
		getFile(file){
			this.wordData.opinion.push(file);
			this.saveFile();
		},
		// 对文件的操作
		fileOption(file,index,opt){
			if(opt=='0'){
				this.checkFile(file.url)
			}else if(opt=='1'){
				if(index==0)return;
				this.wordData.opinion.splice(index-1,0,this.wordData.opinion.splice(index,1)[0]);
				this.saveFile();
			}else if(opt=='2'){
				if(index==this.wordData.opinion.length-1)return;
				this.wordData.opinion.splice(index+1,0,this.wordData.opinion.splice(index,1)[0]);
				this.saveFile();
			}else if(opt=='3'){
				this.updateFile = {...file,index:index}
				this.dialogVisibleUpdateFile = true;
				
			}else if(opt=='4'){
				this.$confirm("确定删除该文件？","提示",{
					type:"error",
					confirmButtonText:"确定删除",
					cancelButtonText:"取消",
				}).then(_=>{
					this.wordData.opinion.splice(index,1);
					this.saveFile();
				})
			}
		},
		//上传附件
		fileOption2(file,index,opt){
			if(opt=='0'){
				this.checkFile(file.url)
			}else if(opt=='1'){
				if(index==0)return;
				this.wordData.attachment.splice(index-1,0,this.wordData.attachment.splice(index,1)[0]);
			}else if(opt=='2'){
				if(index==this.wordData.attachment.length-1)return;
				this.wordData.attachment.splice(index+1,0,this.wordData.attachment.splice(index,1)[0]);
			}else if(opt=='3'){
				this.updateFile = {...file,index:index}
				this.dialogVisibleUpdateFile2 = true;
				
			}else if(opt=='4'){
				this.$confirm("确定删除该文件？","提示",{
					type:"error",
					confirmButtonText:"确定删除",
					cancelButtonText:"取消",
				}).then(_=>{
					this.wordData.attachment.splice(index,1);
				})
			}
		},
		// 上传专家文件
		getFile2(file){
			this.wordData.attachment.push(file);
		},
		// 上传文件函数
		saveFile(){
			let params = {
				uid:this.$store.state.userInfo.userid,
				pid:this.$route.query["pid"],
				file:encodeURIComponent(JSON.stringify(this.wordData.opinion))
			}
			this.ajax.post(this.$store.state.api+"/updateProjectOpinion",params).then(res=>{
				if(res.data==1){
					return this.getData();
				}
			})

		},
		//展示文件
    checkFile(url) {
      this.videoDetail = {};
      if (
        this.vedio.indexOf(
          url.split(".")[url.split(".").length - 1].toLocaleUpperCase()
        ) != -1
      ) {
        this.playerOptions.sources[0].src = url;
        this.videoDetail = this.playerOptions;
        this.showFile = true;
      } else {
        if (
          this.word.indexOf(
            url.split(".")[url.split(".").length - 1].toLocaleUpperCase()
          ) == -1 &&
          this.pdf.indexOf(
            url.split(".")[url.split(".").length - 1].toLocaleUpperCase()
          ) == -1 &&
          this.image.indexOf(
            url.split(".")[url.split(".").length - 1].toLocaleUpperCase()
          ) == -1
        ) {
          this.downFile(url);
          return;
        }
        this.showFileUrl = url;
        this.showFile = true;
        if (typeof url == "undefined") return { type: "", name: "" };
        let urlSplit = url.split(".");
        const type = urlSplit[urlSplit.length - 1];
        if (this.canonical.Image.test(url)) {
          this.Wordss = { type: type, name: "图片" };
          return console.log(this.Wordss);
        }
        if (this.canonical.File.test(url)) {
          this.Wordss = { type: type, name: "文档" };
          return console.log(this.Wordss);
        }
        if (this.canonical.vedio.test(url)) {
          this.Wordss = { type: type, name: "视频" };
          return console.log(this.Wordss);
        } else return (this.Wordss = { type: type, name: type });
      }
    },
		//下载文件
    downFile(f) {
      var credentials = {
        accessKeyId: "AKIATLPEDU37QV5CHLMH",
        secretAccessKey: "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",
      }; //秘钥形式的登录上传
      window.AWS.config.update(credentials);
      window.AWS.config.region = "cn-northwest-1"; //设置区域
      let url2 = f;
      let _url2 = "";
      if (
        url2.indexOf("https://view.officeapps.live.com/op/view.aspx?src=") != -1
      ) {
        _url2 = url2.split(
          "https://view.officeapps.live.com/op/view.aspx?src="
        )[1];
      } else {
        _url2 = url2;
      }
      var s3 = new window.AWS.S3({ params: { Bucket: "ccrb" } });
      let name = decodeURIComponent(
        _url2.split("https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/")[1]
      );
      var params = {
        Bucket: "ccrb",
        Key: name,
      };
      s3.getObject(params, function (err, data) {
        if (err) console.log(err, err.stack); // an error occurred
        else {
          let url = window.URL.createObjectURL(new Blob([data.Body]));
          let a = document.createElement("a");
          a.name = name;
          a.href = url;
          a.download = name;
          a.click();
          console.log(data);
        } // sxuccessful response
      });

      return;
    },
		// 修改文件名称
		updateFileName(){
			if(!this.updateFile.fileName)return this.$message.error("请输入文件名称");
			this.wordData.opinion[this.updateFile.index].fileName = this.updateFile.fileName;
			this.dialogVisibleUpdateFile = false;
			this.saveFile();
		},
		// 修改文件名称
		updateFileName2(){
			if(!this.updateFile.fileName)return this.$message.error("请输入文件名称");
			this.wordData.attachment[this.updateFile.index].fileName = this.updateFile.fileName;
			this.dialogVisibleUpdateFile2 = false;
		}
		// downloadWord2() {
    //   // downloadPDF(
    //   //   this.$refs.myChild.$refs.pdfShow,
    //   //   "附件2：2023年学生创客项目申报书"
    //   // );
    //   // this.wordData['total']=this.wordData.fund.facility*1 + this.wordData.fund.materials*1+this.wordData.fund.process*1+ this.wordData.fund.assist*1+this.wordData.fund.authenticate*1+ this.wordData.fund.match*1+this.wordData.fund.activity*1+this.wordData.fund.affair*1
    //   // return console.log(this.wordData);
		// 	let elementList = this.$refs.myChild.$refs.pdfShow.querySelectorAll('.downImage')
		// 	elementList.forEach(el => {
		// 	  let img = el.getElementsByTagName('img');
		// 		for(let i=0;i<img.length;i++){
		// 			img[i].crossOrigin = "*"
		// 		}
		// 	})
		// 	// return console.log(elementList)
    //   getWord2({...this.downWordData,elementList:this.$refs.myChild.$refs.pdfShow.querySelectorAll('.downImage')})
    //   // getWord(this.downWordData)

    //   this.downloadDig = false;
    // },
  },
  //小型仪器设备费：device        deviceRemarks
  //材料费：Material             MaterialRemarks
  //测试化验加工费：processing    processingRemarks
  //项目协作费：Collaboration     CollaborationRemarks
  //项目成果鉴定费：APPRAISAL     APPRAISALRemarks
  //参展参赛费：entery            enteryRemarks
  //创客交流活动费：activities    activitiesRemarks
  //知识产权事务费：Transaction   TransactionRemarks
  computed: {
    //经费总合
    reversedMessage: function () {
      return (
        this.wordData.fund.device * 1 +
        this.wordData.fund.Material * 1 +
        this.wordData.fund.processing * 1 +
        this.wordData.fund.Collaboration * 1 +
        this.wordData.fund.APPRAISAL * 1 +
        this.wordData.fund.entery * 1 +
        this.wordData.fund.activities * 1 +
        this.wordData.fund.Transaction * 1
      );
    },
  },
  mounted() {
    this.getProjectDepartmentData();
    this.getData();
		this.getSignData();
    //   console.log(this.$route.query['pid']);
  },
};
</script>
      
    <style lang="less" scoped>
#studentProjectWordDetail {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}
</style>