<template>
  <div class="report-box">
    <slot></slot>
    <template v-if="Object.keys(titleData).length">
      <div class="title">
        产品分析报告<span
          @click="errorResolutionTit"
          v-if="$route.path !== '/product-analysis/report' && !this.titleData.completions[0].is_correct"
          >错题解析</span
        >
      </div>
      <input
        v-if="$route.path !== '/product-analysis/result'"
        type="text"
        class="code isDomActive"
        placeholder="请输入基金简称+基金代码"
        v-model="titleValue"
      />
      <input
        v-else
        type="text"
        :class="`code isDomActive ${titleData.completions[0].is_correct ? '' : 'active'}`"
        placeholder="请输入基金简称+基金代码"
        v-model="titleValue"
      />
    </template>
    <div v-for="(item, index) in completions" :key="index">
      <!-- 产品概括 -->
      <product
        @errorResolution="errorResolution"
        ref="product"
        v-if="item.tag === 'product_overview'"
        :data="item"
      ></product>
      <!-- 投资目标 -->
      <invest-target
        @errorResolution="errorResolution"
        ref="investTarget"
        v-if="item.tag === 'investment_objectives'"
        :data="item"
      ></invest-target>
      <!-- 投资目标 -->
      <invest-strategy
        @errorResolution="errorResolution"
        ref="investStrategy"
        v-if="item.tag === 'investment_strategy'"
        :data="item"
      ></invest-strategy>
      <!-- 业绩比较基准 -->
      <compares
        @errorResolution="errorResolution"
        ref="compares"
        v-if="item.tag === 'performance_benchmark'"
        :data="item"
      ></compares>
      <!-- 风险收益特征 -->
      <features
        @errorResolution="errorResolution"
        ref="features"
        v-if="item.tag === 'risk_return_characteristics'"
        :data="item"
      ></features>
      <!-- 基金涉及费用 -->
      <cost
        @errorResolution="errorResolution"
        ref="cost"
        v-if="item.tag === 'fund_related_expenses'"
        :data="item"
      ></cost>
    </div>
    <!-- 提交 -->
    <div class="tool-btn">
      <div class="submit-btn" @click="commitCase" v-if="$route.path !== '/product-analysis/result'">提交报告</div>
      <div class="submit-btn" @click="cacheCaseAnswer" v-if="$route.path !== '/product-analysis/result'">保存</div>
    </div>
  </div>
</template>

<script>
import $ from 'jquery'
import { caseCompletions, getCommitCase, commitCase, cacheCaseAnswer } from '../api'
import Product from './Products.vue'
import InvestTarget from './InvestTarget.vue'
import InvestStrategy from './InvestStrategy.vue'
import Compares from './Compares.vue'
import Features from './Features.vue'
import Cost from './Cost.vue'
export default {
  components: {
    Product,
    InvestTarget,
    Compares,
    Features,
    Cost,
    InvestStrategy
  },
  data() {
    return {
      completions: [],
      resultCompletions: [],
      titleValue: '',
      titleData: {},
      isCommitCase: false
    }
  },
  computed: {
    cases() {
      return this.$store.state.case
    }
  },
  mounted() {
    this.getCommitCase()
  },
  methods: {
    errorResolution(data) {
      this.$emit('errorResolution', data)
    },
    errorResolutionTit() {
      this.$emit('errorResolution', this.titleData)
    },
    // 保存答案
    cacheCaseAnswer() {
      const data = this.getAnswer(1)
      cacheCaseAnswer(this.cases.id, { answers: JSON.stringify(data) })
        .then(res => {
          this.$message({ type: 'success', message: '保存成功' })
        })
        .catch(err => {
          this.$message.error(err.message || '稍后再试')
        })
    },
    // 模板  数据回显
    caseCompletions(id) {
      caseCompletions(id).then(res => {
        res.data.items.map(item => {
          return item.completions.map(cItem => {
            if (!Array.isArray(this.resultCompletions)) {
              const findData = this.resultCompletions.answer.find(fItem => {
                return fItem.id === cItem.id
              })
              findData ? (cItem = Object.assign(cItem, findData)) : (cItem.commit_answer = '')
            } else {
              cItem.commit_answer = ''
            }
            return cItem
          })
        })
        this.completions = res.data.items
        // 标题回显
        this.titleData = this.completions.find(item => {
          return item.tag === 'product_title'
        })
        if (this.titleData) this.titleValue = this.titleData.completions[0].commit_answer
      })
    },
    // 结果
    getCommitCase() {
      const id = this.$route.query.id
      if (id) {
        getCommitCase(id).then(res => {
          this.resultCompletions = res.data.detail
          this.caseCompletions(this.cases.id)
          this.$emit('getScore', this.resultCompletions)
        })
      } else {
        this.caseCompletions(this.cases.id)
      }
    },
    input() {
      this.isCommitCase = false
    },
    // 获取填写的答案
    getAnswer(isCache) {
      // 产品概括数据
      const productCount = []
      this.$refs.product[0].data.completions.forEach(item => {
        productCount.push({ id: item.id, commit_answer: item.commit_answer })
      })
      // 投资目标
      const originalData = this.$refs.investTarget[0].data.completions[0]
      const investTargetCount = [{ id: originalData.id, commit_answer: originalData.commit_answer }]
      // 投资目标
      const strategyData = this.$refs.investStrategy[0].data.completions[0]
      const investStrategyCount = [{ id: strategyData.id, commit_answer: strategyData.commit_answer }]
      // 业绩比较基准数据
      const comparesCount = []
      let comparesData = {}
      if (this.$refs.compares) {
        this.$refs.compares[0].inputList.forEach(item => {
          comparesCount.push(`${item.input1.split(';').join('')},${item.input2.split(';').join('')}`)
        })
        comparesData = {
          id: this.$refs.compares[0].data.completions[0].id,
          commit_answer: comparesCount.join(';')
        }
        this.$refs.compares[0].data.completions[0].commit_answer = comparesCount.join(';')
      }
      // 风险收益特征数据
      const featuresCount = []
      if (this.$refs.compares) {
        this.$refs.features[0].data.completions.forEach(item => {
          featuresCount.push({ id: item.id, commit_answer: item.commit_answer })
        })
      }
      // 基金涉及费用数据
      const costCount = []
      this.$refs.cost[0].data.completions.forEach(item => {
        costCount.push({ id: item.id, commit_answer: item.commit_answer })
      })
      // 标题数据
      const findTitleData = this.completions.find(item => {
        return item.tag === 'product_title'
      }).completions[0]
      const titCount = [{ id: findTitleData.id, commit_answer: this.titleValue }]
      let allAnswer = [
        ...titCount,
        ...productCount,
        ...investTargetCount,
        ...[comparesData],
        ...featuresCount,
        ...costCount,
        ...investStrategyCount
      ]
      allAnswer = allAnswer.filter(item => Object.keys(item).length !== 0)
      if (isCache) {
        allAnswer = allAnswer.filter(item => item.commit_answer !== '')
      }
      return allAnswer
    },
    // 提交
    commitCase() {
      // 空数据的索引
      let emptyDataIndex = this.getAnswer().findIndex(item => item.commit_answer === '')
      // 判断业绩比较基准是否为空
      if (this.$refs.compares) {
        const hasEmptyInput = !!this.$refs.compares[0].inputList.find(item => {
          return item.input1 === '' || item.input2 === ''
        })
        if (hasEmptyInput) {
          const dataId = this.$refs.compares[0].data.completions[0].id
          const dataIndex = this.getAnswer().findIndex(item => item.id === dataId)
          emptyDataIndex = emptyDataIndex > dataIndex && emptyDataIndex !== -1 ? dataIndex : emptyDataIndex
        }
      }
      if (emptyDataIndex === -1) {
        const params = { answers: JSON.stringify(this.getAnswer()) }
        const id = this.$route.query.id
        if (id) params.id = id
        commitCase(params)
          .then(res => {
            this.$message({
              message: '保存成功！你可以在作品展示中查看/编辑报告，查看成绩',
              type: 'success'
            })
            setTimeout(() => {
              this.$router.push({ path: '/product-analysis/result', query: { id: res.data.answers.id } })
            }, 2000)
          })
          .catch(err => {
            this.$message.error(err.message || '稍后再试')
          })
      } else {
        // 空数据的元素
        const emptyElement = document.querySelector(`[id="${this.getAnswer()[emptyDataIndex].id}"]`)
        // 空的情况，所有的高亮
        $('.isDomActive').each(function () {
          $(this).removeClass('active')
          if (this.tagName === 'INPUT' || this.tagName === 'TEXTAREA') {
            if ($(this).val() === '') $(this).addClass('active')
          } else {
            if ($(this).find('textarea').val() === '') $(this).addClass('active')
            if ($(this).find('input').val() === '') $(this).addClass('active')
          }
        })
        $('.tag-input').css('border-bottom', '1px solid rgba(219, 38, 38, 1)')
        // 监听输入，去掉高亮
        $('.isDomActive').bind('input propertychange', function () {
          $(this).removeClass('active')
        })
        let top = 140
        if (emptyElement) {
          // 空数据元素的位置
          top = emptyElement.getBoundingClientRect().top + document.documentElement.scrollTop
          // emptyElement.classList.add('active')
        } else {
          this.isCommitCase = true
        }
        window.scrollTo(0, top)
        this.$message('请填写完整')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
input {
  background: none;
  border: none;
  outline: none;
  &.active {
    border-bottom: 1px solid #c11818 !important;
  }
}
.code {
  width: 370px;
  margin: 35px auto;
  height: 47px;
  display: block;
  text-align: center;
  border-bottom: 1px solid #b4b4b4;
  &::-webkit-input-placeholder {
    color: #afafaf;
  }
}
.submit-btn {
  width: 119px;
  background: #68b8a4;
  border-radius: 16px;
  text-align: center;
  margin: 42px 20px;
  line-height: 32px;
  color: #fff;
  font-size: 18px;
  cursor: pointer;
}
.title {
  font-size: 24px;
  font-weight: bold;
  color: #4cac94;
  line-height: 100%;
  text-align: center;
  margin-top: 27px;
  position: relative;
  span {
    position: absolute;
    right: 25px;
    top: 0;
    font-weight: normal;
    font-size: 16px;
    cursor: pointer;
    z-index: 999;
  }
}
.tool-btn {
  display: flex;
  justify-content: center;
}
</style>
