<template>
  <div class="classroomObservation" v-loading="loading">
    <!-- <div class="co-header1">
			<div class="co-h1-left">
				<span class="co-h1-l-icon el-icon-s-home"></span>
				<div class="co-h1-l-router">
						<span class="co-h1-l-r-up" @click="goTo('ai助手')">AI助手</span>
						<span class="co-h1-l-r-rightIcon el-icon-arrow-right"></span>
						<span class="co-j1-l-r-down">课堂观察</span>
				 </div>
			</div>
		</div> -->
    <div class="co-header2">
      <div class="co-h2-left">
        <!-- <span
					class="co-h2-l-icon"
					@click="$refs.addNewCourseDialogRef.open()"
				></span> -->
        <span class="co-h2-l-icon"></span>
        <!-- @click="addNewCourse()" -->
        <!--<span class="co-h2-l-hr"></span>-->
        <span class="co-h2-l-text">
          <el-select
            class="co_h2_l_t_select"
            v-model="tid"
            placeholder="查看历史课堂"
            @change="changeTid"
          >
            <el-option
              v-for="item in optionData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <div class="selectBox">
                <span>{{ item.label }}</span>
                <div class="controlsBox">
                  <span
                    class="changeSelect"
                    @click.stop="changeCourse(item)"
                  ></span>
                  <span
                    class="delSelect"
                    @click.stop="delCourse(item.id)"
                  ></span>
                </div>
              </div>
            </el-option>
          </el-select>
        </span>
        <!-- <div
					class="co_h2_l_del"
					@click.stop="delCourse()"
					v-if="optionData.length > 0"
				>
					<span></span>
				</div> -->
      </div>
      <div class="co-h2-right">
        <div
          :class="['co-h2-r-btn', fileId && tid ? '' : 'ca-h2-r-noActive']"
          style="background: rgba(54, 129, 252, 1)"
          @click.stop="getReport()"
        >
          <span class="co-h2-r-b-icon1"></span>
          <div style="color: white">一键分析</div>
        </div>

        <div
          :class="['co-h2-r-btn', fileId && tid ? '' : 'ca-h2-r-noActive']"
          style="background: #ffffff"
          @click.stop="preview()"
        >
          <span class="co-h2-r-b-icon2"></span>
          <div style="color: black">查看报告</div>
        </div>
        <!-- <div class="co-h2-r-btn2" @click.stop="preview()">
					<el-tooltip class="item" effect="light" content="预览" placement="top">
						<img
						src="../../../assets/icon/classroomObservation/Syan.png"
						alt=""
					/>
    			</el-tooltip>
				</div> -->

        <div :class="['co-h2-r-btn2']" @click.stop="shareBtn">
          <!-- <span class="co-h2-r-b-icon3"></span> -->
          <el-tooltip
            class="item"
            effect="light"
            content="分享"
            placement="top"
          >
            <img
              src="../../../assets/icon/classroomObservation/daoChu.svg"
              alt=""
            />
          </el-tooltip>
        </div>

        <div :class="['co-h2-r-btn2']" @click.stop="derive">
          <!-- <span class="co-h2-r-b-icon3"></span> -->
          <el-tooltip
            class="item"
            effect="light"
            content="导出"
            placement="top"
          >
            <img
              src="../../../assets/icon/classroomObservation/derive.svg"
              alt=""
            />
          </el-tooltip>
        </div>

        <div :class="['co-h2-r-btn2']" @click.stop="examine">
          <!-- <span class="co-h2-r-b-icon3"></span> -->
          <el-tooltip
            class="item"
            effect="light"
            content="审核"
            placement="top"
          >
            <img
              src="../../../assets/icon/classroomObservation/examine.svg"
              alt=""
            />
          </el-tooltip>
        </div>

        <!-- <div :class="['co-h2-r-btn2']" @click.stop="home">
					<el-tooltip
						class="item"
						effect="light"
						content="主页"
						placement="top"
					>
						<img
							src="../../../assets/icon/classroomObservation/home.svg"
							alt=""
						/>
					</el-tooltip>
				</div> -->
      </div>
    </div>
    <div class="co-main">
      <div class="co-m-left">
        <chatArea
          ref="chatAreaRef"
          :tid="tid"
          @updateFileId="updateFileId"
          @changeAudioUrl="changeAudioUrl"
          @updateTranscription="updateTranscription"
          :fileId="fileId"
          :createTime="createTime"
          :fileIdId="fileIdId"
        />
      </div>
      <div class="co-m-right">
        <messageArea
          :tid="tid"
          :fileId="fileId"
          ref="messageAreaRef"
          @changeAudioUrl="changeAudioUrl"
          @changeChatAreaAudioUrl="changeChatAreaAudioUrl"
          @changeTranscription="changeTranscription"
          @changeOptionData="changeOptionData"
          @updateTime="updateTime"
        />
      </div>
    </div>
    <sharePdf :tid="tid" ref="sharePdfRef" @shareBtn="shareBtn"></sharePdf>
    <changeCourseNameDialog
      :tid="tid"
      ref="changeCourseNameDialogRef"
      @success="changeCourseSuccess"
    />

    <!-- <addNewCourseDialog
			:courseList="optionData"
			ref="addNewCourseDialogRef"
			@success="addNewCourse"
		/> -->
  </div>
</template>

<script>
// 聊天区域
import chatArea from "./components/chatArea.vue";
// 信息区域
import messageArea from "./components/messageArea.vue";

import sharePdf from "./components/sharePdf.vue";

import { v4 as uuidv4 } from "uuid";
// 添加课堂弹窗
// import addNewCourseDialog from "./components/addNewCourseDialog.vue";
//修改课程名称弹窗
import changeCourseNameDialog from "./components/changeCourseNameDialog";
//保存模板弹窗
import QRCode from "qrcodejs2";
import * as echarts from "echarts";
import "echarts-wordcloud";
// word
import htmlDocx from "html-docx-js/dist/html-docx";
import saveAs from "file-saver";
import MarkdownIt from "markdown-it";
export default {
  components: {
    chatArea,
    messageArea,
    sharePdf,
    changeCourseNameDialog
    // addNewCourseDialog,
  },
  data() {
    return {
      loading: false,
      createTime: new Date().toLocaleString().replaceAll("/", "-"),
      tid: "",
      fileId: "",
      fileIdId: "",
      optionData: [],
      userId: this.$route.query["userid"],
      tag: {
        0: "一",
        1: "二",
        2: "三"
      }
    };
  },
  methods: {
    //切换了课堂
    changeTid(newValue) {
      this.$nextTick(() => {
        this.$refs.messageAreaRef.getData();
        this.$refs.chatAreaRef.getData();
        this.getFileIdId();

        // 	setTimeout(()=>{
        // 		this.$refs.messageAreaRef.init();
        // 		this.$refs.chatAreaRef.init();
        // 		this.tid = "";
        // 		this.fileId = "";
        // 		this.fileIdId = "";
        // 	},6000)
      });
    },
    addNewCourse() {
      return new Promise((resolve, reject) => {
        this.addNewCourseByDefault().then(_ => {
          resolve();
        });
      });
      // var OpenCC = require("opencc-js");
      // let converter = OpenCC.Converter({
      // 	from: "hk",
      // 	to: "cn",
      // });
      // return new Promise((resolve, reject) => {
      // 	if (this.loading) return this.$message.info("请稍等");
      // 	this.loading = true;
      // 	let date = new Date();
      // 	let month = date.getMonth() + 1;
      // 	let day = date.getDate();
      // 	let classroomName = `${month < 10 ? "0" + month : month}${
      // 		day < 10 ? "0" + day : day
      // 	}新建课堂`;
      // 	let sum = this.optionData.filter(
      // 		(i) => i.label.indexOf(classroomName) != -1
      // 	).length;
      // 	if (!sum == 0) {
      // 		classroomName += sum;
      // 	}
      // 	let params = {
      // 		tid: uuidv4(),
      // 		name: classroomName,
      // 		userid: this.userId,
      // 	};
      // 	this.ajax
      // 		.post(
      // 			"https://gpt4.cocorobo.cn/insert_classroom_observation_tid",
      // 			params
      // 		)
      // 		.then((res) => {
      // 			let _data = res.data.FunctionResponse;
      // 			if (converter(_data.message) == converter("创建成功")) {
      // 				// 设置该课堂的tid
      // 				this.tid = params.tid;
      // 				this.ajax
      // 					.post("https://gpt4.cocorobo.cn/insert_classroom_observation", {
      // 						tid: params.tid,
      // 						type: 10,
      // 						index: 0,
      // 						json_data: JSON.stringify({ file_ids: "" }),
      // 						userid: this.userId,
      // 					})
      // 					.then((res2) => {
      // 						let _data2 = res2.data.FunctionResponse;
      // 						if (converter(_data2.message) == converter("创建成功")) {
      // 							this.loading = false;
      // 							this.$nextTick(() => {
      // 								this.getCourseList().then((_) => {
      // 									this.getFileIdId();
      // 									this.$refs.messageAreaRef.getData();
      // 									this.$refs.chatAreaRef.getData();
      // 									resolve();
      // 								});
      // 							});
      // 						} else {
      // 							this.$message.error("创建fileIds失败");
      // 						}
      // 					});
      // 			} else if (converter(_data.message) == converter("tid重复")) {
      // 				this.$message.error("该课堂已存在");
      // 				this.loading = false;
      // 			} else {
      // 				this.$message.error("创建失败");
      // 				this.loading = false;
      // 			}
      // 		});
      // });
    },
    addNewCourseByDefault() {
      // 通过用户ID获取默认的模板
      var OpenCC = require("opencc-js");
      let converter = OpenCC.Converter({
        from: "hk",
        to: "cn"
      });
      return new Promise((resolve, reject) => {
        let params = {
          uid: this.userId
        };
        this.loading = true;
        this.ajax
          .get(this.$store.state.api + "selectClassroomDefault", params)
          .then(res => {
            let _data = res.data[0][0];
            if (_data) {
              this.loading = true;
              _data.tips = JSON.parse(_data.tips);
              let _result = [];
              _data.tips.forEach(i => {
                if (i.isOtherData) return _result.push(i);
                if (converter("词频词汇分析") == converter(i.jsonData.name))
                  return;
                let _obj = {
                  jsonData: i.jsonData,
                  type: i.Type,
                  index: i.tIndex
                };
                _result.push(_obj);
              });
              this.loading = false;
              // console.log('👇要生成的模板')
              // console.log(_result)
              this.addNewCourseByTemplate(_result).then(_ => {
                resolve();
              });
            } else {
              this.loading = false;
              this.$message.error("获取模板详细为空");
            }
          });
      });
    },
    addNewCourseByTemplate(json = []) {
      if (json.length <= 0) return;
      var OpenCC = require("opencc-js");
      let converter = OpenCC.Converter({
        from: "hk",
        to: "cn"
      });
      let tagList = json.find(i => i.isOtherData);
      json = json.filter(
        i =>
          !i.isOtherData &&
          converter(i.jsonData.name) != converter("词频词汇分析")
      );
      return new Promise((resolve, reject) => {
        this.loading = true;
        const _newTid = uuidv4();
        let params = {
          tid: _newTid,
          userid: this.userId,
          template: json
        };
        this.ajax
          .post(
            "https://gpt4.cocorobo.cn/insert_classroom_observation_template",
            params
          )
          .then(res => {
            let _data = res.data.FunctionResponse;
            if (converter(_data.message) == converter("创建成功")) {
              // 设置该课堂的tid
              this.tid = params.tid;
              this.ajax
                .post("https://gpt4.cocorobo.cn/insert_classroom_observation", {
                  tid: params.tid,
                  type: 10,
                  index: 0,
                  json_data: JSON.stringify({ file_ids: "" }),
                  userid: this.userId
                })
                .then(res2 => {
                  let _data2 = res2.data.FunctionResponse;
                  if (converter(_data2.message) == converter("创建成功")) {
                    this.loading = false;
                    this.$nextTick(() => {
                      this.getCourseList().then(_ => {
                        this.getFileIdId();
                        this.$refs.messageAreaRef.getData().then(res => {
                          if (tagList) {
                            this.$refs.messageAreaRef.changeAnalysisName(
                              tagList.dialogTagList,
                              1
                            );
                          }
                        });
                        this.$refs.chatAreaRef.getData();
                        resolve();
                      });
                    });
                  } else {
                    this.$message.error("创建fileIds失败");
                  }
                });
            } else if (converter(_data.message) == converter("tid重复")) {
              this.$message.error("该课堂已存在");
              this.loading = false;
            } else {
              this.$message.error("创建失败");
              this.loading = false;
            }
          });
      });
    },
    updateFileId(newValue) {
      this.fileId = newValue;
    },
    // 生成报告
    getReport() {
      if (!this.fileId) return;
      // this.$confirm("操作将覆盖原有内容，是否继续？", "提示", {
      // 	confirmButtonText: "确定",
      // 	cancelButtonText: "取消",
      // 	type: "warning",
      // })
      // 	.then(() => {
      this.$refs.messageAreaRef.getReport();
      // 	})
      // 	.catch((e) => {
      // 		console.log(e)
      // 		console.log("取消生成报告");
      // 	});
    },
    //预览
    preview() {
      if (!this.fileId) return;
      window.parent.postMessage(
        {
          tools: "classroom_observation_board",
          type: this.tid
        },
        "*"
      );
    },
    async derive() {
      if (!this.tid) return this.$message.error("请先选择课堂");

      try {
        this.loading = true;
        let bmData = this.$refs.messageAreaRef.bmData
          ? this.$refs.messageAreaRef.bmData.jsonData
          : "";
        const md = new MarkdownIt();
        let dataList = this.$refs.messageAreaRef.dataList;
        let tagList = this.$refs.messageAreaRef.dialogTagList;
        let showBrief = this.$refs.messageAreaRef.showBrief;
        tagList.forEach(i => (i.dataList = []));
        let url = `https://beta.cloud.cocorobo.cn/aigpt/#/classroom_observation_board?tid=${this.tid}`;
        const qRCodeSrc = await this.getQrCodeImageSrc(url);
        dataList.forEach(i1 => {
          tagList.forEach(i2 => {
            if (i2.value == i1.Type) {
              i2.dataList.push(i1);
            }
          });
        });

        let directoryHtml = `<div style="margin-bottom:1in"><div style="text-align:center;font-size:20pt;margin-bottom:0.5in">目录</div>`;

        let analysisHtml = ``;

        // tagList.forEach(i => {
        //   let dire = `<div>`;
        //   let tagHtml = `<div style="margin-bottom:100px">`;
        //   if (i.value == 0) {
        //     i.dataList = i.dataList.filter(i2 => i2.tIndex != 2);
        //   }
        //   i.dataList.sort((a, b) => a.tIndex - b.tIndex);

        //   tagHtml += `<h1 style="font-size:16pt;margin-bottom:30px">${
        //     this.tag[i.value]
        //   }、${i.name}</h1>`;
        //   dire += `<div style="font-size:14pt;margin:15px 0">${
        //     this.tag[i.value]
        //   }、${i.name}</div>`;
        //   i.dataList.forEach(async (i2, i2Index) => {
        //     tagHtml += `<h2 style="font-size:14pt;margin-bottom:20px">${i2Index +
        //       1}、${
        //       i2.jsonData.anotherName
        //         ? i2.jsonData.anotherName
        //         : i2.jsonData.name
        //     }</h2>`;
        //     dire += `<div style="font-size:11pt;margin:10px 0;margin-left:50px">${i2Index +
        //       1}、${
        //       i2.jsonData.anotherName
        //         ? i2.jsonData.anotherName
        //         : i2.jsonData.name
        //     }</div>`;
        //     if (showBrief) {
        //       tagHtml += `<div style="font-size:10.5pt;font-style:italic;margin-bottom:10px;color:#6b798e">${i2.jsonData.result}</div>`;
        //     }
        //     if (i2.jsonData.eChartData) {
        //       console.log(
        //         await this.getEChartsImageSrc(i2.jsonData.eChartData)
        //       );
        //       // tagHtml += `<div>${await this.getEChartsImageSrc(
        //       //   i2.jsonData.eChartData
        //       // )}</div>`;
        //       // tagHtml+=`<img src="${await this.getEChartsImageSrc(i2.jsonData.eChartData)}" style="width:400px;height:400px;"/>`
        //     }
        //     let _content = md.render(i2.jsonData.content);

        //     tagHtml += `<div style="font-size:10.5pt;margin-bottom:10px">${_content}</div>`;
        //   });

        //   tagHtml += "</div>";
        //   dire += "</div>";
        //   analysisHtml += tagHtml;
        //   directoryHtml += dire;
        // });

        for (let c = 0; c < tagList.length; c++) {
          let i = tagList[c];
          let dire = `<div>`;
          let tagHtml = `<div style="margin-bottom:0.5in">`;
          if (i.value == 0) {
            i.dataList = i.dataList.filter(i2 => i2.tIndex != 2);
          }
          i.dataList.sort((a, b) => a.tIndex - b.tIndex);
          tagHtml += `<h1 style="font-size:16pt;margin-bottom:-1in">${
            this.tag[i.value]
          }、${i.name}</h1>`;
          dire += `<p style="font-size:14pt;margin-bottom:-0.8in">${
            this.tag[i.value]
          }、${i.name}</p>`;

          for (let d = 0; d < i.dataList.length; d++) {
            let i2 = i.dataList[d];
            let i2Index = d;
            tagHtml += `<h2 style="font-size:14pt;margin-bottom:-1in">${i2Index +
              1}、${
              i2.jsonData.anotherName
                ? i2.jsonData.anotherName
                : i2.jsonData.name
            }</h2>`;
            dire += `<p style="font-size:11pt;margin-bottom:-0.8in;margin-left:0.1in">${i2Index +
              1}、${
              i2.jsonData.anotherName
                ? i2.jsonData.anotherName
                : i2.jsonData.name
            }</p>`;
            if (showBrief) {
              tagHtml += `<p style="font-size:10.5pt;font-style:italic;margin-bottom:-0.7in;color:#6b798e">${i2.jsonData.result}</p>`;
            }
            if (i2.jsonData.eChartData) {
              tagHtml += `<img src="${await this.getEChartsImageSrc(
                i2.jsonData.eChartData
              )}"/>`;
            }

            if (i2.jsonData.CH && i2.jsonData.RT) {
              tagHtml += `<div>
								<img src=''>
								</div>`;
            }

            let _content = md.render(i2.jsonData.content);

            tagHtml += `<p style="font-size:10.5pt;margin-bottom:-0.5in">${_content}</p>`;
          }
          tagHtml += "</div>";
          dire += "</div>";
          analysisHtml += tagHtml;
          directoryHtml += dire;
        }
        directoryHtml += "</div>";
        // this.loading = false;
        // return console.log(analysisHtml);
        // return console.log(analysisHtml);
        let _html = `
			<div>
				<p style="width:100vw;margin-bottom:1.5in">*分析结果仅供参考</p> 
				<p style="font-size:28pt;width:100vw;text-align:center;">课堂观察报告</p>
				<p style="font-size:10pt;width:100vw;text-align:center;margin-bottom:0.6in">报告生成时间：${new Date().toLocaleString()}</p>
				<div style="font-size:16pt;width:100vw;text-align:center;margin-bottom:1in">
					<p style="font-size:20pt;margin-bottom:0.7in">《${bmData.courseName}》</p>
					<p style="margin-bottom:-1in">授课老师：${bmData.teacherName ? bmData.teacherName : "未填写"}</p>
					<p style="margin-bottom:-1in">授课年级：${bmData.grade ? bmData.grade : "未填写"}</p>
					<p style="margin-bottom:-1in">授课科目：${bmData.subject ? bmData.subject : "未填写"}</p>
					<p style="margin-bottom:-1in">授课时间：${bmData.time ? bmData.time : "未填写"}</p>
				</div>
				<div style="font-size:16pt;width:100vw;text-align:center;margin-bottom:0.5in">
					<img src="${qRCodeSrc}" style="width:150px;height:150px;margin:auto;"/>
					<p>扫码查看网页版</p>
				</div>
			</div>
			${directoryHtml}

			<div>
				${analysisHtml}
			</div>
			`;
        this.generateDocx(`《${bmData.courseName}》课堂观察报告`, _html);
        this.loading = false;
      } catch (e) {
        console.log(e);
        this.$message.error("导出失败");
        this.loading = false;
      }
    },
    getQrCodeImageSrc(url) {
      return new Promise((resolve, reject) => {
        let qrcode = new QRCode(document.createElement("div"), {
          text: url, // 需要转换为二维码的内容
          width: 150,
          height: 150,
          colorDark: "#000000",
          colorLight: "#ffffff",
          correctLevel: QRCode.CorrectLevel.H
        });
        let img = qrcode._el.getElementsByTagName("img")[0];
        img.onload = () => {
          resolve(img.src);
        };
      });
    },
    getEChartsImageSrc(option) {
      return new Promise(resolve => {
        let hiddenDiv = document.createElement("div");
        hiddenDiv.style.width = "600px";
        hiddenDiv.style.height = "500px";
        hiddenDiv.style.position = "absolute";
        hiddenDiv.style.left = "-9999px"; // 隐藏div
        document.body.appendChild(hiddenDiv);

        // 初始化图表
        let myChart = echarts.init(hiddenDiv);

        // 设置图标配置
        myChart.setOption(option);

        myChart.on("finished", () => {
          // 获取图表的图片
          let base64Image = myChart.getDataURL({
            type: "png", // 图片格式
            pixelRatio: 1, // 图像清晰度
            backgroundColor: "#fff" // 背景颜色
          });

          resolve(base64Image);
          // 清除隐藏的div和图表实例
          document.body.removeChild(hiddenDiv);
          myChart.dispose();
        });
      });
    },
    // 导出docx
    async generateDocx(name, html) {
      // 将html文件中需要用到的数据挂载到store上
      const content = `<!DOCTYPE html>
      <html xmlns:v='urn:schemas-microsoft-com
      :vml'xmlns:o='urn:schemas-microsoft-com:office
      :office'xmlns:w='urn:schemas-microsoft-com:office
      :word'xmlns:m='http://schemas.microsoft.com/office/2004/12/omml'
      xmlns='http://www.w3.org/TR/REC-html40' 
      xmlns='http://www.w3.org/1999/xhtml'>
      <head>
          <meta charset="UTF-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>${name}</title>
          <style>
						*{
							font-family: '宋体';
							margin:0;
							padding:0;
							line-height:1;
						}
            table {
              border-collapse: collapse; /* 折叠边框 */
              width: 100%;
							font-size:10.5pt;
            }
            th, td {
              border: 1px solid black; /* 线条样式 */
              padding: 8px;
              text-align: left;
							font-size:10.5pt;
            }
						ol,ul{
							margin:0;
							padding:0;
							margin-right:-1in;
						}
						li{
							margin-bottom:0.1in
							margin-right:-1in;
						}
						p{
							line-height:1;
							margin:0;
							padding:0
						}
          </style>
      </head>
      <body>
      ${html}
      </body>
      </html>`;
      // console.log(content)
      // return console.log(content)
      // debugger
      let blob = htmlDocx.asBlob(content);

      // const uploadFile = new File([blob], `${name}.docx`, {
      //   type:
      //     "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      // });
      saveAs(blob, `${name}.docx`);
      return true;
      // this.beforeUploadHtml(uploadFile);
    },
    beforeUploadHtml(event) {
      var file = event;
      var credentials = {
        accessKeyId: "AKIATLPEDU37QV5CHLMH",
        secretAccessKey: "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"
      }; //秘钥形式的登录上传
      window.AWS.config.update(credentials);
      window.AWS.config.region = "cn-northwest-1"; //设置区域

      var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } }); //选择桶
      var _this = this;

      if (file) {
        var params = {
          Key:
            file.name.split(".")[0] +
            new Date().getTime() +
            "." +
            file.name.split(".")[file.name.split(".").length - 1],
          ContentType: file.type,
          Body: file,
          "Access-Control-Allow-Credentials": "*",
          ACL: "public-read"
        }; //key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
        var options = {
          partSize: 2048 * 1024 * 1024,
          queueSize: 2,
          leavePartsOnError: true
        };
        bucket
          .upload(params, options)
          .on("httpUploadProgress", function(evt) {
            //这里可以写进度条
            // console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
          })
          .send(function(err, data) {
            if (err) {
              _this.$message.error("上传失败");
            } else {
              console.log(data.Location);
            }
          });
      }
    },
    // 分享
    shareBtn() {
      // if(!this.fileId)return;
      // this.dialogVisibleShare = !this.dialogVisibleShare;
      this.$refs.sharePdfRef.open();
    },
    // 审核
    examine() {
      if (!this.tid) return;
      window.parent.postMessage(
        {
          tools: "classroom_observation_ob_comment",
          type: this.tid
        },
        "*"
      );
    },
    // 主页
    home() {
      this.$message.info("主页");
    },
    delCourse(_value) {
      this.$confirm("此操作将永久删除该课堂, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // this.optionData.splice(
          // 	this.optionData.findIndex((item) => item.value == _value),
          // 	1
          // );
          // this.tid = this.optionData[0] ? this.optionData[0].value : "";
          // this.changeTid(this.tid);
          // this.$message({
          // 	type: "success",
          // 	message: "删除成功!",
          // });
          let params = {
            tid: _value
          };
          this.ajax
            .post(
              "https://gpt4.cocorobo.cn/update_classroom_observation_isdel",
              params
            )
            .then(res => {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.tid = "";

              // 清空tid
              this.tid = "";
              this.fileIdId = "";
              this.fileId = "";
              this.getCourseList().then(_ => {
                if (!this.tid) {
                  this.$refs.messageAreaRef.init();
                  this.$refs.chatAreaRef.init();
                } else {
                  this.getFileIdId();
                  this.$refs.messageAreaRef.getData();
                  this.$refs.chatAreaRef.getData();
                }
              });
            });
        })
        .catch(() => {});
    },
    // 获取修改fileId的ID
    getFileIdId() {
      if (!this.tid) return;
      let pram = {
        tid: this.tid,
        type: "10"
      };
      this.fileIdId = "";
      this.fileId = "";
      this.ajax
        .post("https://gpt4.cocorobo.cn/get_classroom_observation_new", pram)
        .then(res => {
          let _data = res.data.FunctionResponse.result.length
            ? JSON.parse(res.data.FunctionResponse.result)
            : [];
          if (_data.length <= 0) return;
          this.fileIdId = _data[0].id;
          if (_data[0].jsonData != "") {
            this.fileId = JSON.parse(_data[0].jsonData).file_ids;
          } else {
            this.fileId = "";
          }
        });
    },
    // 切换录音文件
    changeAudioUrl(data) {
      this.$refs.messageAreaRef.changeAudioUrl(data);
    },
    changeChatAreaAudioUrl(data) {
      this.$refs.chatAreaRef.changeAudioUrl(data.url);
    },
    getCourseList() {
      this.loading = true;
      return new Promise((resolve, reject) => {
        this.ajax
          .post("https://gpt4.cocorobo.cn/get_classroom_observation_all", {
            userid: this.userId
          })
          .then(res => {
            let _data = res.data.FunctionResponse.result;
            let _result = [];
            try {
              _result = _data ? JSON.parse(_data) : [];
            } catch (error) {
              _result = [];
            }

            if (_result.length <= 0) {
              this.loading = false;
              resolve();
              return;
            }
            let _optionData = _result.map(item => {
              item.jsonData = item.jsonData ? JSON.parse(item.jsonData) : {};
              return {
                label: item.jsonData.courseName
                  ? item.jsonData.courseName
                  : `${item.tId}课堂`,
                value: item.tId,
                id: item.id
              };
            });
            _optionData = _optionData.filter(i => i.label != "" && i.tId != "");
            this.optionData = _optionData;
            if (this.optionData.length > 0) {
              this.$refs.chatAreaRef.$refs.startPageRef.showIntroduce = false;
            }
            this.loading = false;
            resolve();
          })
          .catch(e => {
            console.log(e);
            resolve();
            this.$message.error("获取课堂列表失败");
          });
      });
    },
    updateTranscription({ transcriptionData, editorBarData }, fn) {
      this.$refs.messageAreaRef.updateMessageTranscription(
        {
          transcriptionData,
          editorBarData
        },
        fn
      );
    },
    changeTranscription({ transcriptionData, editorBarData }) {
      this.$refs.chatAreaRef.changeEditorBar({
        transcriptionData,
        editorBarData
      });
    },
    changeOptionData(_tid, _newObj) {
      let _index = this.optionData.findIndex(i => i.value == _tid);
      if (_index != -1) {
        this.optionData[_index] = { ...this.optionData[_index], ..._newObj };
        this.$forceUpdate();
      }
    },
    updateTime(time) {
      this.createTime = time;
    },
    // 修改课程名称
    changeCourse(item) {
      this.$refs.changeCourseNameDialogRef.open(item);
      // console.log(item);
    },
    // 修改课程名称确定
    changeCourseSuccess(data) {
      this.loading = true;
      if (this.tid == data.tid) {
        this.$refs.messageAreaRef.bmData.jsonData.courseName = data.name;
        this.$refs.messageAreaRef
          .saveData(this.$refs.messageAreaRef.bmData)
          .then(res => {
            this.loading = false;
            this.optionData.find(i => i.id == data.id).label = data.name;
            this.$message.success("修改成功");
          });
      } else {
        this.ajax
          .post("https://gpt4.cocorobo.cn/get_classroom_observation_new", {
            tid: data.tid,
            type: 0
          })
          .then(res => {
            let _data = res.data.FunctionResponse.result;
            _data = JSON.parse(_data);
            let _bmData = _data.find(i => i.tIndex == 0);
            _bmData.jsonData = JSON.parse(_bmData.jsonData);
            _bmData.jsonData.courseName = data.name;
            this.$refs.messageAreaRef.saveData(_bmData).then(res => {
              this.loading = false;
              this.optionData.find(i => i.id == data.id).label = data.name;
              this.$message.success("修改成功");
            });
          })
          .catch(e => {
            console.log(e);
            this.$message.error("修改失败");
            this.loading = false;
          });
      }
    },
    //保存词频词汇分析
    saveWordFrequency({ _sentence = 0, _words = 0 }) {
      this.$refs.messageAreaRef.saveWordFrequency({ _sentence, _words });
    }
  },
  mounted() {
    this.getCourseList().then(_ => {
      if (!this.tid) {
        return this.$refs.messageAreaRef.getDefaultData();
      }
      this.getFileIdId();
      this.$refs.messageAreaRef.getData();
      this.$refs.chatAreaRef.getData();
    });
  }
};
</script>

<style scoped>
.classroomObservation {
  min-width: 1500px;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

.co-header1 {
  width: 100%;
  height: 46px;
  background-color: #060e17;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 0 20px;
}

.co-h1-left {
  width: auto;
  height: 22px;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  padding: 0 20px;
}

.co-h1-l-icon {
  color: #5d6268;
  width: 16px;
  height: 16px;
  margin-right: 10px;
}

.co-h1-l-router {
  display: flex;
  align-items: center;
  color: white;
  font-size: 14px;
}

.co-h1-l-router > span {
  margin: 0 5px;
}

.co-h1-l-r-up {
  color: #5d6268;
  cursor: pointer;
}

.co-h1-l-r-up:hover {
  color: white;
}

.co-j1-l-r-down {
  cursor: pointer;
}

.co-h1-l-r-rightIcon {
  font-size: 16px;
  color: #5d6268;
}

.co-header2 {
  width: 100%;
  height: 42px;
  min-height: 42px;
  max-height: 42px;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 0 20px;
}

.co-h2-left {
  width: auto;
  height: 22px;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.co-h2-l-icon {
  width: 20px;
  height: 20px;
  position: relative;
  background: url("../../../assets/icon/classroomObservation/courseIcon.svg")
    no-repeat;
  /* transform: rotate(45deg); */
  cursor: pointer;
  background-size: 100% 100%;
}
.co-h2-l-hr {
  width: 2px;
  height: 20px;
  background-color: #e7e7e7;
  border-radius: 10px;
  margin: 0 10px;
}

.co-h2-right {
  width: auto;
  height: 100%;
  display: flex;
  align-items: center;
}

.co-h2-r-btn {
  width: auto;
  box-sizing: border-box;
  padding: 0 10px;
  height: 30px;
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  margin: 0 10px;
  box-sizing: border-box;
  border: 1px solid rgba(134, 179, 253, 1);
  /* border: solid 1px #3681FC; */
  border-radius: 5px;
}

.ca-h2-r-noActive {
  opacity: 0.5 !important;
  cursor: not-allowed !important;
}

.co-h2-r-btn2 {
  width: auto;
  box-sizing: border-box;
  padding: 10px;
  height: 30px;
  display: flex;
  align-items: center;
  cursor: pointer;
  margin: 0 10px;
  box-sizing: border-box;
  border-radius: 5px;
  box-shadow: 0px 4px 10px 0px rgba(29, 57, 131, 0.08);

  /* box-shadow: 1px 1px 20px 4px rgba(29, 57, 131, 0.05); */
}

.co-h2-r-btn2 > img {
  width: 20px;
  height: 20px;
}

.co-h2-r-btn > span:nth-child(1) {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}

.co-h2-r-b-icon1 {
  background: url("../../../assets/icon/classroomObservation/six.svg") no-repeat;
  background-size: 100% 100%;
}

.co-h2-r-b-icon2 {
  background: url("../../../assets/icon/classroomObservation/Syan.svg")
    no-repeat;
  background-size: 100% 100%;
}

/* .co-h2-r-b-icon2 {
	background: url("../../../assets/icon/classroomObservation/daoChu.png")
		no-repeat;
	background-size: 100% 100%;
}
.co-h2-r-b-icon3 {
	background: url("../../../assets/icon/classroomObservation/Syan.png")
		no-repeat;
	background-size: 100% 100%;
} */

/* .co-h2-r-blueBtn {
	background: rgba(134, 179, 253, 1);

	color: white;
} */

.co-main {
  width: 100%;
  flex: 1;
  display: flex;

  /* align-items: center; */
  /* justify-content: center; */
}

.co-m-left {
  box-sizing: border-box;
  flex: 1;
  min-width: 650px;
}

.co-m-right {
  height: 100%;
  flex: 1;
  box-sizing: border-box;
  min-width: 450px;

  overflow: auto;
}

.co_h2_l_t_select >>> .el-input__inner {
  border: none;
}
/* .co_h2_l_t_select >>> .el-input__suffix {
	display: none;
} */

.co_h2_l_del {
  width: 35px;
  height: 35px;
  margin-left: 10px;
  border-radius: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.co_h2_l_del > span {
  width: 20px;
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url("../../../assets/icon/classroomObservation/del.svg") no-repeat;
  background-size: 100% 100%;
}

.co_h2_l_del:hover {
  background-color: #eaeef1;
}

.selectBox {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.controlsBox {
  display: flex;
  align-items: center;
  width: auto;
  height: 100%;
  display: none;
}

.selectBox:hover > .controlsBox {
  display: flex;
}

.changeSelect {
  width: 16px;
  height: 16px;
  /* display: none; */
  align-items: center;
  justify-content: center;
  background: url("../../../assets/icon/classroomObservation/editIcon.svg")
    no-repeat;
  background-size: 100% 100%;
  box-sizing: border-box;
  margin-right: 10px;
}

.delSelect {
  width: 16px;
  height: 16px;
  /* display: none; */
  align-items: center;
  justify-content: center;
  background: url("../../../assets/icon/classroomObservation/del.svg") no-repeat;
  background-size: 100% 100%;
  box-sizing: border-box;
  /* transform: translateY(7px); */
}
</style>
