<template>
  <div class="user-study">
    <h5>请为您的目标人群选择特征</h5>
    <div class="container">
      <div class="left">
        <div class="top-bar">
          <el-button v-show="!showTool" type="primary" size="medium" round @click="showTool = true">编程工具</el-button>
          <el-button v-show="showTool" type="primary" size="medium" round @click="showTool = false">关闭工具</el-button>
        </div>
        <div class="questions" v-if="!showTool">
          <multiple-choice :choice="current.choice" v-if="['0', '2'].includes(status)" @select="handleChoiceSelect">
            <template #btn-prev v-if="status === '0'">
              <el-button v-if="current.index !== 0" size="medium" @click="handlePrev" round>上一题</el-button>
            </template>
            <template #btn-center v-if="status === '2'">
              <el-button size="medium" @click="handleReturn" round>返回</el-button>
            </template>
            <template #btn-next v-if="status === '0'">
              <el-button v-if="current.index < questions.length - 1" type="primary" size="medium" @click="handleNext" round>下一题</el-button>
              <el-button v-else type="primary" size="medium" @click="handleComplete" round>完成选择</el-button>
            </template>
          </multiple-choice>
          <div v-else class="complete">
            <p>根据您选择的目标人群特征分析，此类受众并不适合当前的金融产品,请重新选择！</p>
            <answer-list :list="questions" @select="handleSelect"></answer-list>
            <div style="text-align:center;">
              <el-button v-if="status !== '3'" type="primary" size="medium" @click="handleFinish" round>完成报告</el-button>
            </div>
          </div>
        </div>
        <div class="tool" v-else>
          <codemirror class="code" v-model="code"></codemirror>
          <div style="text-align:center;padding-top:15px;">
            <el-button type="primary" size="medium" @click="handleSubmit" round>确认提交</el-button>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="score" v-if="status === '3'">
          <score-svg></score-svg>
          <p>{{score}}分</p>
        </div>
        <template v-else>
          <tabs v-model="tabActive" :list="list" @tab-click="handleTabClick"></tabs>
          <div class="echart-cont" v-show="tabActive === '1'">
            <echart-bar :value="current.choice"/>
          </div>
          <user-table :params="tableFilter" v-show="tabActive === '2'" />
        </template>
      </div>
    </div>
  </div>
</template>

<script>
// 组件
import MultipleChoice from '../components/MultipleChoice.vue'
import Tabs from '../components/Tabs.vue'
import AnswerList from '../components/AnswerList.vue'
import UserTable from '../components/UserTable.vue'
import EchartBar from '../components/EchartBar.vue'
import ScoreSvg from '../components/ScoreSvg.vue'
// api
import { getQuestions, submitReport, clearScore, getReport } from '../api'
export default {
  components: { MultipleChoice, Tabs, AnswerList, UserTable, EchartBar, ScoreSvg },
  data() {
    return {
      showTool: false,
      questions: [
        {
          id: '111',
          title: '消费者年龄',
          options: [
            { label: '18岁以下', value: 1 },
            { label: '18-30岁', value: 2 },
            { label: '31-45岁', value: 3 },
            { label: '46-60岁', value: 4 }
          ],
          selection: [],
          index: 1
        }
      ],
      selection: [],
      tableFilter: {},
      current: {
        index: 0,
        choice: {}
      },
      status: '0', // '0':未完成，'1':已完成，'2':修改, '3':成绩
      code: '',
      tabActive: '1',
      list: [
        { label: '数据展示', value: '1' },
        { label: '数据列表', value: '2' }
      ],
      score: 0
    }
  },
  created() {
    if (![2, 4].includes(this.$store.state.role)) {
      this.$router.push('/home')
      return
    }
    this.init()
    this.status = this.$route.query.type || '0'
  },
  methods: {
    init() {
      Promise.all([this.fetchQuestions(), this.fetchGetReport()]).then(res => {
        // 组装数据
        const questions = res[0]
        console.log(res[0], res[1])
        let selection = []
        if (res[1].answer && Array.isArray(res[1].answer.options)) {
          selection = res[1].answer.options
          this.score = res[1].answer.score
        }
        if (selection.length > 0 && this.status !== '3') {
          this.status = '1'
        }
        this.initQuestions(questions, selection)
        this.handleChoiceSelect()
      }).catch(() => {
        if (!(this.$store.state.case && this.$store.state.case.id)) {
          this.$alert('请先选择完成产品分析案例选择，再进行用户分析', {
            confirmButtonText: '回到首页',
            showClose: false,
            callback: action => {
              this.$router.push('/home')
            }
          })
        }
      })
    },
    handlePrev() {
      this.current.index--
      this.current.choice = this.questions[this.current.index]
    },
    handleNext() {
      if (this.current.index < this.questions.length - 1) {
        this.current.index++
        this.current.choice = this.questions[this.current.index]
      }
    },
    handleComplete() {
      this.status = 1
    },
    handleTabClick() {},
    handleChoiceSelect() {
      const tableFilter = {}
      this.questions.forEach(item => {
        if (item.selection.length) {
          tableFilter[item.tag] = item.selection[0].tag
        }
      })
      this.tableFilter = tableFilter
    },
    handleSelect(val) {
      if (this.status !== '3') {
        this.current.index = val.index - 1
        this.current.choice = val
        this.status = '2'
      }
    },
    handleReturn() {
      this.status = '1'
    },
    handleFinish() {
      const selection = []
      const isFinish = true
      for (let i = 0; i < this.questions.length; i++) {
        const item = this.questions[i]
        if (item.selection.length) {
          selection.push(item.selection[0].id)
        } else {
          this.$message.error('请完成全部选题再提交')
          this.isFinish = false
          break
        }
      }
      if (isFinish) {
        this.fetchSubmitReport(selection)
      }
    },
    handleSubmit() {
      this.$message.error('暂未开通此功能')
    },
    initQuestions(questions, selection) {
      questions.forEach((item, index) => {
        let selectItem
        if (selection.length) {
          selectItem = selection.find(it => it.question_id === item.id)
        }
        if (selectItem) {
          const opt = item.options.find(it => it.id === selectItem.id)
          item.selection = [opt]
        } else {
          item.selection = []
        }
        item.index = index + 1
      })
      this.questions = questions
      this.current.index = 0
      this.current.choice = this.questions[0]
    },
    fetchQuestions() {
      // getQuestions().then(res => {
      //   if (res.code === 0 && res.data && Array.isArray(res.data.items)) {
      //     const list = res.data.items
      //     list.forEach((item, index) => {
      //       item.selection = []
      //       item.index = index + 1
      //     })
      //     this.questions = list
      //     this.current.index = 0
      //     this.current.choice = this.questions[0]
      //   }
      // })
      return new Promise((resolve, reject) => {
        getQuestions().then(res => {
          if (res.code === 0 && res.data && Array.isArray(res.data.items)) {
            resolve(res.data.items)
          } else {
            reject(res)
          }
        }).catch((err) => reject(err))
      })
    },
    fetchSubmitReport(list) {
      const params = {
        option_ids: JSON.stringify(list)
      }
      submitReport(params).then(res => {
        if (res.data) {
          if (res.data.deduct_points > 10) {
            this.$alert('您所选的用户标签不符合当前案例的目标客群，选择次数已超3次，您对营销目标客群选择并不熟悉，请加强学习，返回重新开始', '提示', {
              confirmButtonText: '重新开始',
              showClose: false,
              callback: action => {
                this.fetchClearScore()
              }
            })
          } else {
            this.score = res.data.score
            this.status = '3'
          }
        }
      }).catch(err => {
        this.$message.error(err.message || '根据您选择的目标人群特征分析，此类受众并不适合当前的金融产品,请重新选择！')
      })
    },
    fetchClearScore() {
      clearScore().then(res => {
        if (res.code === 0 && res.data && res.data.status) {
          this.$message.success('重置成功！')
          this.fetchQuestions().then(res => {
            this.initQuestions(res, [])
          }).catch(err => {
            console.log(err)
          })
          this.status = '0'
        }
      })
    },
    fetchGetReport() {
      return new Promise((resolve, reject) => {
        getReport().then(res => {
          if (res.code === 0 && res.data && res.data.records) {
            resolve(res.data.records)
          } else {
            reject(res)
          }
        }).catch((err) => reject(err))
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.user-study{
  width:1260px;
  padding-bottom:40px;
  /* height:calc(100vh - 86px); */
  margin:0 auto;
}
h5{
  font-size:22px;
  line-height:68px;
  font-weight:normal;
  color:#585858;
}
.container{
  display:flex;
}
.container .left{
  width:43%;
  background:#fff;
  height:538px;
}
.top-bar{
  padding:20px 30px 0;
  text-align:right;
}
.top-bar .el-button, .complete .el-button, .tool .el-button{
  padding:8px 30px;
}
.questions{
  height: calc(100% - 52px);
  overflow-y: auto;
  &::-webkit-scrollbar{
    width: 4px;
    height: 4px;
  }
  &::-webkit-scrollbar-button{
    width: 0;
    height: 0;
  }
  &::-webkit-scrollbar-track{
  }
  &::-webkit-scrollbar-thumb{
    border-radius: 8px;
    background-color: #c3e3db;
  }
  &::-webkit-scrollbar-thumb:hover {
    background-color: #68b8a4;
  }
  &::-webkit-scrollbar-thumb:active {
    background-color: #68b8a4;
  }
}
.complete{
  padding:20px 25px;
}
.complete>p{
  font-size:16px;
  line-height:30px;
  color:#333;
  user-select: none;
}
.tool{
  padding:15px 20px;
}
.code ::v-deep.CodeMirror {
  height: 398px;
}
.container .right{
  width:calc(57% - 20px);
  margin-left:20px;
  background:#fff;
}
.echart-cont{
  padding:30px 30px 20px;
  height:calc(100% - 54px);
}
.score{
  text-align:center;
  padding-top:100px;
}
.score p{
  font-size:40px;
  line-height:80px;
  font-weight:bold;
}
</style>
