<template>
  <div class="pb_content" style="background: #F0F2F5;" v-loading="loading || isloading">
    <div class="pb_content_body" style="position: relative; margin: 0">
      <div class="right">
        <div class="courseTop" :style="`justify-content: ${isN==1?'flex-end':'space-between'};`">
          <div class="stepsNav" v-if="isN !=1">
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <el-breadcrumb-item :to="{
    path:
      '/testPerson?userid=' +
      userid +
      '&oid=' +
      oid +
      '&org=' +
      org +
      '&role=' +
      role,
  }" v-if="type == 3">个人中心</el-breadcrumb-item>
              <el-breadcrumb-item :to="{
    path:
      '/testStudent?userid=' +
      userid +
      '&oid=' +
      oid +
      '&org=' +
      org +
      '&role=' +
      role +
      '&isN=' +
      isN +
      '&tcid=' +
      tcid ,
  }" v-else>表单中心</el-breadcrumb-item>
              <el-breadcrumb-item>
                <span style="color: rgb(15, 126, 255)">{{ title }}</span>
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="r_pub_button_retrun" @click="retrunCourse">返回</div>
        </div>
        <div class="step_box">
          <div class="edit_top" :style="isN==1?'border-bottom:none;justify-content:space-between;padding:10px':''">
						<div v-if="isN==1" class="edit_title"  :style=" isN==1? 'margin-left : 12px' : ''">提交记录</div>
            <div class="op_btn">
							<el-button type="primary" :style=" isN==1? 'padding: 5px 10px;' : ''" size="small" @click="autoFill" v-if="(showAutoFillBtn && isN!=1)">智能填写</el-button>
              <el-button type="primary" :style=" isN==1? 'padding: 5px 10px;' : ''" size="small" @click="refresh" v-if="isReset">刷新</el-button>
              <el-button :type="isN!=1?'primary':'info'" :style=" isN==1? 'padding: 5px 10px;' : ''" size="small" @click="reset">重置</el-button>
              <el-button type="primary" :style=" isN==1? 'padding: 5px 10px;' : ''" size="small" @click="save" v-if="(type != 3 && isN!=1)">保存</el-button>
              <el-button type="primary" :style=" isN==1? 'padding: 5px 10px;' : ''" size="small" @click="publish">提交</el-button>
            </div>
          </div>
          <topicVue :cJson.sync="cJson" :title="title" :brief="brief" ref="topicVue" v-if="!loading"
            @getTestWorkByCid="getTestWorkByCid" @publish2="publish2" :tid="tid" :gcourseid="gcourseid"></topicVue>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import topicVue from './component/topic.vue';
export default {
  components: {
    topicVue
  },
  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,
      tid: this.$route.query.tid,
      type: this.$route.query.type,
      updateType: this.$route.query.type,
      isN: this.$route.query.isN,
      tcid: this.$route.query.tcid,
      steps: 1,
      title: "",
      brief: "",
      testType: [],
      see: false,
      cJson: [],
      cJson2: [],
      loading: false,
      look: "",
      isReset: false,
      isloading: false,
      courseid: '',
      gcourseid: this.$route.query.courseid
    }
  },
	computed:{
		showAutoFillBtn(){
			let _json = this.JSONSetting(this.cJson)
			return _json.filter(i=>i.type==3).length>0;
		}
	},
  methods: {
    retrunCourse() {
      this
        .$confirm("是否确认返回？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          distinguishCancelAndClose: true,
          type: "warning",
        })
        .then(() => {
          if (this.type == 3) {
            this.goTo(
              "/testPerson?userid=" +
              this.userid +
              "&oid=" +
              this.oid +
              "&org=" +
              this.org +
              "&role=" +
              this.role
            );
          } else {
            this.goTo(
              "/testStudent?userid=" +
              this.userid +
              "&oid=" +
              this.oid +
              "&org=" +
              this.org +
              "&role=" +
              this.role +
              "&isN=" +
              this.isN +
              "&tcid=" +
              this.tcid 
            );
          }
        })
        .catch((v) => {

        });
    },
    goTo(path) {
      this.$router.push(path);
    },
    reset() {
      this
        .$confirm("是否将已经填写的内容重置？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          if(this.tid){
            this.deleteTest(this.tid)
          }else{
            if(this.courseid){
              this.cJson = this.setCourseid(JSON.parse(JSON.stringify(this.cJson2)));
            }else{
              this.cJson = JSON.parse(JSON.stringify(this.cJson2));
            }
            this.loading = true
            this.isReset = false
            setTimeout(() => {
              this.loading = false
            }, 0);
            this.$forceUpdate()
          }
        })
        .catch(() => {

        });
    },
    refresh() {
      this
        .$confirm("是否将现在的题目刷新成最新的题目", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          if(this.tid){
            this.deleteTest(this.tid)
          }else{
            if(this.courseid){
              this.cJson = this.setCourseid(JSON.parse(JSON.stringify(this.cJson2)));
            }else{
              this.cJson = JSON.parse(JSON.stringify(this.cJson2));
            }
            this.loading = true
            this.isReset = false
            setTimeout(() => {
              this.loading = false
            }, 0);
            this.$forceUpdate()
          }
        })
        .catch(() => {

        });
    },
    getTestWorks() {
      let params = {
        cid: this.cid,
        uid: this.userid,
      };
      this.ajax
        .get(this.$store.state.api + "getTestWorks", params)
        .then((res) => {
          // this.cJson = JSON.parse(res.data[0][0].chapters);
          if (res.data[2].length) {
            this.cJson = JSON.parse(res.data[2][0].courseJson)

            let cJson = this.setJSON(JSON.parse(JSON.stringify(this.cJson)))
            let cJson2 = this.setJSON(this.setJson2(JSON.parse(JSON.stringify(this.cJson2))))

            if (JSON.stringify(cJson) != JSON.stringify(cJson2)) {
              this.isReset = true
            }


          }

          this.$forceUpdate()

          this.loading = false

        })
        .catch((err) => {
          this.loading = false
          console.error(err);
        });
    },
    getTestWorks2() {
      let params = {
        cid: this.cid,
        tid: this.tid,
      };
      this.ajax
        .get(this.$store.state.api + "getTestWorks2", params)
        .then((res) => {
          // this.cJson = JSON.parse(res.data[0][0].chapters);
          if (res.data[2].length) {
            this.cJson = JSON.parse(res.data[2][0].courseJson)

            let cJson = this.setJSON(JSON.parse(JSON.stringify(this.cJson)))
            let cJson2 = this.setJSON(this.setJson2(JSON.parse(JSON.stringify(this.cJson2))))

            if (JSON.stringify(cJson) != JSON.stringify(cJson2)) {
              this.isReset = true
            }


          }

          this.$forceUpdate()

          this.loading = false

        })
        .catch((err) => {
          this.loading = false
          console.error(err);
        });
    },
    getTestWorkByCid(courseid) {
      this.isloading = true
      this.courseid = courseid
      let params = {
        cid: this.cid,
        uid: this.userid,
      };
      let _courseid = courseid
      this.ajax
        .get(this.$store.state.api + "selectTestWorksCid", params)
        .then((res) => {
          if (res.data[0].length) {
            console.log(res.data[0]);
            let rData = res.data[0]
            this.tid = ''
            aa: for (var i = 0; i < rData.length; i++) {
              let rDataJson = this.JSONSetting(JSON.parse(rData[i].courseJson))
              let _json = JSON.parse(rData[i].courseJson)
              for (var j = 0; j < rDataJson.length; j++) {
                let _param = rDataJson[j]
                if (_param.type == 6 && _param.json.answer2 && _param.json.answer2 == _courseid) {
                  console.log(_json);
                  this.cJson = _json
                  let cJson = this.setJSON(JSON.parse(JSON.stringify(this.cJson)))
                  let cJson2 = this.setJSON(this.setJson2(JSON.parse(JSON.stringify(this.cJson2))))
                  if (JSON.stringify(cJson) != JSON.stringify(cJson2)) {
                    this.isReset = true
                  }
                  this.tid = rData[i].id
                  this.$forceUpdate()
                  break aa;
                }
              }
            }
            if (!this.tid) {
              this.cJson = this.setJSON(this.setCourseid(JSON.parse(JSON.stringify(this.cJson2))))
            }
          }else{
            this.tid = ''
            this.cJson = this.setJSON(this.setCourseid(JSON.parse(JSON.stringify(this.cJson2))))
          }
          this.$forceUpdate()
          this.isloading = false
        })
        .catch((err) => {
          this.isloading = false
          console.error(err);
        });
    },
    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)
        }
        console.log(item.array);
        return item;
      });
      console.log(array);
      return array;
    },
    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
        console.log(item.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 = [];
        }
        console.log(item.array);
        return (item.ttype != 1 && item.array.length > 0) || item.ttype == 1;
      });
      console.log(checkArray);
      return checkArray;

    },
    setCourseid(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.type != 6 && item2.type != 7 && item2.type != 8) {
              item2.json.answer2 = [];
            }else if(item2.type == 6){
              item2.json.answer2 = this.courseid ? this.courseid : '';
            }else if(item2.type == 7 || item2.type == 8){
              item2.json.answer2 = '';
            }
            if (item2.array) {
              item2.array = item2.array.filter((item3) => {
                if (item3.ttype == 1 && item3.json && !item3.json.answer2 && item3.type != 6 && item3.type != 7 && item3.type != 8) {
                  item3.json.answer2 = [];
                }else if(item3.type == 6){
                  item3.json.answer2 = this.courseid ? this.courseid : '';
                }else if(item3.type == 7 || item3.type == 8){
                  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.type != 6 && item.type != 6 && item.type != 7 && item.type != 8) {
          item.json.answer2 = [];
        }else if(item.type == 6){
          item.json.answer2 = this.courseid ? this.courseid : '';
        }else if(item.type == 7 || item.type == 8){
          item.json.answer2 = '';
        }
        console.log(item.array);
        return (item.ttype != 1 && item.array.length > 0) || item.ttype == 1;
      });
      console.log(checkArray);
      return checkArray;

    },
    getData() {
      this.loading = true
      let params = {
        cid: this.cid,
      };
      this.ajax
        .get(this.$store.state.api + "getTestCourseDetail", params)
        .then((res) => {
          this.cJson = JSON.parse(res.data[0][0].chapters);
          this.cJson2 = JSON.parse(res.data[0][0].chapters);
          this.title = res.data[0][0].title;
          this.brief = res.data[0][0].brief;

          this.see = res.data[0][0].open == 1 ? true : false;


          this.testType = [];
          for (var i = 0; i < res.data[1].length; i++) {
            this.testType.push(res.data[1][i].typeid);
          }
          console.log(this.testType);
          this.look = res.data[0][0].look
         	if(this.isN!=1){
						if (this.type == 3) {
         	   this.getTestWorks2()
         	 } else {
         	   this.getTestWorks()
         	 }
				 	}else{
						this.loading = false;
						this.isReset = true;
					}
          this.$forceUpdate();

        })
        .catch((err) => {
          this.loading = false
          console.error(err);
        });
    },
    save() {
      let cjson = this.$refs['topicVue'].checkArray
      console.log(cjson);
      let params = [
        {
          uid: this.userid,
          cid: this.cid,
          cjson: JSON.stringify(cjson),
          type: '1',
        },
      ];
      this.ajax
        .post(this.$store.state.api + "addTestWorks", params)
        .then((res) => {
          this.$message.success('保存成功')
          this.goTo(
            "/testStudent?userid=" +
            this.userid +
            "&oid=" +
            this.oid +
            "&org=" +
            this.org +
            "&role=" +
            this.role +
            "&isN=" +
            this.isN +
            "&tcid=" +
            this.tcid 
          );
        })
        .catch((err) => {
          this.$message.error("网络不佳");
          console.error(err);
        });
    },
    publish() {
      let cjson = this.$refs['topicVue'].checkArray
      console.log(cjson);
      let _uid = ''
      if(this.isN == 1){
        _uid = this.tcid
      }else { 
        _uid = (this.tid) ? this.tid : this.userid
      }
      let params = [
        {
          uid: _uid,
          cid: this.cid,
          cjson: JSON.stringify(cjson),
          type: '2',
        },
      ];
      this.ajax
        .post(this.$store.state.api + ((this.tid) ? "addTestWorks2" : "addTestWorks"), params)
        .then((res) => {
          this.$message.success('提交成功')
          if (this.type == 3) {
            this.goTo(
              "/testPerson?userid=" +
              this.userid +
              "&oid=" +
              this.oid +
              "&org=" +
              this.org +
              "&role=" +
              this.role
            );
          } else {
            this.goTo(
              "/testStudent?userid=" +
              this.userid +
              "&oid=" +
              this.oid +
              "&org=" +
              this.org +
              "&role=" +
              this.role +
              "&isN=" +
              this.isN +
              "&tcid=" +
              this.tcid 
            );
          }
        })
        .catch((err) => {
          this.$message.error("网络不佳");
          console.error(err);
        });
    },
    publish2() {
      this.isloading = true
      let cjson = this.$refs['topicVue'].checkArray
      let _cjson = this.JSONSetting(JSON.parse(JSON.stringify(cjson)));
      let pan = this.panJSON(_cjson)
      if(!pan){
        setTimeout(() => {
            this.isloading = false
          }, 500);
        return
      }
      console.log(cjson);
      let params = [
        {
          uid: (this.tid) ? this.tid : this.userid,
          cid: this.cid,
          cjson: JSON.stringify(cjson),
          type: '2',
        },
      ];
      this.ajax
        .post(this.$store.state.api + ((this.tid) ? "addTestWorks2" : "addTestWorks"), params)
        .then((res) => {
          this.$message.success('保存成功')
          setTimeout(() => {
            this.isloading = false
          }, 500);
        })
        .catch((err) => {
          this.$message.error("网络不佳");
          this.isloading = false
          console.error(err);
        });
    },
    panJSON(array){
      var pan = 0
      for(var i = 0; i < array.length; i++){
        if(array[i].type != 6){
          let param = array[i].json
          if(array[i].type == 5 && param.file && param.file.length > 0){
            pan++
          }else if(param.answer2.length || typeof(param.answer2) == 'number'){
            pan++
          }
        }
      }
      if(pan > 0){
        return true
      }else {
        return false
      }
    },
    deleteTest(tid) {
      let _this = this;
      let params = [
        {
          tid: tid
        }
      ];
      _this.ajax
        .post(_this.$store.state.api + "deleteTestCourseWorks", params)
        .then(res => {
          this.getTestWorkByCid(this.courseid)
        })
        .catch(err => {
          console.error(err);
        });
    },
		autoFill(){
			this
        .$confirm("这将覆盖原有的内容，是否继续？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
					console.log(this.$refs['topicVue'])
          this.$refs['topicVue'].autoFillGapV();
        })
        .catch(() => {

        });
		}
  },
  mounted() {
    this.getData();
  },
}
</script>

<style scoped>
.pb_content {
  height: 100% !important;
  /* margin: 0 20px 0 20px; */
}

.pb_content_body {
  width: 100% !important;
  height: 100%;
}

.right {
  height: 100%;
  width: 100%;
  display: flex;
  overflow: hidden;
  flex-direction: column;
}

.basic_box {
  margin: 0 auto;
  position: relative;
  padding: 0 20px 0 20px;
}

.courseTop {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: calc(100% - 40px);
  margin: 0 auto;
  padding: 10px 0;
}

.stepsNav {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}

.step_box {
  width: calc(100%);
  margin: 0 auto;
  height: calc(100% - 38px);
}

.edit_top {
  height: 50px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  position: relative;
  /* padding: 0 30px; */
  padding-right: 10px;
  border-top: 2px solid #eee;
  border-bottom: 2px solid #eee;
  width: 95%;
  margin: 0 auto;
  box-sizing: border-box;
}

.edit_title{
	font-size: 22px;
	margin-left: 30px;
	position: relative;
}

.edit_title::after{
	content: "";
	width: 5px;
	height: 100%;
	background-color: #078DFF;
	border-radius: 2px;
	position: absolute;
	left: -10px;
	top: 0;
}

</style>