<template>
  <div class="outcome" v-loading="saveLoading">
    <bar @cutPage="cutPage(1)" :tit="'分析结果'" :backPage="0"></bar>

		<div class="o_content">
			<van-tabs color="#409EFF" style="width:100%;height: 100%;display: flex;flex-direction: column;" v-model="showIndex" swipeable animated scrollspy @click="changeShowIndex" swipe-threshold="3">
				<van-tab v-for="(item,index) in dialogTagList" :name="item.value" :title="item.name" :key="item.value">
					<div class="o_c_item">
						<analysisItem
      			  ref="analysisItemRef"
      			  v-for="(item, index) in dataList"
      			  :key="item.id"
      			  :data="item"
      			  v-show="showIndex === item.Type"
      			  v-if="!(item.Type == 0 && item.tIndex == 2)"
      			  :analysisList="analysisList"
      			  :bmData="bmData"
      			  :fileId="fileId"
							:dataList="dataList"
      			/>
					</div>
				</van-tab>
			</van-tabs>
		</div>
    <!-- <div class="sortList">
      <div>
				<div :class="[showIndex == 0 ? 'sortActive' : '']" @click.stop="changeShowIndex(0)">通用</div>
      	<div :class="[showIndex == 1 ? 'sortActive' : '']" @click.stop="changeShowIndex(1)">学科</div>
      	<div :class="[showIndex == 2 ? 'sortActive' : '']" @click.stop="changeShowIndex(2)">扩展</div>
			</div>
      <span @click.stop="addAnalysis">＋</span>
    </div>

    <div class="stencilList">
      <analysisItem
        ref="analysisItemRef"
        v-for="(item, index) in dataList"
        :key="item.id"
        :data="item"
        v-show="showIndex === item.Type"
        v-if="!(item.Type == 0 && item.tIndex == 2)"
        :analysisList="analysisList"
        :bmData="bmData"
        :fileId="fileId"
				:dataList="dataList"
      />
    </div> -->

    <div class="botBtn">
      <div class="shareBtn" @click.stop="share()">
        <img src="../../assets/images/classObserve/share.png" alt="" />
        <span>分享</span>
      </div>

      <div class="bb_box">
        <div class="btn" @click.stop="saveTemplate()">
          保存模板
        </div>
        <!-- :class="['btn', fileId ? '' : 'btnDis']" -->
        <div class="btn" @click.stop="AllAnalysis()">
          一键分析
        </div>

        <div class="btn" @click.stop="viewTheReport()">
          查看报告
        </div>
      </div>
    </div>
    <van-popup v-model="showPopup">
      <div class="popupCon">
        <div class="tit">模板信息</div>
        <div class="bri">请根据提示补充模版信息</div>
        <div>
          <el-input v-model="form.name" placeholder="模版名称"></el-input>
          <el-input type="textarea" :rows="3" resize="none" v-model="form.brief" placeholder="模版简介"></el-input>
          <el-select v-model="form.subject" placeholder="所属学科" style="z-index: 2026;">
            <el-option
              v-for="item in subjectList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>

        <div class="switch">
          <span style="margin-right: 5px;">公开到社区</span
          ><el-switch v-model="form.per" active-color="rgba(54, 129, 252, 1)"> </el-switch>
        </div>
      </div>
      <div class="btnS">
        <div @click="cancelSaveTemplate">取消</div>
        <div style="color: rgba(54, 129, 252, 1);" @click="saveInfo">保存</div>
      </div>
    </van-popup>

    <van-popup v-model="sharePopup">
      <div class="saveBox">
        <div class="sb_imgArea">
          <span class="qrcodeUrl" ref="qrCodeUrl"></span>
        </div>
        <div class="sb_inputArea">
          <el-input class="sc_fu_input" style="color: black" disabled v-model="origin">
            <template slot="append"
              ><div class="sc_fu_copyBtn" @click.stop="copy(origin)">
                复制链接
              </div></template
            >
          </el-input>
        </div>
      </div>
      <div class="btnS">
        <div @click="sharePopup = false">取消</div>
        <div style="color: rgba(54, 129, 252, 1);" @click="sharePopup = false">确定</div>
      </div>
    </van-popup>
    <div class="o_report" v-if="showReport">
      <div class="o_r_top">
        <span>查看报告</span>
        <div @click.stop="showReport = false">×</div>
      </div>
      <div class="o_r_box">
        <iframe v-if="origin" :src="origin" width="100%" height="100%"></iframe>
      </div>
    </div>
    <addTel ref="addTelRef" :data="analysisList" @success="addAnalysisByList" />
  </div>
</template>

<script>
import bar from './components/bar.vue'
import analysisItem from './components/analysisItem.vue'
import { Dialog } from 'vant'
import { insertClassroomTemplateRequest,insertNewObsRequest } from '@/api/classObserve'
import QRCode from 'qrcodejs2'
import addTel from './addTel.vue'
let OpenCC = require("opencc-js");
export default {
  components: {
    bar,
    analysisItem,
    addTel
  },
  props: {
    page: {
      type: Number,
      default: 1
    },
    dataList: {
      type: Array,
      default: () => []
    },
		dialogTagList:{
			type:Array,
			default:()=>[]
		},
    analysisList: {
      type: Array,
      default: () => []
    },
    bmData: {
      type: Object,
      default: () => {}
    },
    fileId: {
      type: String,
      default: ''
    },
    tid: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      userId: this.$store.state.user.id,
      abuShow: false,
      cellShow: false,
      showPopup: false,
      sharePopup: false,
      showIndex: 0,
      saveLoading: false,
      form: {
        name: '',
        brief: '',
        subject: '',
        pre: false
      },
			menuList:[],
      subjectList: [
        { value: '1', label: '语文' },
        { value: '2', label: '数学' },
        { value: '3', label: '英语' },
        { value: '4', label: '科学' },
        { value: '5', label: '物理' },
        { value: '6', label: '化学' },
        { value: '7', label: '生物' },
        { value: '8', label: '历史' },
        { value: '9', label: '地理' },
        { value: '10', label: '政治' }
      ],
      origin: '',
      showReport: false
    }
  },
  methods: {
    cutPage(page) {
      this.$emit('cutPage', page)
    },
    addAnalysis() {
      this.$refs.addTelRef.open(this.showIndex)
    },
    ctrlShow() {
      this.cellShow = !this.cellShow
    },
    showAbu() {
      this.abuShow = true
    },
    changeShowIndex(newIndex) {
      this.showIndex = newIndex
    },
    delItem(item) {
      Dialog.confirm({
        title: '删除分析',
        message: `确定删除 "${item.jsonData.name}" 这个分析？`
      })
        .then(() => {
          this.$parent.delAnalysis(item)
        })
        .catch(() => {
          console.log('不删除')
          // on cancel
        })
    },
    share() {
      // return;
      this.sharePopup = true
      this.$nextTick(() => {
        let url = `https://beta.cloud.cocorobo.cn/aigpt/#/classroom_observation_board?tid=${this.tid}`
        this.origin = url
        this.$refs.qrCodeUrl.innerHTML = ''
        var qrcode = new QRCode(this.$refs.qrCodeUrl, {
          text: url, // 需要转换为二维码的内容
          width: 250,
          height: 250,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.H
        })
      })
    },
    copy(content) {
      // 创建临时textarea元素
      const tempInput = document.createElement('textarea')
      tempInput.value = content // 设置要复制的内容
      // 隐藏元素
      tempInput.style.position = 'absolute'
      tempInput.style.left = '-9999px'
      // 将元素添加到DOM中
      document.body.appendChild(tempInput)
      // 选中元素内容
      tempInput.select()
      // 执行复制操作
      document.execCommand('copy')
      // 移除临时元素
      document.body.removeChild(tempInput)
      this.$toast.success('复制成功')
    },
    viewTheReport() {
      this.showReport = true
      let url = `https://beta.cloud.cocorobo.cn/aigpt/#/classroom_observation_board?tid=${this.tid}`
      this.origin = url
    },
    AllAnalysis() {
      if (!this.fileId) return this.$toast('请先上传文件或者录音')
      this.$refs.analysisItemRef.forEach(i => {
        i.optimize()
      })
      this.$toast.success('一键分析成功')
    },
    saveTemplate() {
      this.showPopup = !this.showPopup
    },
    cancelSaveTemplate() {
      this.form = {
        name: '',
        brief: '',
        subject: '',
        per: false
      }
      this.showPopup = false
    },
    saveInfo() {
      if (!this.form.name.trim()) return this.$toast.fail('请填写模板名称')
      if (!this.form.subject.trim()) return this.$toast.fail('请选择科目')
      // if(!this.form.brief.trim())return this.$toast.fail("请填写模板简介");

      this.saveLoading = true
      let _data = JSON.parse(JSON.stringify(this.dataList))
      let _result = []

      _data.forEach(i => {
        if (i.Type == 0 && i.tIndex == 2) return
        i.jsonData.content = ''
        i.jsonData.dataFileList = []
        i.jsonData.fileList = []
        i.createtime = ''
        ;(i.id = ''), (i.tId = ''), (i.userid = '')
        _result.push(i)
      })

      let params = [
        {
          title: this.form.name,
          subject: this.form.subject,
          uid: this.userId,
          brief: this.form.brief,
          per: this.form.per ? 1 : 0,
          jsonData: JSON.stringify(_result)
        }
      ]

      insertClassroomTemplateRequest(params)
        .then(res => {
          this.$toast.success('保存为模板成功')
          this.cancelSaveTemplate()
          this.saveLoading = false
        })
        .catch(e => {
          this.$toast.fail('另存为模板失败')
          console.log(e)
        })
    },
    addAnalysisByList(list) {
			this.saveLoading = true;
      this.$refs.addTelRef.close()
			let promises = [];
			list.forEach((item,index)=>{
				promises.push(this.addAnalysisItem(item,index))
			})
			Promise.all(promises).then(()=>{
				this.saveLoading = false;
				this.$toast.success('添加成功')
			})
    },
    addAnalysisItem(id,index = 0) {
      return new Promise(resolve => {
        
				let converter = OpenCC.Converter({
						from:'hk',
						to:'cn'
				})
        let assistant = this.analysisList.find(i => i.id == id)
        let newIndexData = this.dataList
          .filter(i => i.Type == assistant.type)
          .sort((a, b) => new Date(a.createtime) - new Date(b.createtime))
        newIndexData = newIndexData.length ? newIndexData[newIndexData.length - 1] : null
        let newIndex = newIndexData ? newIndexData.tIndex + 1 : assistant.type == 0 ? 2 : 0
        let params = {
          index: newIndex+index,
          userid: this.userId,
          json_data: JSON.stringify({
            name: assistant.name,
						anotherName:assistant.name,
            result: assistant.detail,
						mId: assistant.id,
						echartsType: assistant.echartsType,
            fileList: [],
            dataFileList: [],
            content: ''
          }),
          tid: this.tid,
          type: assistant.type.toString()
        }
				insertNewObsRequest(params).then(res=>{
					let _data = res.FunctionResponse;
						if (_data.message && converter(_data.message) == converter("创建成功")) {
							let _result = JSON.parse(_data.result)[0];
							_result.jsonData = JSON.parse(_result.jsonData);
							this.$parent.dataList.push(_result)
							this.$nextTick(()=>{
								this.$refs.analysisItemRef.forEach(i=>{
									if(i.data.id===_result.id){
										i.optimize();
									}
								})
							})
							resolve();
						} else {
							this.$toast.fail(`"${assistant.title}"添加失败`);
							resolve();
						}
				})
				
      })
    },
		
  }
}
</script>

<style lang="scss" scoped>
.outcome {
  height: calc(100%);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-sizing: border-box;
}
/*
	.sortList {
  width: 100%;
	max-width: calc(100% - 15px);
  display: flex;
  box-sizing: border-box;
  justify-content: space-between;
  margin-top: 55px;
  height: auto;
  border-bottom: 0.5px rgba(231, 231, 231, 1) solid;
	background-color: red;
  span {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 40px;
    height: auto;
    font-size: 20px;
    margin-right: 15px;
  }
  div {
    flex: 1;
    text-align: center;
    font-size: 16px;
    font-weight: 400;
    transition: 0.3s;
    position: relative;
    padding: 10px;
  }
  .sortImg {
    display: flex;
    align-items: center;
    justify-content: center;
    border-left: 0.5px rgba(231, 231, 231, 1) solid;
  }
  .sortActive {
    color: #3681fc;
    font-weight: bold;
  }
}
.stencilList {
  flex: 1;
  padding: 15px;
  box-sizing: border-box;
  overflow: auto;
  background-image: linear-gradient(to bottom, #fff 0%, #ebf1fd 100%);
  .tit {
    color: rgba(0, 0, 0, 0.9);
    font-size: 14px;
    font-weight: 600;
    margin-left: 5px;
  }
  .outcomeCon {
    // display: flex;
    min-height: 50px;
    border: 0.5px #ccc solid;
    align-items: center;
    border-radius: 5px;
    min-height: 40px;
    padding: 0 10px;
  }
}
*/
.o_content{
	width: 100%;
	flex:1;
	margin-top: 55px;
	height: auto;
	// background-color: red;
	.o_c_item{
		width: 100%;
		height: calc(100vh - 164px);
		flex: 1;
		overflow: auto;
		box-sizing: border-box;
		padding: 10px;
		// background:yellow;
	}
}
.botBtn {
  background-color: #fff;
  width: 100%;
  padding: 10px 10px;
  padding-left: 15px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  .shareBtn {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-right: 20px;
    justify-content: space-between;
    font-size: 12px;
    font-size: 400;
    color: rgba(4, 0, 0, 1);
  }
  .bb_box {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    justify-content: space-around;
    padding: 0;
    .btn {
      flex: 1;
      background-color: rgba(54, 129, 252, 1);
      color: #fff;
      height: 45px;
      border-radius: 10px;
      display: flex;
      font-size: 16px;
      margin: 0 5px;
      justify-content: center;
      align-items: center;
    }
    .btnDis {
      background-color: rgb(165, 165, 165);
    }
  }
}
.abu {
  background-color: #fff;
  width: 100px;
  border-radius: 6px;
  //   padding: 10px 10px;
  box-shadow: 0px 8px 10px -5px rgba(0, 0, 0, 0.08);
  box-shadow: 0px 16px 24px 2px rgba(0, 0, 0, 0.04);
  box-shadow: 0px 6px 30px 5px rgba(0, 0, 0, 0.05);
  .abuBtn {
    display: flex;
    align-items: center;
    padding: 10px 15px;
    font-size: 12px;
    font-weight: 400;
    img {
      margin-right: 5px;
    }
  }
}
.outcomeBtn {
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  div {
    display: flex;
    img {
      width: 16px;
      height: 16px;
    }
  }
}

/deep/ .van-popup--center {
  border-radius: 10px;
  width: 280px;
}
/deep/.el-input__inner {
  border: 0;
  background-color: rgba(243, 243, 243, 1);
}
/deep/.el-select {
  width: 100%;
}
/deep/.el-textarea__inner {
  border: 0;
  background-color: rgba(243, 243, 243, 1);
  margin: 10px 0;
}

/deep/.van-overlay {
  z-index: 1999 !important;
}

/deep/.vant-tabs__content{
		flex: 1;
}

/deep/.van-popup {
  z-index: 2000 !important;
}

.popupCon {
  padding: 10px 15px;
  .tit {
    width: 100%;
    text-align: center;
    font-size: 18px;
    font-weight: 600;
    padding: 10px 0;
  }
  .bri {
    font-size: 16px;
    font-weight: 400;
    text-align: center;
    color: rgba(0, 0, 0, 0.6);
    padding-bottom: 10px;
  }
  .switch {
    margin: 10px 0;
    font-size: 14px;
    // font-weight: 600;
    color: rgba(0, 0, 0, 0.9);
  }
}
.btnS {
  display: flex;
  border-top: 0.5px solid rgba(231, 231, 231, 1);
  justify-content: space-between;
  div {
    flex: 1;
    text-align: center;
    padding: 17px 0;
    font-size: 14px;
    font-weight: 600;
  }
}

.saveBox {
  padding: 10px 15px;
  .sb_imgArea {
    width: 100%;
    height: auto;
    display: flex;
    justify-content: center;
    padding: 20px 0;
  }
}

.o_report {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background-color: red;
  z-index: 999;
  .o_r_top {
    width: 100%;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #15233e;
    position: relative;
    span {
      font-size: 16px;
      font-weight: bold;
      color: #fff;
    }
    div {
      position: absolute;
      right: 10px;
      color: #fff;
      font-size: 18px;
      height: auto;
      width: auto;
      padding: 2px 7px;
      border-radius: 5px;
      display: flex;
      box-sizing: border-box;
      // border: solid 1px #fff;
      justify-content: center;
      align-items: center;
      // background-color: #93b0eb;
    }
  }
  .o_r_box {
    width: 100%;
    height: calc(100% - 40px);
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;
  }
}
</style>
