<template>
  <div class="allPage" v-loading="loading">
    <homePage
      ref="homePageRef"
      @cutPage="cutPage"
      :page="page"
      v-if="page == 1"
      :baseMessageLoading="baseMessageLoading"
      :classList="classList"
      :tid="tid"
      :bmData="bmData"
    ></homePage>
    <bindFrom ref="bindFromRef" @cutPage="cutPage" :page="page" v-if="page == 2"></bindFrom>
    <classInfo
      ref="classInfoRef"
      @cutPage="cutPage"
      :page="page"
			:tid="tid"
      v-if="page == 3"
      v-loading="baseMessageLoading"
      :bmData="bmData"
      :imageList="imageList"
    ></classInfo>
    <stencilled ref="stencilledRef" @cutPage="cutPage" :page="page" v-if="page == 5"></stencilled>
    <editTel ref="editTelRef" @cutPage="cutPage" :page="page" v-if="page == 6"></editTel>
    <addTel ref="addTelRef" @cutPage="cutPage" :page="page" v-if="page == 7"></addTel>
    <outcome
      ref="outcomeRef"
      @cutPage="cutPage"
      :page="page"
      v-show="page == 8"
      :loading="[currencyLoading, scienceLoading, extendLoading]"
      :dataList="dataList"
    />
  </div>
</template>

<script>
import homePage from './homePage'
import bindFrom from './bindFrom'
import classInfo from './classInfo'
import stencilled from './stencilled'
import editTel from './editTel'
import addTel from './addTel'
import outcome from './outcome.vue'
import { updateObsRequest, getCourseListRequest, getObsRequest, delClassRequest,delObsRequest } from '@/api/classObserve'

export default {
  components: { homePage, bindFrom, classInfo, stencilled, editTel, addTel, outcome },
  data() {
    return {
      userId: this.$store.state.user.id,
      page: 1,
      loading: false,
      currencyLoading: true,
      baseMessageLoading: true,
      scienceLoading: true,
      extendLoading: true,
      classList: [],
      bmData: {
        id: '',
        tId: '',
        tIndex: 0,
        jsonData: {
          activity_methods: '',
          activity_structure: '',
          classroom_resources: '',
          courseName: '',
          name: '',
          studentNum: 0,
          subject: '',
          textbook: ''
        }
      },
      imageList: {},
      dataList: [],
      tid: ''
    }
  },
  methods: {
    cutPage(val) {
      this.page = val
    },
    // 获取课堂列表
    getCourseList() {
      this.loading = true
      return new Promise((resolve, reject) => {
        getCourseListRequest({
          userid: this.userId
        })
          .then(res => {
            let _data = res.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,
                newLabel: item.jsonData.courseName ? item.jsonData.courseName : `${item.tId}课堂`,
                show: false,
                edit: false
              }
            })
            _optionData = _optionData.filter(i => i.label != '' && i.tId != '')
            this.classList = _optionData
            this.loading = false
            if (this.classList.length > 0) {
              this.changeTid(this.classList[0].value)
            }
            resolve()
          })
          .catch(e => {
            console.log(e)
            resolve()
            this.$message.error('获取课堂列表失败')
          })
      })
    },
    // 切换课堂
    changeTid(newTid) {
      if (this.tid == newTid) return
      let _flag = this.tid !== newTid
      this.tid = newTid
      if (_flag) {
        this.getData()
      }
    },
    //编辑课堂名称
    editClassName(item) {
      let _index = this.classList.findIndex(i => i.id == item.id)
      if (_index != -1) {
        if (this.tid == item.value) {
          //是现在预览的课堂
          this.$refs.homePageRef.historyListLoading = true
          this.bmData.jsonData.courseName = item.newLabel
          this.saveData(this.bmData).then(_ => {
            this.$refs.homePageRef.historyListLoading = false
            this.classList[_index].label = item.newLabel
            this.classList[_index].edit = false
            this.classList[_index].show = false
            this.loading = false
            this.$toast.success('修改成功')
          })
        } else {
          this.$refs.homePageRef.historyListLoading = true
          getObsRequest({ tid: item.value, type: 0 })
            .then(res => {
              let _data = res.FunctionResponse.result
              _data = JSON.parse(_data)
              let _bmData = _data.find(i => i.tIndex == 0)
              _bmData.jsonData = JSON.parse(_bmData.jsonData)
              _bmData.jsonData.courseName = item.newLabel
              this.saveData(_bmData).then(_ => {
                this.classList[_index].label = item.newLabel
                this.classList[_index].edit = false
                this.classList[_index].show = false
                this.loading = false
                this.$refs.homePageRef.historyListLoading = false
                this.$toast.success('修改成功')
              })
            })
            .catch(e => {
              console.log(e)
              this.$toast.fail('修改失败')
            })
        }
      }
    },
    //删除课堂
    delClass(item) {
      this.$refs.homePageRef.historyListLoading = true
      delClassRequest({ tid: item.id }).then(_ => {
        this.$toast.success('删除成功')
        this.getCourseList().then(_ => {
          if (this.tid == item.value || (this.tid == '' && this.classList.length > 0)) {
            this.changeTid(this.classList[0].value)
          }
          this.$refs.homePageRef.historyListLoading = false
        })
      })
    },
    //保存分析数据
    saveData(params) {
      return new Promise((resolve, reject) => {
        updateObsRequest({
          id: params.id,
          json_data: JSON.stringify(params.jsonData)
        })
          .then(res => {
            resolve()
          })
          .catch(e => {
            this.$message.error('保存失败')
            resolve()
          })
      })
    },
    //获取通用分析与基本信息
    getCurrencyAndBaseMessageData() {
      return new Promise(resolve => {
        if (!this.tid) return
        this.loading = true
        this.currencyLoading = true
        this.baseMessageLoading = true
        getObsRequest({ tid: this.tid, type: '0' })
          .then(res => {
            let _data = res.FunctionResponse.result.length ? JSON.parse(res.FunctionResponse.result) : []
            let _bmData = _data.find(i => i.tIndex == 0)
            // 基础信息
            _bmData.jsonData = JSON.parse(_bmData.jsonData)
						_bmData.jsonData.time? "":_bmData.jsonData.time = "";
            // 图片
            let _imageList = _data.find(i => i.tIndex == 1)
            _imageList.jsonData = JSON.parse(_imageList.jsonData)

            if (!_imageList.jsonData.videoList) {
              _imageList.jsonData.videoList = []
            }
            if (!_imageList.jsonData.NephogramList) {
              _imageList.jsonData.NephogramList = []
            }

            let currency = []
            for (let i = 2; i < _data.length; i++) {
              let _currency = _data[i]
              _currency.jsonData = JSON.parse(_currency.jsonData)
              currency.push(_currency)
            }
            // 赋值
            this.dataList.push(...currency)
            this.bmData = _bmData
            this.imageList = _imageList

            this.baseMessageLoading = false
            this.currencyLoading = false
            this.loading = false
            resolve()
          })
          .catch(e => {
            console.log(e)
            this.$toast.fail('获取通用分析失败')
            resolve()
          })
      })
    },
    //获取学科分析
    getScienceData() {
      return new Promise(resolve => {
        if (!this.tid) return
        this.scienceLoading = true
        getObsRequest({ tid: this.tid, type: '1' })
          .then(res => {
            let _data = res.FunctionResponse.result.length ? JSON.parse(res.FunctionResponse.result) : []
            if (_data.length == 0) {
              return (this.scienceLoading = false)
            }
            let science = []
            for (let i = 0; i < _data.length; i++) {
              let _science = _data[i]
              _science.jsonData = JSON.parse(_science.jsonData)
              science.push(_science)
            }
            this.dataList.push(...science)
            this.scienceLoading = false
            resolve()
          })
          .catch(e => {
            console.log(e)
            this.$toast.fail('获取科学分析失败')
            resolve()
          })
      })
    },
    //获取扩展分析
    getExtendData() {
      return new Promise(resolve => {
        if (!this.tid) return
        this.extendLoading = true;
				getObsRequest({tid:this.tid,type:"2"}).then(res=>{
					let _data = res.FunctionResponse.result.length
						? JSON.parse(res.FunctionResponse.result)
						: [];
					if (_data.length == 0) {
						return (this.extendLoading = false);
					}
					let extent = [];
					for (let i = 0; i < _data.length; i++) {
						let _extent = _data[i];
						_extent.jsonData = JSON.parse(_extent.jsonData);
						extent.push(_extent);
					}
					this.dataList.push(...extent);
					this.extendLoading = false;
					resolve();
				}).catch((e) => {
					console.log(e);
					this.$toast("获取扩展分析失败")
					resolve();
				});
      })
    },
		//获取全部的数据
    getData() {
			this.dataList = [];
			this.imageList = {};
      return new Promise(resolve => {
        Promise.all([this.getCurrencyAndBaseMessageData(),this.getScienceData(),this.getExtendData()]).then(_ => {
          console.log('所有分析获取完成')
					resolve();
        })
      })
    },
		//删除分析
		delAnalysis(item){
			if(!this.tid)return;
			this.currencyLoading = true;
			this.baseMessageLoading = true;
      this.scienceLoading = true;
      this.extendLoading = true;
			delObsRequest({
				id:item.id,
				type:item.Type,
				tid:this.tid
			}).then(res=>{
				this.dataList = this.dataList.filter(_item=>_item.id!=item.id);
				this.$toast.success('删除成功');
				this.currencyLoading = false;
				this.baseMessageLoading= false;
				this.scienceLoading= false;
				this.extendLoading= false;
			}).catch(e=>{
				this.$toast.fail('删除失败');
				this.currencyLoading = false;
				this.baseMessageLoading= false;
				this.scienceLoading= false;
				this.extendLoading= false;
			})
		},
		//修改分析
		editAnalysis(item){
			if(!this.tid)return;
			this.baseMessageLoading= true;
      this.scienceLoading= true;
      this.extendLoading= true;
			editObsRequest({
				id:item.id,
				type:item.Type,
				tid:this.tid
			}).then(res=>{
			})
		}
  },
  mounted() {
    this.getCourseList().then(_ => {
      // if(this.tid=="" && this.classList.length>0){
      // 	this.changeTid(this.classList[0].value);

      // }
      // this.getData()
    })
    // console.log(getClassList)
  }
}
</script>

<style lang="scss" scoped>
.allPage {
  height: 100vh;
}
</style>
