<template>
<div class="volume-container">
  <div class="body scroll-view">
    <div class="bl-flex hw" center>
      <div class="bl-flex" size-md bg-color-f items-center padding-sm padding-left-md padding-right-md round-pie1
        v-if="$route.query.buyer">
        <i class="font-ileads ileads-icon-gouxuan1" size-lg color-success margin-right-sm></i>
        <div bold>购买成功</div>
      </div>
    </div>
    <div class="bl-flex" v-if="data.topic.is_memo && data.topic.memo" column padding-left-lg>
      <div color-f bold class="h-memo-h1">留下您的联系方式，</div>
      <div color-f bold class="h-memo-h2">我们尽快为您预约哦</div>
    </div>
    
    <div class="bl-flex" column padding-lg>
      <div class="bl-flex" flex-end>
        <div class="bl-flex">
          <img :src="ImgLeads1" class="il-img2" />
        </div>
      </div>
      <div class="bl-flex card" column card not-margin not-padding>
        <div margin-bottom-md shadow round padding-bottom-sm padding-top-xs
          v-for="(combo, comboIndex) in putResult"
          :key="comboIndex">
          <div class="bl-flex" flex-wrap items-center between border-bottom padding-md padding-left-lg
            v-if="combo.id">
            <div color-warning bold size-sm>{{ combo.name }}</div>
            <span color active padding-top-xs padding-bottom-xs size-xs v-if="!!comboIndex" @click="copyPrevVal(combo.result, comboIndex)">与上一个内容一致</span>
          </div>
          <transition-group name="flip-list" class="volume-content bl-flex" tag="div" column size-sm padding-left-lg padding-right-lg>          
            <div
              v-for="(item, index) in combo.result"
              :key="index + 1"
              :class="{ cur: edataItem === item }"
              @click="$emit('selectItem', item)">

              <div class="bl-flex" border-bottom
                :items-center="item.type != 'textarea'">
                <label class="f-label" nowrap :padding-top-lg="item.type == 'textarea'">
                  <span v-if="item.required" color-error>*</span>
                  {{ item.title }}
                </label>
                <div flex1>
                  <textarea 
                    v-model="item.val" 
                    :maxlength="item.max || 200" placeholder="请填写" 
                    :text-right="(item.layout_align || data.topic.layout_align) === 'right'"
                    v-if="item.type === 'textarea'" />

                  <input v-model="item.val" 
                    :maxlength="item.max || 200" 
                    :text-right="(item.layout_align || data.topic.layout_align) === 'right'"
                    :placeholder="['input'].includes(item.type) ? '请填写' : '请选择'" 
                    :readonly="!['input'].includes(item.type) || item.disabled"
                    v-if="['input', 'select', 'date'].includes(item.type)"
                    @click="!['input'].includes(item.type) && btnOpen(item)" />

                  <div class="slider-layout" v-if="item.type === 'slider'">
                    <div class="val" v-if="item.val">{{ item.val }}</div>
                    <div class="warn" v-else>拨动滑块选择</div>
                    <van-slider
                      v-model="item.sliderVal"
                      :min="-1" 
                      :max="item.content.length - 1"
                      @input="item.val = (item.content[item.sliderVal] || {}).title || ''" />
                    <div class="ruler-layout">
                      <div class="ruler-item">
                        <span></span>
                      </div>
                      <div class="ruler-item"
                        v-for="(it, itIndex) in item.content"
                        :key="itIndex">
                        <span v-if="!it.sliderHide">
                          {{ it.title }}
                          <br v-if="it.memo" />
                          {{ it.memo || '' }}
                        </span>
                      </div>
                    </div>
                  </div>

                  <van-radio-group padding-top-sm padding-bottom-sm
                    v-model="item.val" 
                    :style="{ justifyContent: (item.layout_align || data.topic.layout_align) === 'right' ? 'flex-end' : 'flex-start' }"
                    :direction="(item.layout_inline || data.topic.layout_inline) === 2 ? 'vertical' : 'horizontal'"
                    v-if="['radio'].includes(item.type)">
                    <van-radio
                      :class="(item.layout_inline || data.topic.layout_inline) === 2 ? 'vertical' : 'horizontal'"
                      :name="it.title" 
                      v-for="(it, itIndex) in item.content" 
                      :key="itIndex">{{ it.title }}{{ it.memo && `（${it.memo}）` }}</van-radio>
                  </van-radio-group>

                  <van-checkbox-group padding-top-sm padding-bottom-sm
                    v-model="item.val"
                    :style="{ justifyContent: (item.layout_align || data.topic.layout_align) === 'right' ? 'flex-end' : 'flex-start' }"
                    :direction="(item.layout_inline || data.topic.layout_inline) === 2 ? 'vertical' : 'horizontal'"
                    :max="item.max" 
                    v-if="item.type === 'checkbox'">
                    <van-checkbox 
                      :class="(item.layout_inline || data.topic.layout_inline) === 2 ? 'vertical' : 'horizontal'"
                      :name="it.title" 
                      v-for="(it, itIndex) in item.content" 
                      :key="itIndex" 
                      shape="square">{{ it.title }}{{ it.memo && `（${it.memo}）` }}</van-checkbox>
                  </van-checkbox-group>
                </div>
                <i class="font-ileads ileads-icon-jiantou" color-des padding-sm not-padding-right
                  v-if="['select', 'date'].includes(item.type)"
                  @click="btnOpen(item)"></i>
              </div>
            </div>
          </transition-group>
        </div>
        <div class="bl-flex" relative between padding-top-lg>
          <div class="l-pie" round-pie bg-color-6></div>
          <div class="r-pie" round-pie bg-color-6></div>
        </div>
        <div class="bl-flex" padding-lg padding-left-xl padding-right-xl v-if="!!data.result.length">
          <button class="btn primary" round-pie1
            :disabled="loading.submit || !data.result.length" 
            @click="$emit('submit', combos)">提交</button>
        </div>
      </div>
    </div>
  </div>

  <slot />

  <van-popup v-model="show.picker" position="bottom">
    <van-picker
      :title="comPicker.title"
      show-toolbar
      :columns="comPicker.columns"
      @confirm="onConfirmPicker"
      @cancel="onCancelPicker"
    />
  </van-popup>

  <van-popup v-model="show.date" position="bottom">
    <van-datetime-picker
      v-model="comDate.currentDate"
      type="date"
      :title="comDate.title"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="onConfirmDate"
      @cancel="onCancelDate"
    />
  </van-popup>
</div>
</template>

<script>
import mixinLayout from '../mixins/layout'
import ImgLeads1 from '~/img/leads-img1.png'
export default {
  mixins: [mixinLayout],
  data () {
    let maxDate = new Date()
    let minDate = new Date(maxDate.getFullYear() - 100, 0, 1)
    return {
      ImgLeads1,
      maxDate,
      minDate,
      show: {
        picker: false,
        date: false
      },
      comPicker: {
        title: '',
        columns: [],
        defaultIndex: 0,
        data: {}
      },
      comDate: {
        title: '',
        currentDate: '',
        data: {}
      },
      combos: []
    }
  },
  computed: {
    putResult () {
      return (this.combos && this.combos.length)
        ? this.combos
        : [this.data]
    }
  },
  methods: {
    btnOpen (item) {
      let config = {
        'select': () => this.onOpenPicker(item),
        'date': () => this.onOpenDate(item)
      }
      let fn = config[item.type]
      fn && fn()
    },
    onOpenPicker (item) {
      let columns = item.content.map(it => it.title)
      let index = columns.indexOf(item.val)
      this.$set(this, 'comPicker', {
        title: `请选择${item.title}`,
        columns,
        defaultIndex: index != -1 ? index : 0,
        data: item
      })
      this.show.picker = true
    },
    onConfirmPicker (value) {
      this.comPicker.data.val = value
      this.onCancelPicker()
    },
    onCancelPicker () {
      this.show.picker = false
    },
    onOpenDate (item) {
      let currentDate
      try {
        if (item.val) {
          currentDate = new Date(item.val.replace(/-/g, '/'))
        } else {
          currentDate = new Date()
        }
      } catch (err) {
        currentDate = new Date()
      }
      this.$set(this, 'comDate', {
        title: `请选择${item.title}`,
        currentDate,
        data: item
      })
      this.show.date = true
    },
    onConfirmDate (value) {
      this.comDate.data.val = value.toString('yyyy-MM-dd')
      this.onCancelDate()
    },
    onCancelDate () {
      this.show.date = false
    },
    inCombos () {
      let { ids, combos } = this.$route.query
      let arr_ids = ids && ids.split(',')
      let arr_combos = combos && combos.split(',')
      let comboRst = arr_ids && arr_ids.map((id, index) => {
        return {
          id,
          name: arr_combos[index],
          query: {
            buyer_id: id
          },
          result: JSON.parse(JSON.stringify(this.data.result))
        }
      })
      this.combos = comboRst
    },
    // 与上一个内容一致
    copyPrevVal (result, index) {
      try {
        let prevItem = this.combos[index - 1]
        if (!prevItem) {
         throw new Error('缺少上一个表单对象')
        }
        result.forEach((item, i) => {
          item.val = prevItem.result[i].val
        })
      } catch (err) {
        this.$toast.fail('引用错误')
      }
    },
    init () {
      this.inCombos()
    }
  },
  created () {
    this.init()
  }
}
</script>

<style lang="scss" scoped>
@import './style.scss';
</style>
