<template>
  <div class="tabPager">
    <h1 class="pager_title">{{ title }}</h1>
    <p v-if="remark" class="remark">
      {{ remark }}
    </p>
    <div v-for="item in pagerLists" :class="{delLine: item.isJump}" :key="item.queguid" class="question">
      <template v-if="!item.isJump">
        <div class="title">
          <b v-if="item.isanswer" class="sign">*</b>
          <span class="sort">{{ item.sort + 1 }}</span>
          <b class="option_title">{{ item.quetitle }}</b>
        </div>
        <div class="queOpion">
          <template v-if="item.type === 1">
            <el-input :rows="2" v-model="item.remark" type="textarea" placeholder="请输入内容"/>
          </template>
          <template v-else-if="item.type === 2">
            <el-radio-group v-model="item.checkid" @change="jumpPage(item, $event)">
              <el-radio v-for="optR in item.itemList" :key="optR.itemid" :label="optR.itemid">
                {{ optR.name }}
              </el-radio>
            </el-radio-group>
          </template>
          <template v-else>
            <el-checkbox-group v-model="item.checkid">
              <el-checkbox v-for="optC in item.itemList" :key="optC.itemid" :label="optC.itemid">
                {{ optC.name }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
        </div>
      </template>
    </div>
    <p v-if="pagerLists.length > 0" class="btn">
      <el-button type="primary" @click="submitPager">提 交</el-button>
    </p>
  </div>
</template>

<script>
// import { getPager, answerPager } from '@/api/questionnaire/management'
import { uniqueObjArray } from '@/utils'

export default {
  name: 'TabPager',
  props: {
    pagerDatas: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      loading: false,
      title: '',
      remark: '',
      pagerid: '',
      pagerLists: [],
      jumpItem: [] // 跳过的试题
    }
  },
  watch: {
    pagerDatas(newValue, oldValue) {
      // console.log(newValue.pageid, oldValue.pageid)
      if (newValue.pageid && oldValue.pageid === undefined) {
        this.getPagers()
      }
    }
  },
  created() {},
  methods: {
    // 获取问卷信息
    getPagers() {
      this.loading = true
      return new Promise(resolve => {
        // getPager(this.pagerDatas.pageid).then(response => {
        //   this.loading = false
        //   if (response.state.toLowerCase() === 'success') {
        //     // 修改父组件的值
        //     this.$emit('getPagerTitle', response.data.title)
        //     this.title = response.data.title
        //     this.remark = response.data.remark
        //     if (response.data.item && response.data.item.length > 0) {
        //       this.pagerLists = this.changePagerOptions(response.data.item)
        //     }
        //   }
        // })
        resolve()
      })
    },

    // 提交
    submitPager() {
      // 验证必填项
      let pagerOptions = []
      // 正常接通
      if (this.pagerDatas.callresult === '5bfe540c5a10b06b7a35a83a') {
        if (this.validPager() === false) {
          return
        }
        // 修改试题数据用于提交
        pagerOptions = this.getPagerOptions()
      }
      const data = Object.assign(this.pagerDatas, {
        result: pagerOptions
      })
      // console.log(JSON.stringify(data));
      // answerPager(data).then(response => {
      //   this.loading = false
      //   if (response.state.toLowerCase() === 'success') {
      //     // 触发父组件的方法
      //     this.$emit('getTP')
      //     this.$message.success('恭喜你，数据提交成功!')
      //   }
      // }).catch(() => {
      //   this.loading = false
      // })
    },

    // 单选题跳题
    jumpPage(value, e) {
      // 1.获取跳题的 queguid
      let jumpid = null
      const csort = value.sort
      for (let i = 0, len = value.itemList.length; i < len; i++) {
        // 去重 this.jumpItem 根据选项 optionId
        this.jumpItem = uniqueObjArray(this.jumpItem, e)
        this.jumpItem.forEach((v, n) => {
          if (v.itemId === value.queid) {
            v.arr.forEach((k, j) => {
              this.$set(k, 'isJump', false)
            })
          }
        })
        if (value.itemList[i].queguid && value.itemList[i].itemid === e) {
          jumpid = value.itemList[i].queguid
          break
        }
      }
      // 2.根据 queguid 获取当前试题 -- 跳到试题之间的 试题
      if (jumpid) {
        for (let j = 0, len = this.pagerLists.length; j < len; j++) {
          if (this.pagerLists[j].queguid === jumpid) {
            const arr = this.pagerLists.filter((v, i) => {
              return i > csort && i < this.pagerLists[j].sort
            })
            this.jumpItem.push({
              itemId: value.queid, // 当前试题id
              optionId: e, // 选项id
              arr: arr
            })
            arr.forEach((v, k) => {
              this.$set(v, 'isJump', true)
            })
          }
        }
      }
    },

    // 验证数据
    validPager() {
      for (let i = 0, len = this.pagerLists.length; i < len; i++) {
        // 跳过的题不验证
        if (this.pagerLists[i].isJump) {
          continue
        }
        if (this.pagerLists[i].isanswer) {
          if (this.pagerLists[i].type === 3 && this.pagerLists[i].checkid.length === 0) {
            this.$message.warning(`你还没有选择${this.pagerLists[i].quetitle}`)
            return false
          }
          if (this.pagerLists[i].type === 1 && !this.pagerLists[i].remark) {
            this.$message.warning(`您还没有填写${this.pagerLists[i].quetitle}`)
            return false
          }
        }
      }
    },

    // 修改获取的数据
    changePagerOptions(arr) {
      const tem = []
      arr.forEach((v, i) => {
        const itemTem = []
        let checkid = null
        if (v.item.length > 0) {
          v.item.forEach((v, i) => {
            itemTem.push({
              'itemid': v.id, // 选项id
              'queguid': v.queguid, // 选择的跳转 单选问题guid
              'name': v.itemsname,
              'sort': v.sort
            })
          })

          if (v.type === 2) { // 单选
            // checkid = v.item[0].id;
            checkid = ''
          } else if (v.type === 3) {
            // checkid = v.item[0].id.split();
            checkid = []
          }
        }
        tem.push({
          'queid': v.id, // 试题id
          'queguid': v.queguid,
          'quetitle': v.title,
          'type': v.type,
          'sort': v.sort,
          'remark': v.remark,
          'isanswer': v.isanswer, // 是否是必填
          'isJump': false, // 是否是跳过
          'checkid': checkid,
          'itemList': itemTem
        })
      })
      return tem
    },

    // 提交前试题数据修改
    getPagerOptions() {
      const tem = []
      this.pagerLists.forEach((v, i) => {
        // 跳过的题不保存
        if (!v.isJump) {
          const itemTem = []
          if (v.type > 1) {
            v.itemList.forEach((m, i) => {
              let ischeck = 0
              if (v.type === 2) {
                if (v.checkid === m.itemid) {
                  ischeck = 1
                }
              }
              if (v.type === 3) {
                if (v.checkid && v.checkid.length > 0) {
                  v.checkid.forEach((k, j) => {
                    if (k === m.itemid) {
                      ischeck = 1
                    }
                  })
                }
              }
              itemTem.push({
                'itemid': m.itemid,
                'sort': m.sort,
                'name': m.name,
                'ischeck': ischeck
              })
            })
          }
          tem.push({
            'queid': v.queid,
            'sort': v.sort,
            'quetitle': v.quetitle,
            'type': v.type,
            'remark': v.remark,
            'itemList': itemTem
          })
        }
      })
      return tem
    }

  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
	.tabPager {
		.pager_title {
			text-align: center;
			font-size: 24px;
			color: #333333;
		}

		.remark {
			font-size: 16px;
			text-align: justify;
			text-indent: 2em;
			letter-spacing: 1px;
			color: #333333;
			word-break: break-all;
			word-wrap: break-word;
			line-height: 24px;
		}

		.question {
			padding: 20px;
			border-bottom: 2px solid #F1F1F1;

			.title {
				margin-bottom: 30px;
				position: relative;

				.sign {
					color: #F14949;
					vertical-align: middle;
					position: absolute;
					left: 5px;
					top: 5px;
				}

				.sort {
					display: inline-block;
					width: 30px;
					height: 24px;
					background-color: #409EFF;
					border-radius: 2px;
					color: #FFFFFF;
					text-align: center;
					line-height: 24px;
					font-size: 14px;
					margin-left: 20px;
				}

				.option_title {
					padding-left: 20px;
					font-weight: bold;
					font-size: 14px;
					color: #333333;
				}
			}

			.queOpion {
				font-size: 14px;
				padding: 0 12px;
				color: #333333;
			}

			.operate_btn {
				text-align: right;
			}
		}

		.delLine {
			border: none;
			padding: 0;
		}

		.btn {
			width: 100%;
			text-align: center;

			.el-button {
				width: 240px;
			}
		}
	}
</style>
