<template>
  <div class="stencilled">
    <bar @cutPage="cutPage" :tit="'模版中心'" :backPage="0"></bar>
    <div style="height: 55px;width: 100%;"></div>
    <div class="selectInp">
      <van-search shape="round" v-model="selectValue" placeholder="搜索表单" />
      <span @click.stop="getData()">搜索</span>
    </div>
    <div class="sortList">
      <div :class="[tagIndex == 0 ? 'sortActive' : '']" @click.stop="changeTagIndex(0)">社区</div>
      <div :class="[tagIndex == 1 ? 'sortActive' : '']" @click.stop="changeTagIndex(1)">我的</div>
      <div :class="[tagIndex == 2 ? 'sortActive' : '']" @click.stop="changeTagIndex(2)">收藏</div>
      <div @click="reveal" class="sortImg"><img src="../../assets/images/classObserve/filter.svg" alt="" /> 筛选</div>
    </div>
    <div class="stencilList" v-loading="loading">
      <div
        style="margin-bottom: 15px;"
        v-for="(item, index) in templateData"
        :key="item.id"
        @click="choiceTemplate(item)"
      >
        <stencilledCon
          :data="item"
          :isChoice="choiceTemplateId == item.id"
          :tagSubjectList="tagSubjectList"
          :collectData="collectData"
        ></stencilledCon>
      </div>
    </div>
    <div class="botBtn">
      <div :class="['btn', choiceTemplateId ? '' : 'btnDisabled']" @click="getAnalysisAndUse()">
        使用该模版创建课堂
      </div>
    </div>

    <van-action-sheet v-model="sortShow" title="全部筛选">
      <div class="actionCon">
        <div class="sheetTit">学科</div>
        <div class="claList">
          <div
            :class="['ListBlc', tagSubject2 == item.value ? 'ListBlcActive' : '']"
            v-for="(item, index) in tagSubjectList"
            @click.stop="tagSubject2 = item.value"
            :key="index"
          >
            {{ item.label }}
          </div>
        </div>
        <div class="actionBtn">
          <div class="btn" @click.stop="revealReset">重置</div>
          <div class="btn btn1" @click.stop="revealSubmit">确认</div>
        </div>
      </div>
    </van-action-sheet>

    <van-action-sheet
      v-loading="saveTemplateLoading"
      v-model="templateShow"
      @closed="closeSheet"
      :title="analysisDetail ? analysisDetail.name : '预览模板'"
    >
      <div class="actionTel" v-if="templateShow && analysisDetail">
        <div class="telCon">
          <div class="telConCell">
            <div class="tit">
              <div>通用课堂分析</div>
              <span v-if="isEditTel" @click.stop="addTemplate(0)">＋</span>
            </div>
            <div class="list">
              <div
                class="cell"
                v-for="(item, index) in analysisDetail.tips.filter(i => i.Type == 0)"
                :key="index + '-' + 0"
                v-show="item.tIndex !== 2"
              >
                <div>{{ item.jsonData.name }}</div>
                <span v-if="isEditTel" @click.stop="delTips(item, index, 0)">
                  <img src="../../assets/images/classObserve/del.svg" />
                </span>
              </div>
            </div>
          </div>

          <div class="telConCell">
            <div class="tit">
              <div>学科课堂分析</div>
              <span v-if="isEditTel" @click.stop="addTemplate(1)">＋</span>
            </div>
            <div class="list">
              <div
                class="cell"
                v-for="(item, index) in analysisDetail.tips.filter(i => i.Type == 1)"
                :key="index + '-' + 1"
              >
                <div>
                  {{ item.jsonData.name }}
                </div>
                <span v-if="isEditTel" @click.stop="delTips(item, index, 1)">
                  <img src="../../assets/images/classObserve/del.svg" />
                </span>
              </div>
            </div>
          </div>

          <div class="telConCell">
            <div class="tit">
              <div>扩展课堂分析</div>
              <span v-if="isEditTel" @click.stop="addTemplate(2)">＋</span>
            </div>
            <div class="list">
              <div
                class="cell"
                v-for="(item, index) in analysisDetail.tips.filter(i => i.Type == 2)"
                :key="index + '-' + 2"
              >
                <div>{{ item.jsonData.name }}</div>
                <span v-if="isEditTel" @click.stop="delTips(item, index, 2)">
                  <img src="../../assets/images/classObserve/del.svg" />
                </span>
              </div>
            </div>
          </div>
        </div>
        <div class="actionBtn">
          <div class="btn" @click="editTel(true)" v-if="userId === analysisDetail.userid && !isEditTel">编辑模板</div>

          <div
            class="btn"
            v-if="!isEditTel && (defaultData ? defaultData.id !== analysisDetail.id : true)"
            @click.stop="setDefaultTemplate(analysisDetail)"
          >
            设为默认
          </div>
          <div class="btn btn1" v-if="!isEditTel" @click.stop="useAnalysis(analysisDetail)">使用模板</div>
          <div class="btn" @click="editTel(false)" v-if="userId === analysisDetail.userid && isEditTel">取消编辑</div>
          <div class="btn btn1" v-if="isEditTel" @click.stop="saveTemplate">保存模板</div>
        </div>
      </div>
    </van-action-sheet>
		<addTel ref="addTelRef" :data="analysisList" @success="addAnalysisByList" @close="()=>{templateShow = true}"/>
  </div>
</template>

<script>
import bar from './components/bar.vue'
import stencilledCon from './components/stencilledCon'
import { Dialog } from 'vant'
import {
  getClassroomTemplateRequest,
  getClassroomDefaultRequest,
  updateClassroomTemplateCollectRequest,
  getClassroomTemplateDetailRequest,
  updateClassroomTemplateDataRequest,
  updateClassroomDefaultRequest
} from '../../api/classObserve'
import addTel from './addTel.vue'


export default {
  components: {
    bar,
    stencilledCon,
		addTel
  },
  props: {
    page: {
      type: Number,
      default: 1
    },
		analysisList:{
			type:Array,
			default:()=>[]
		}
  },
  data() {
    return {
      selectValue: '',
      sortShow: false,
      abuShow: false,
      loading: false,
      saveTemplateLoading: false,
      templateShow: false,
      defaultData: null,
      tagIndex: 0,
      templateData: [],
      collectData: [],
      tagSubject: '',
      tagSubject2: '',
      userId: this.$store.state.user.userinfo.userid,
      analysisDetail: null,
      choiceTemplateId: '',
      tagSubjectList: [
        { 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: '政治' }
      ],
      previewData: null,
      isEditTel: false
    }
  },
  methods: {
    changeTagIndex(newIndex) {
      this.tagIndex = newIndex
      this.choiceTemplateId = ''
      this.getData()
    },
    cutPage() {
      this.$emit('cutPage', 1)
    },
    editTel(newValue) {
      this.isEditTel = newValue
      if (!newValue) {
        Dialog.confirm({
          title: '放弃修改',
          message: '确定放弃修改内容？'
        })
          .then(() => {
            this.previewTel(this.analysisDetail)
          })
          .catch(() => {
            this.isEditTel = true
          })
      }
    },
    reveal() {
      this.tagSubject2 = this.tagSubject
      this.sortShow = true
    },
    revealSubmit() {
      this.tagSubject = this.tagSubject2
      this.sortShow = false
      this.getData()
    },
    revealReset() {
      this.tagSubject = ''
      this.tagSubject2 = ''
    },
    previewTel(data) {
      this.loading = true
      getClassroomTemplateDetailRequest({
        uid: this.userId,
        cid: data.id,
        st: 0
      })
        .then(res => {
          let _data = res[0][0]
          if (_data) {
            _data.tips = JSON.parse(_data.tips)
            this.analysisDetail = _data
            this.templateShow = true
						this.isEditTel = false
          } else {
            this.$toast.fail('获取模板详细为空')
          }
        })
        .catch(e => {
          console.log(e)
          this.$toast.fail('获取模板详细失败')
        })
        .finally(_ => {
          this.loading = false
        })
      // this.templateShow = true;
      // console.log(data)
    },
    getMyselfData() {
      this.loading = true
      this.templateData = []
      let params = {
        uid: this.userId,
        txt: this.selectValue,
        sub: this.tagSubject,
        type1: 1
      }
      getClassroomTemplateRequest(params)
        .then(res => {
          let _data = res[0]
          this.templateData = _data
        })
        .catch(e => {
          console.log(e)
          this.$toast.fail('获取数据失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    getCollectData(flag = true) {
      this.loading = true
      if (flag) {
        this.templateData = []
      }
      let params = {
        uid: this.userId,
        txt: this.selectValue,
        sub: this.tagSubject,
        type1: 2
      }
      getClassroomTemplateRequest(params)
        .then(res => {
          let _data = res[0]
          if (flag) {
            this.templateData = _data
          }
          this.collectData = _data
        })
        .catch(e => {
          console.log(e)
          this.$toast.fail('获取数据失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    getPublicData() {
      this.loading = true
      this.templateData = []
      let params = {
        uid: this.userId,
        txt: this.selectValue,
        sub: this.tagSubject,
        type1: 0
      }
      getClassroomTemplateRequest(params)
        .then(res => {
          let _data = res[0]
          this.templateData = _data
        })
        .catch(e => {
          console.log(e)
          this.$toast.fail('获取数据失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    getDefaultTemplate() {
      let params = {
        uid: this.userId
      }
      getClassroomDefaultRequest(params)
        .then(res => {
          let _data = res[0][0]
          this.defaultData = _data
        })
        .catch(e => {
          this.$toast.fail('获取默认模板失败')
          // this.$message.error("获取默认模板失败");
          console.log(e)
        })
    },
    getData() {
      if (this.tagIndex == 0) {
        this.getPublicData()
      } else if (this.tagIndex == 1) {
        this.getMyselfData()
      } else if (this.tagIndex == 2) {
        this.getCollectData()
      }
    },
    closeSheet() {
      // this.analysisDetail = null
      // this.isEditTel = false
    },
    collect(type = 0, data) {
      this.loading = true
      //1 取消收藏 0收藏
      let cid = type == 0 ? data.id : this.collectData.filter(item => item.id == data.id)[0].id2
      updateClassroomTemplateCollectRequest([
        {
          uid: this.userId,
          cid: cid,
          type: type
        }
      ])
        .then(res => {
          // this.$toast.success(type == 1 ? '取消收藏成功' : '收藏成功')
        })
        .catch(e => {
          this.$toast.fail('操作失败')
        })
        .finally(_ => {
          this.loading = false
          if (this.tagIndex == 2) {
            this.getCollectData()
          } else {
            this.getCollectData(false)
          }
        })
    },
    delTips(item, index, type) {
      Dialog.confirm({
        title: '删除分析',
        message: `确定删除 "${item.jsonData.name}" 这个分析？`
      })
        .then(() => {
          let _index = this.analysisDetail.tips.findIndex(_i => JSON.stringify(_i) === JSON.stringify(item))
          if (_index != -1) {
            let _data = JSON.parse(JSON.stringify(this.analysisDetail.tips))

            _data.splice(_index, 1)
            this.analysisDetail.tips = _data
          }
        })
        .catch(() => {
          console.log('不删除')
          // on cancel
        })

      // this.analysisDetail.tips.splice(index,1);
    },
    saveTemplate() {
      this.saveTemplateLoading = true
      if (this.analysisDetail.userid !== this.userId) {
        this.isEditTel = false
        return this.$toast.fail('您没有权限修改此模板')
      }
      let params = [
        {
          uid: this.userId,
          cid: this.analysisDetail.id,
          title: this.analysisDetail.name,
          jsonData: JSON.stringify(this.analysisDetail.tips)
        }
      ]
      updateClassroomTemplateDataRequest(params)
        .then(res => {
          this.$toast.success('保存成功')
          this.isEditTel = false
          // this.getData();
        })
        .catch(e => {
          console.log(e)
          this.$toast.fail('保存失败')
        })
        .finally(_ => {
          this.saveTemplateLoading = false
        })
    },
    choiceTemplate(item) {
      if (this.choiceTemplateId == item.id) {
        return (this.choiceTemplateId = '')
      }
      this.choiceTemplateId = item.id
    },
    useAnalysis(item) {
      Dialog.confirm({
        title: '使用模板',
        message: `确定使用 "${item.name}" 这个模板来创建课堂？`
      })
        .then(() => {
          getClassroomTemplateDetailRequest({
            uid: this.userId,
            cid: item.id,
            st: 1
          })
            .then(res => {
              var OpenCC = require('opencc-js')
              let converter = OpenCC.Converter({
                from: 'hk',
                to: 'cn'
              })
              let _data = res[0][0]

              _data.tips = JSON.parse(_data.tips)

              let _result = []
              _data.tips.forEach(i => {
                if (converter('词频词汇分析') == converter(i.jsonData.name)) return
                let _obj = {
                  jsonData: i.jsonData,
                  type: i.Type,
                  index: i.tIndex
                }
                _result.push(_obj)
              })
              this.$parent.addNewCourseByTemplate(_result)
              this.cutPage(1)
            })
            .catch(e => {
              this.$toast.fail('获取默认模板失败')
              // this.$message.error("获取默认模板失败");
              console.log(e)
            })
        })
        .catch(() => {
          console.log('不使用')
          // on cancel
        })
    },
    getAnalysisAndUse() {
      if (!this.choiceTemplateId) return this.$toast('请先选择模板')
      let _data = this.templateData.find(i => i.id == this.choiceTemplateId)

      if (_data) {
        this.useAnalysis(_data)
      }
    },
    setDefaultTemplate(item) {
      Dialog.confirm({
        title: '设为默认模板',
        message: `确定将 "${item.name}" 这个模板设为默认模板？`
      })
        .then(() => {
          let params = [
            {
              uid: this.userId,
              tid: item.id
            }
          ]
          this.saveTemplateLoading = true
          updateClassroomDefaultRequest(params)
            .then(res => {
              if (res == 1) {
                this.$toast.success('设置默认模板成功')
              } else {
                this.$toast.fail('设置默认模板失败')
              }
              this.getDefaultTemplate()
            })
            .catch(e => {
              this.$toast.fail('设置默认模板失败')
              console.log(e)
              this.getDefaultTemplate()
            })
            .finally(_ => {
              this.saveTemplateLoading = false
            })
        })
        .catch(() => {
          console.log('不设置')
          // on cancel
        })
    },
		addTemplate(type=0){
			this.templateShow = false;
			this.$refs.addTelRef.open(type)
			// console.log("添加模块",type)
		},
		addAnalysisByList(data){
			this.templateShow = true;
			this.$refs.addTelRef.close();
			let _list = this.analysisList.filter(i=>data.includes(i.value));
			console.log(_list);
			_list.forEach(i=>{
				this.analysisDetail.tips.push({
					id: "",
				jsonData: {
					name: i.title,
					result: i.brief,
					fileList: [],
					dataFileList: [],
					wordNum: "",
					wordCountNum: "",
					fileList2: [],
					content: "",
				},
				Type: i.type,
				tIndex: this.analysisDetail.tips.filter((i2) => i2.Type == i.type).length?this.analysisDetail.tips.filter((i2) => i2.Type == i.type).map(i3=>i3.tIndex).sort((a,b)=>b-a)[0]+1:i.type==0?3:0,
				tId: "",
				createtime: "",
				like_num: 0,
				like_data: null,
				userid: "",
				isdel: 0,
				})
			})
			console.log(this.analysisDetail)
			
			console.log("上")
		}
  },
  mounted() {
    this.getData()
    this.getCollectData(false)
    this.getDefaultTemplate()
  }
}
</script>

<style lang="scss" scoped>
.actionTel {
  height: 100% !important;
  // height: 500px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  // padding: 10px 15px;
  box-sizing: border-box;
  .telCon {
    flex: 1;
    overflow: auto;
    .telConCell {
    }
    .tit {
      width: 100%;
      padding: 13px 15px;
      background-color: rgba(231, 231, 231, 1);
      color: rgba(0, 0, 0, 0.6);
      font-size: 12px;
      font-weight: 400;
      box-sizing: border-box;
			display: flex;
			justify-content: space-between;
			align-items: center;
			span{
				transform: scale(1.7,1.7);
				margin-right: 10px;
			}
    }
    .list {
      padding: 0 10px;
    }
    .cell {
      padding: 15px 0px;
      border-bottom: 0.5px solid rgba(231, 231, 231, 1);
      font-size: 16px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.9);
      display: flex;
      justify-content: space-between;
      align-items: center;
      span {
        width: 20px;
        height: 20px;
        margin-right: 10px;
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .actionBtn {
    height: 70px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    // padding: 0 15px;
    .btn {
      flex: 1;
      border-radius: 6px;
      padding: 12px 0;
      margin: 0 5px;
      display: flex;
      justify-content: center;
      color: rgba(54, 129, 252, 1);
      background-color: rgba(242, 243, 255, 1);
      font-size: 16px;
      &:nth-of-type(1) {
        margin-left: 10px;
      }
      &:nth-last-of-type(1) {
        margin-right: 10px;
      }
    }
    .btn1 {
      color: #fff;
      background-color: rgba(54, 129, 252, 1);
    }
  }
}
.stencilled {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
}
/deep/.van-action-sheet {
  height: 80% !important;
}
/deep/.van-action-sheet__header {
  font-weight: 600;
}
.selectInp {
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .van-search {
    width: 100%;
    .van-search__content {
      height: 45px;
      align-items: center;
    }
  }
  span {
    color: rgba(54, 129, 252, 1);
    font-size: 16px;
    font-weight: 600;
    display: block;
    width: 40px;
  }
}
.sortList {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding-bottom: 15px;
  border-bottom: 0.5px rgba(231, 231, 231, 1) solid;
  .sortActive {
    color: rgba(54, 129, 252, 1);
    font-weight: bold;
  }
  div {
    width: 25%;
    text-align: center;
    font-size: 16px;
    font-weight: 400;
  }
  .sortImg {
    display: flex;
    align-items: center;
    justify-content: center;
    border-left: 0.5px rgba(231, 231, 231, 1) solid;
  }
}
.stencilList {
  flex: 1;
  padding: 15px;
  box-sizing: border-box;
  overflow: auto;
}
.botBtn {
  height: 60px;
  background-color: #fff;
  width: 100%;
  padding: 10px 25px;
  box-sizing: border-box;
  border-top: 0.5px #ccc solid;
  .btn {
    width: 100%;
    background-color: rgba(54, 129, 252, 1);
    color: #fff;
    height: 40px;
    border-radius: 5px;
    display: flex;
    font-size: 16px;
    // font-weight: 600;
    justify-content: center;
    align-items: center;
    transition: 0.3s;
  }
  .btnDisabled {
    background-color: #e7e7e7;
    color: rgb(104, 104, 104);
  }
}
.actionCon {
  height: 100% !important;
  // height: 500px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 10px 15px;
  box-sizing: border-box;
  .sheetTit {
    font-size: 14px;
    font-weight: 600;
    padding-bottom: 10px;
  }
  .claList {
    flex: 1;
    overflow: auto;
    .ListBlc {
      width: 30%;
      height: 35px;
      border-radius: 30px;
      display: inline-block;
      box-sizing: border-box;
      font-size: 14px;
      font-weight: 400;
      line-height: 35px;
      background-color: rgba(243, 247, 253, 1);
      text-align: center;
      border: 1px rgba(242, 243, 255, 1) solid;
    }
    .ListBlcActive {
      background-color: #3681fc;
      border-color: #3681fc;
      color: #fff;
    }
  }
  .claList > div {
    margin-right: calc(10% / 2);
    margin-bottom: 10px;
  }
  .claList :nth-child(3n) {
    margin-right: 0;
  }
  .actionBtn {
    height: 70px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .btn {
      flex: 1;
      border-radius: 6px;
      padding: 12px 0;
      display: flex;
      justify-content: center;
      color: rgba(54, 129, 252, 1);
      background-color: rgba(242, 243, 255, 1);
      font-size: 16px;
    }
    .btn1 {
      color: #fff;
      background-color: rgba(54, 129, 252, 1);
    }
  }
}
</style>
