<template>
  <!-- 测试上传组件 -->
  <div v-loading="loading">
    <div class="pAHeader">
      <div class="pAHeader1">创客项目申请</div>
    </div>
    <hr />

    <!-- 学生项目立项 -->
    <studentProjectWord
      ref="pdf"
      :wordData="wordData"
      :reversedMessage="reversedMessage"
			@fileOption2="fileOption2"
			@getFile2="getFile2"
    />
    <div style="position: fixed; bottom: 5%; right: 2%">
			<el-button @click="saveDraft" type="primary">保存草稿</el-button>
      <el-button @click="test" type="primary">保存项目</el-button>
    </div>

		<!-- 保存项目弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="submitHint"
      width="600px"
      class="pageSubmitData"
    >
      <div class="deleteContent">
        确定保存“{{ wordData["projectName"] }}”项目吗？
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitWord" class="AllDialogBtn"
          >确认保存</el-button
        >
        <el-button @click="submitHint = 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>
  </div>
</template>

<script>
// import MakerSpaceWord from '../components/MakerSpaceWord.vue'
import getProjectNo from "@/components/tool/getProjectNo";
import { getNowDate } from "@/components/tool/Date.js";
import studentProjectWord from "./components/studentProjectWord.vue";
import vpdf from "@/components/vpdf.vue";
import vword from "@/components/vword.vue";
// import markerFundWord from '@/components/markerFundWord.vue';
// import markeractivityWord from '@/components/markeractivityWord.vue';
export default {
  components: {
    studentProjectWord,
		vpdf,
		vword
    // markerFundWord,
    // markeractivityWord
  },
  data() {
    return {
      accept: "*",
      loading: false,
      submitHint: false,
			updatedWordDig: false, //立即修改对话框
			showFile:false,// 展示文件弹窗
			dialogVisibleUpdateFile:false,//修改文件弹窗
			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:""
			},
      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: "" },
					{ name: "", collage: "", work: "" },
					{ name: "", collage: "", work: "" },
					{ name: "", collage: "", work: "" }
				],
        teacherS: [
					{ name: "", collage: "", work: "" },
					{ name: "", collage: "", work: "" },
					{ name: "", collage: "", work: "" },
					{ name: "", collage: "", work: "" }
				],
        brief: "",
        introduce: {
          back: "",
          innovate: "",
          path: "",
          scene: "",
          worth: "",
          team: "",
          cost: "",
          expectResults: "",
          expectResultsTeacher: "",
          expectConversion: "",
          plan: "",
        },
				attachment:[],
        total: "",
        fund: {
          device: "",
          Material: "",
          processing: "",
          Collaboration: "",
          APPRAISAL: "",
          entery: "",
          activities: "",
          Transaction: "",
        },
				opinion:[],
      },
    };
  },
  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
      );
    },
  },
  methods: {
    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 (this.wordData[i].length == 0) {
          //     this.$message.error("请选择美丽校园改造项目");
          //     document
          //       .querySelector("#schoolRadio")
          //       .scrollIntoView({ behavior: "smooth" });
          //     return false;
          //   }
          //   break;
          // case "applyParsonRadio":
          //   if (this.wordData[i].length == 0) {
          //     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 (this.wordData[i].length > 300 || this.wordData[i].length == 0) {
          //     this.$message.error("请填写项目简介，字数在300字以内");
          //     document
          //       .querySelector("#brief")
          //       .scrollIntoView({ behavior: "smooth" });
          //     return false;
          //   }
          //   break;
          case "fund":
            // device:"",
            //     Material:"",
            //     processing:"",
            //     Collaboration:"",
            //     APPRAISAL:"",
            //     entery:"",
            //     activities:"",
            //     Transaction:"",
            // let mon=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.match*1+this.wordData.fund.activity*1+this.wordData.fund.affair*1
            let mon = 0;
            for (let k in this.wordData.fund) {
              mon += this.wordData.fund[k] * 1;
            }
            // console.log(mon);
            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.Collaboration * 1 +
        this.wordData.fund.APPRAISAL * 1 +
        this.wordData.fund.entery * 1 +
        this.wordData.fund.activities * 1 +
        this.wordData.fund.Transaction * 1;

      this.submitHint = true;
    },

    submitWord() {
      //提交
      // return console.log(this.wordData['total']);
			let typeList = {
				"4a4e2cfe-e1a1-11ee-81d4-00ff5c7a43f5":"CX",
				"56f0ad8d-e1a1-11ee-81d4-00ff5c7a43f5":"CY",
				"ed917c55-f51d-11ed-a3f6-509a4c5b67cf":"SJ",
				"1":"XM"
			}
      getProjectNo(typeList[this.wordData["radio"]]).then((result) => {
        let pram = {
          uid: this.$store.state.userInfo.userid, //用户ID
          pNo: result, //项目编号
          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"]), //申请人姓名
          cid: 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["studentS"].filter(i=>i.name!='').length + this.wordData["teacherS"].filter(i=>i.name!='').length, //项目组人数
					attachment:encodeURIComponent(JSON.stringify(this.wordData["attachment"])),//附件上传
        };
        this.ajax
          .post(this.$store.state.api + "/studentProjectWordApply", pram)
          .then(
            async (result) => {
              console.log(result);
              if (result["data"] == 1) {
                this.$message.success("项目提交成功");
                //提交项目成功，查看sessionStore是否有数据，有则删
								// localStorage.removeItem(`StudentProjectApplyData${this.$store.state.userInfo.userid}`);
                await this.ajax.post(this.$store.state.api+"/delDraft",{userid:this.$store.state.userInfo.userid,type:0})
								this.submitHint = false;
								this.$destroy();
                this.$router.push("/projectApplication");
								
              } else {
                this.$message.error("项目提交失败");
								this.submitHint = false
              }
            },
            (err) => {
              console.log(err);
            }
          )
          .catch((err) => {
            console.log(err);
          });
      });
    },
    saveData() {
      // localStorage.setItem(
      //   `StudentProjectApplyData${this.$store.state.userInfo.userid}`,
      //   JSON.stringify(this.wordData)
      // );
    },
		// 保存草稿
		saveDraft(){
			if(this.loading)return this.$message.info('请稍等...');
			this.loading = true;
			let params = {
				userid:this.$store.state.userInfo.userid,
				type:0,
				jsonData:encodeURIComponent(JSON.stringify(this.wordData))
			}
			this.ajax.post(this.$store.state.api + "/saveDraft",params).then(res=>{
				if(res.data==1){
					this.$message.success("保存成功")
				}else{
					this.$message.error("保存失败")
				}
				this.loading = false;
			})
		},
		//获取草稿
		getDraft(){
			if(this.loading)return this.$message.info('请稍等...');
			this.loading = true;
			let params = {
				userid:this.$store.state.userInfo.userid,
				type:0,
			}
			this.ajax.get(this.$store.state.api + "/getDraft",params).then(res=>{
				if(res.data[0].length){
					this.wordData = JSON.parse(res.data[0][0].json)
				// }else{
				// 	if (localStorage.getItem(`StudentProjectApplyData${this.$store.state.userInfo.userid}`)){
				// 		this.wordData = JSON.parse(
      	// 		  localStorage.getItem(`StudentProjectApplyData${this.$store.state.userInfo.userid}`)
      	// 		);
				// 	}
				}
				this.loading = false;
			})
		},
		//上传附件
		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.dialogVisibleUpdateFile = 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);
		},
		// 展示文件
		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 });
      }
    },
		// 修改文件名称
		updateFileName(){
			if(!this.updateFile.fileName)return this.$message.error("请输入文件名称");
			this.wordData.attachment[this.updateFile.index].fileName = this.updateFile.fileName;
			this.dialogVisibleUpdateFile = false;
		},
		//下载文件
    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;
    },
  },
  mounted() {
		this.getDraft();
    window.addEventListener("beforeunload", () => this.saveData());
  },

  beforeRouteLeave(to, from, next) {
    //判断，如果还没提交然后切换页面了，则把数据存到sessionStore里;
    if (!this.submitHint) this.saveData();
    next();
  },
};
</script>

<style lang="less" scoped></style>
