<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>
              <el-button v-if="status === '2'" size="medium" @click="handleReturn" round>返回</el-button>
              <el-button v-else size="medium" type="primary" @click="handleFinish(false)" plain 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(false)" plain round>保存报告</el-button>
              <el-button v-if="status !== '3'" type="primary" size="medium" @click="handleFinish(1)" 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, getReportDetails, saveReport, getReportRecord } 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,
      recordId: ''
    }
  },
  computed: {
    case() {
      return this.$store.state.case
    }
  },
  created() {
    if (![2, 4].includes(this.$store.state.role)) {
      this.$router.push('/home')
      return
    }
    this.recordId = this.$route.query.id || ''
    this.status = this.$route.query.type || '0'
    this.init()
  },
  methods: {
    init() {
      Promise.all([this.fetchQuestions(), this.fetchGetReport()]).then(res => {
        const singleChoice = []
        const multiChoice = []
        // 组装数据
        res[0].forEach(item => {
          // 模拟多选题
          // if (['学历', '可支配资产总额', '娱乐偏好', '购物服务要求程度', '感兴趣的金融信息', '感兴趣的优惠方式', '金融产品服务要求程度'].includes(item.subject)) {
          //   item.display_multi = 1
          // }
          if (item.display_multi === 0) singleChoice.push(item)
          else multiChoice.push(item)
        })
        const questions = [...singleChoice, ...multiChoice]
        let selection = []
        if (res[1] && 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) {
          const tagArr = item.selection.map(it => it.tag)
          tableFilter[item.tag] = tagArr.join(',')
        }
      })
      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(isComplete) {
      const selection = []
      let isFinish = true
      for (let i = 0; i < this.questions.length; i++) {
        const item = this.questions[i]
        if (item.selection.length) {
          item.selection.forEach(it => selection.push(it.id))
          // selection.push(item.selection[0].id)
        } else {
          isFinish = false
          if (isComplete) break
        }
      }
      if (isComplete) {
        if (isFinish) this.fetchSubmitReport(selection)
        else this.$message.error('请完成全部选题再提交')
      } else {
        if (selection.length > 0) this.fetchSaveReport(selection)
        else this.$message.error('您并没有选中项需要保存')
      }
    },
    handleSubmit() {
      this.$message.error('暂未开通此功能')
    },
    initQuestions(questions, selection) {
      questions.forEach((item, index) => {
        let selectArr
        if (selection.length) {
          selectArr = selection.filter(it => it.question_id === item.id)
        }
        if (selectArr) {
          const selectIds = selectArr.map(it => it.id)
          const opt = item.options.filter(it => selectIds.includes(it.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() {
      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)
      }
      if (this.recordId) params.id = this.recordId
      submitReport(params).then(res => {
        if (res.data) {
          this.score = res.data.score
          this.status = '3'
          if (res.data.deduct_points > 10) {
            this.$alert('您所选的用户标签不符合当前案例的目标客群，选择次数已超3次，您对营销目标客群选择并不熟悉，请加强学习，返回重新开始', '提示', {
              confirmButtonText: '重新开始',
              showClose: false,
              callback: action => {
                this.fetchClearScore()
              }
            })
          }
        }
      }).catch(err => {
        this.$message({
          message: err.message || '根据您选择的目标人群特征分析，此类受众并不适合当前的金融产品,请重新选择！',
          type: 'error',
          duration: 10000
        })
        // this.$message.error(err.message || '根据您选择的目标人群特征分析，此类受众并不适合当前的金融产品,请重新选择！')
      })
    },
    fetchSaveReport(list) {
      const params = {
        option_ids: JSON.stringify(list)
      }
      saveReport(this.case.id, params).then(res => {
        if (res.code === 0 && res.data && res.data.id) {
          this.recordId = res.data.id
          this.$message.success('保存成功！')
        }
      })
    },
    fetchClearScore() {
      clearScore().then(res => {
        if (res.code === 0 && res.data && res.data.status) {
          this.$message.success('重置成功！')
          this.fetchQuestions().then(res => {
            this.initQuestions(res, [])
            this.handleChoiceSelect()
          }).catch(err => {
            console.log(err)
          })
          this.status = '0'
        }
      })
    },
    fetchGetReport() {
      return new Promise((resolve, reject) => {
        if (this.recordId) {
          getReportDetails(this.recordId).then(res => {
            if (res.code === 0 && res.data && res.data.detail) {
              resolve(res.data.detail)
            } else {
              reject(res)
            }
          }).catch((err) => reject(err))
        } else {
          getReportRecord(this.case.id, 3).then(res => {
            if (res.code === 0 && res.data && Array.isArray(res.data.items)) {
              if (res.data.items[0]) this.recordId = res.data.items[0].id
              resolve(res.data.items[0])
            } else {
              reject(res)
            }
          })
        }
      })
    }
  }
}
</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>
