<template>
  <div class="choseCheck">
    <div class="cc_top">
      <div class="cc_t_left">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item
            :to="{
              path:
                '/test?userid=' +
                userid +
                '&oid=' +
                oid +
                '&org=' +
                org +
                '&role=' +
                role
            }"
            >表单管理</el-breadcrumb-item
          >
          <el-breadcrumb-item>
            <span style="color: rgb(15, 126, 255)">AI分析</span>
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="cc_t_right">
        <div class="r_pub_button_retrun" @click="back">返回</div>
      </div>
    </div>
    <div class="cc_bottom" v-loading="loading ">
			<div class="cc_b_left" v-loading="getFileLoading">
				<div v-if="courseInfoList">
					<aiBoxRight :courseId="aiBoxRightCid" :worksArray="courseInfoList" ref="aiChat" @pushFileData="pushFileData" @clearFileData="clearFileData"></aiBoxRight>
				</div>
			</div>
			<div class="cc_b_right">
				<div class="cc_b_r_menu">

						<div v-for="(item,index) in menuList" @click="changeMenuIndex(index)" :key="index" :class="{'cc_b_r_menu_active':menuIndex==index}">
							<el-tooltip  class="item" effect="dark" :content="item.name" placement="top">
								<span>{{item.name}}</span>
						</el-tooltip>
						</div>

				</div>
				<div class="cc_b_r_content">
					<!-- <iframe
        ref="viframe"
        v-if="showFileUrl"
        style="width: 100%; height: 100%; border: none"
        :src="showFileUrl"
      ></iframe> -->
			<!-- 'https://view.officeapps.live.com/op/view.aspx?src=' +
			encodeURIComponent(showFileUrl) -->
					<!-- <txtView v-if="showFileUrl" :url="showFileUrl"></txtView> -->
					 <csvTableView v-if="showFileUrl" :url="showFileUrl"/>
				</div>
			</div>
		</div>
  </div>
</template>

<script>
import aiBoxRight from '../check/aiBoxRight.vue';
import txtView from './txtView.vue';
import csvTableView from './csvTableView.vue';
export default {
  name: "ChoseCheck",
	components:{
		aiBoxRight,
		txtView,
		csvTableView
	},
  data() {
    return {
      // 组件数据
      userid: this.$route.query.userid,
      oid: this.$route.query.oid,
      org: this.$route.query.org,
      role: this.$route.query.role,
      cid: this.$route.query.cid,
			menuList:[],
			menuIndex:0,
			courseInfoList:[],
			loading:true,
			leftLoading:true,
    };
  },
  methods: {
    // 组件方法
    back() {
      this.goTo(
        "/test?userid=" +
          this.userid +
          "&oid=" +
          this.oid +
          "&org=" +
          this.org +
          "&role=" +
          this.role
      );
    },
    goTo(path) {
      this.$router.push(path);
    },
		getData(){
			if(this.cid){
				this.loading = true
				let cidList = this.cid.split(',')
				let promiseList = []
				cidList.forEach(el=>{
					promiseList.push(this.getCourseData(el))
				})
				Promise.all(promiseList).then(res=>{
					console.log(this.courseInfoList)
					console.log(res);
					this.courseInfoList = res;
					this.loading = false
				})
			}
		},
		getCourseData(courseId) {
      return new Promise((resolve)=>{
				let params = {
        cid: courseId,
        cn: "",
        tim : "",
        tea: ""
      };
      this.ajax
        .get(this.$store.state.api + "getTestWorksNoPageCopy", params)
        .then(async (res) => {
          let testJson = res.data[0][0]
          let works = res.data[1]
          let chapters = this.setJSON(this.setJson2(JSON.parse(JSON.stringify(JSON.parse(res.data[0][0].chapters)))))
          let courseCount11 = []
          let array = []
          let courseIds = []; // 初始化一个空数组来存储所有的courseId
          for (let i = 0; i < works.length; i++) {
            let cJson = this.setJSON(JSON.parse(JSON.stringify(JSON.parse(works[i].courseJson))))
            if (JSON.stringify(cJson) == JSON.stringify(chapters)) {
              let _json = this.JSONSetting(JSON.parse(JSON.stringify(JSON.parse(works[i].courseJson))))
              for (var ja = 0; ja < _json.length; ja++) {
                let _json2 = _json[ja].json;
                if (_json[ja].type == 6) {
                  let courseId = _json2.answer2;
                  courseIds.push(courseId); // 将type为6的courseId添加到数组中
                }
                if (_json[ja].type == 11) {
                  let _answer = _json2.answer2;
                  _answer.length ? courseCount11 = courseCount11.concat(_answer) : '';
                  _json[ja].json.courseId = _answer ? _answer : [];
                  courseIds = courseIds.concat(_answer); // 将type为11的courseId添加到数组中
                }
              }
            }
          }
          // 将所有的courseId去重
          courseIds = Array.from(new Set(courseIds));
          // 使用一个数组来存储所有的courseId后，执行getCourseInfoTestAll
          let courseTitles = {}; // 初始化一个空对象来存储所有的courseTitles
          let params2 = [{
            cid: courseIds.join(",")
          }]

          let data2 = await this.ajax.post(this.$store.state.api + 'getCourseInfoTestAll2', params2);
          let result2 = data2.data[0];
          result2.forEach(i => {
            courseTitles[i.courseId] = i.title;
          });

          for (let i = 0; i < works.length; i++) {
            let cJson = this.setJSON(JSON.parse(JSON.stringify(JSON.parse(works[i].courseJson))))
            if (JSON.stringify(cJson) == JSON.stringify(chapters)) {
              let _json = this.JSONSetting(JSON.parse(JSON.stringify(JSON.parse(works[i].courseJson))))

              _json.forEach(item => {
                if (item.type == 11) {
                  let cid = item.json.answer2
                  let _title = []
                  for(var i = 0; i < cid.length; i++){
                    _title.push(courseTitles[cid[i]])
                  }
                  item.json.answer2 = _title.length ? _title.join(",") : '';
                }
                if (item.type == 6) {
                  let courseId = item.json.answer2;
                  item.json.answer2 = courseTitles[courseId] || '';
                }
              });
              // 更新对应的_json对象的answer2
              array.push({
                courseid: works[i].courseid,
                id: works[i].id,
                userid: works[i].userid,
                name: works[i].username ? works[i].username : '匿名',
                time: works[i].time,
                array: _json,
                cut:0,
                uteaName: works[i].uteaName,
                courseJson: JSON.parse(works[i].courseJson),
              })
            }
          }
					let obj = {courseId:testJson.courseId,name:testJson.title,worksArray:array}
					// this.courseInfoList.push(obj)
					resolve(obj)
        })
        .catch((err) => {
					resolve();
          console.error(err);
        });
			})
    },
		setJSON(json) {
      return json.filter((item) => {
        if (item.array) {
          item.array = item.array.filter((item2) => {
            if (item2.ttype == 1 && item2.json) {
              delete item2.json.answer2
              delete item2.json.score2
              delete item2.json.file
            }
            if (item2.array) {
              item2.array = item2.array.filter((item3) => {
                if (item3.ttype == 1 && item3.json) {
                  delete item3.json.answer2
                  delete item3.json.score2
                  delete item3.json.file
                }
                return item3;
              });
            }
            return item2;
          });
        } else if (item.ttype == 1 && item.json) {
          delete item.json.answer2
          delete item.json.score2
          delete item.json.file
        }
        return item
      });
    },
		JSONSetting(json) {
      let _json = json
      let array = []
      _json.filter((item) => {
        if (item.array) {
          item.array = item.array.filter((item2) => {
            if (item2.ttype == 1 && item2.json) {
              array.push(item2)
            }
            if (item2.array) {
              item2.array = item2.array.filter((item3) => {
                if (item3.ttype == 1 && item3.json) {
                  array.push(item3)
                }
                return item3;
              });
            }
            return item2;
          });
        }
        if (item.ttype == 1 && item.json) {
          array.push(item)
        }
        return item;
      });
      return array;
    },
		setFilter(json) {
      let _json = json
      let array = []
      _json.filter((item) => {
        item.nameFilters = [],
          item.filterParams = {
            name: [],
          }
        if (item.type == 1) {
          for (var i = 0; i < item.json.array.length; i++) {
            item.nameFilters.push({ text: item.json.array[i].option, value: item.json.array[i].option })
          }
        }
        array.push(item)
        return item;
      });
      return array
    },
		setJson2(json) {
      let _json = json;
      // this.type = _json[0].ttype;
      let checkArray = _json.filter((item) => {
        if (item.array) {
          item.array = item.array.filter((item2) => {
            if (item2.ttype == 1 && item2.json && !item2.json.answer2) {
              item2.json.answer2 = [];
            }
            if (item2.array) {
              item2.array = item2.array.filter((item3) => {
                if (item3.ttype == 1 && item3.json && !item3.json.answer2) {
                  item3.json.answer2 = [];
                }
                return item3;
              });
            }
            return (
              (item2.ttype != 1 && item2.array.length > 0) || item2.ttype == 1
            );
          });
        }
        if (item.ttype == 1 && item.json && !item.json.answer2) {
          item.json.answer2 = [];
        }
        return (item.ttype != 1 && item.array.length > 0) || item.ttype == 1;
      });
      return checkArray;

    },
		pushFileData(data){
			this.menuList.push(data);
		},
		clearFileData(){
			this.menuList = []
		},
		changeMenuIndex(index){
			this.menuIndex = index
		}
  },
	computed:{
		showFileUrl(){
			if(this.menuList.length){
				return this.menuList[this.menuIndex].url
			}else{
				return ""
			}
		},
		aiBoxRightCid(){
			let _result = this.cid;

			let _cidList = _result.split(',');
			if(_cidList.length>1){
				_cidList.sort((a, b) => parseInt(b) - parseInt(a));
				_result = _cidList.join(',');
			}

			return _result
		},
		getFileLoading(){
			let _result = this.cid;
			if(this.menuList.length >= _result.split(',').length){
				return false
			}else{
				return true
			}
		}
	},
	mounted(){
		this.getData();
	}
};
</script>

<style scoped>
/* 组件样式 */
.choseCheck {
  width: 100vw;
  height: 100vh;
  overflow: auto;
  box-sizing: border-box;
  padding: 0 20px;
}

.cc_top {
  width: 100%;
  height: 40px;
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.cc_bottom {
  width: 100%;
  height: calc(100% - 40px - 10px);
  overflow: auto;
  background-color: #fff;
	border-radius: 5px;
	display: flex;
}

.cc_b_left{
	width: 50%;
	height: 100%;
}

.cc_b_left>div{
	width: 100%;
	height: 100%;
}

.cc_b_right{
	width: 50%;
	height: 100%;
  max-height: 100%;
  overflow: auto;
	box-sizing: border-box;
	border-left: 1px solid #E4E7ED;
}

.cc_b_r_menu{
	width: 100%;
	height: 50px;
	display: flex;
	align-items: center;
	box-sizing: border-box;
	border-bottom: 1px solid #E4E7ED;
	overflow: auto;
}

.cc_b_r_menu>div{
	height: 100%;
	width: 100px;
	min-width: 100px;
	max-width: 100px;
	padding: 0 15px;
	display: flex;
	text-align: center;
	/* justify-content: center; */
	align-items: center;
	cursor: pointer;
	transition: all 0.3s;
	/* text-overflow: ellipsis;
	overflow: hidden;
	white-space: nowrap; */
}

.cc_b_r_menu>div:hover{
	background-color: #F5F7FA;
}
.cc_b_r_menu>div>span{
	width: 100%;
	text-overflow: ellipsis;
	overflow: hidden;
	white-space: nowrap;
}

.cc_b_r_menu_active{
	background-color: #3681FC !important;
	color: #fff;
}

.cc_b_r_content{
	width: 100%;
	height: calc(100% - 50px);
}
</style>
