<template>
  <child-view>
    <div ref="box" class="sub-page">
      <div>
        <time-line v-if="showLine" ref="timeline" :status="content.status" :count="count" :isEnd="isEnd" />
      </div>
      <div class="bg-app-dark-2 border border-app-blue-3 border-solid rounded-lg mx-4 mt-4">
        <div class="p-4 border-0 border-b border-app-blue-3 border-solid">
          <community-card :community="content" type="pro" :voteId="content.ID" />
        </div>
        <div class="p-4 border-0 border-b border-app-blue-3 border-solid" :class="{'pb-44': hide && content.status === 2, 'pb-20': (hide && content.status !== 2) || (hide && !canVote)}">
          <div
            v-for="(item, index) in content.voteOptions"
            :key="index"
            class="mb-3 px-3 py-4 flex items-start border border-app-blue-3 border-solid rounded-lg"
            :class="{'opacity-50': !canVote}"
            >
            <img v-show="item.id !== selectId" class="w-4 h-4 mr-2 mt-0.5 flex-shrink-0" src="@/assets/unselect.png" alt="" @click="changeHandle(item.id)">
            <img v-show="item.id === selectId" class="w-4 h-4 mr-2 mt-0.5 flex-shrink-0" src="@/assets/selected.png" alt="" @click="changeHandle(item.id)">
            <div ref="content" class="text-sm px-3">
              <span class="inline-block break-all" v-if="item.type1 === 0">{{ item.name }}</span>
              <div v-else class="flex items-end" @click="triggle(index, item.type1)">
                <span class="inline-block transition-all duration-300 delay-100 ease-in-out overflow-hidden" :class="{ 'initial-height': item.type1 === 1, 'max-h-full': item.type1 === 2 }">
                  {{ item.name }}
                </span>
                <div class="transition-all duration-300 ease-in-out" :class="{'transform origin-center -rotate-90 mb-0': item.type1 === 2, 'mb-1': item.type1 === 1 }">
                  <app-icon customize type='icon-arrow-right-copy-copy'></app-icon>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="!hide" class="p-4" :class="{ 'fixed bottom-0 left-0 z-40 w-full bg-app-drak-1': hide }">
          <input v-show="canVote && content.status === 2" class="x-input text-sm" type="text" v-model="voteNum" @input="checkInput">
          <div v-if="canVote && content.status === 2" class="flex items-center justify-between">
            <p class="text-sm text-gray-400">可用余票 <span class="inline-block text-white opacity-100">{{ rest }}</span></p>
            <p class="text-xs" @click="inAll">全部填入</p>
          </div>
          <button
            class="w-full  h-10 leading-10 text-center text-sm rounded-lg"
            :class="[ btnType === 1 ? 'bg-app-blue-3' : btnType === 2 ? 'bg-yellow-500' : 'bg-app-blue-5', rest === 0 ? 'bg-app-blue-5' : 'bg-app-blue-3' ]"
            @click="vote">{{ voteText }}</button>
          <p v-if="canVote && content.status === 2" class="text-xs mt-2.5 mb-0 text-yellow-600 flex items-center justify-between">
            <span>投票成功后需要支付</span>
            <span>0.002BTY</span>
          </p>
        </div>
      </div>
      <!-- <div v-if="hide" class="fixed bottom-0 left-0 z-40 w-full bg-app-drak-1 p-4">
        <input v-show="canVote && content.status === 2" class="x-input text-sm" type="text" v-model="voteNum" @input="checkInput">
          <div v-if="canVote && content.status === 2" class="flex items-center justify-between">
            <p class="text-sm text-gray-400">可用余票 <span class="inline-block text-white opacity-100">{{ rest }}</span></p>
            <p class="text-xs" @click="inAll">全部填入</p>
          </div>
          <button
            class="w-full  h-10 leading-10 text-center text-sm rounded-lg"
            :class="[ btnType === 1 ? 'bg-app-blue-3' : btnType === 2 ? 'bg-yellow-500' : 'bg-app-blue-5', rest === 0 ? 'bg-app-blue-5' : 'bg-app-blue-3' ]"
            @click="vote">{{ voteText }}</button>
          <p v-if="canVote && content.status === 2" class="text-xs mt-2.5 mb-0 text-yellow-600 flex items-center justify-between">
            <span>投票成功后需要支付</span>
            <span>0.002BTY</span>
          </p>
      </div> -->
    </div>
  </child-view>
</template>

<script lang="ts">
import CommunityCard from '@/components/home/CommunityCard.vue'
import childView from '@/layouts/childView.vue'
import AppIcon from '@/components/common/Icon.vue'
import Vue from 'vue'
import { service } from '@/service/index'
import TimeLine from '@/components/home/TimeLine.vue'
import loading from '@/components/loading'
// import { test } from '@/constants/test'
import { Toast } from 'vant'
import { mapState } from 'vuex'

interface DayAccountItem {
  balance: string;
  startHeight: string;
  endHeight: string;
  isToday: boolean;
  used: string;
}

export default Vue.extend({
  components: {
    childView,
    CommunityCard,
    AppIcon,
    TimeLine
  },
  data() {
    return {
      // 区块计时
      showLine: true,
      count: 0,
      isEnd: 0,
      canVote: true,
      content: {} as any,
      voteNum: '',
      rest: 0,
      hide: false,
      selectId: 0,
      voteText: '投票',
      btnType: 1,
      voteClick: true,
    }
  },
  computed: {
    ...mapState({
      address: (state: any) => state.app.address
    })
  },
  methods: {
    // 获取详情数据
    getDetails() {
      loading.showLoading()
      service.voteDetails({
        execer: 'user.p.szhtest.rankvote',
        funcName: 'GetRankVoteInfo',
        payload: {
          voteID: this.$route.query.voteID as string
        }
      }).then(res => {
        this.content = res.result
        this.isEnd = res.result.status
        const isOpen = res.result.isOpen
        const list = res.result.members
        if (this.content.status === 2 && this.content.numType === 1) {
          this.showLine = false
        }
        if (!isOpen) {
          this.canVote = list.some((item: { addr: string }) => item.addr === this.address)
        }
        let HEIGHT = undefined as undefined | number
        if (this.content.status === 1) {
          HEIGHT = +res.result.startHeight
        } else {
          HEIGHT = +res.result.endHeight
        }
        this.setStatus(this.canVote)
        this.getRest(HEIGHT)
        this.$nextTick(() => {
          // 设置高度
          for (let i = 0; i < this.content.voteOptions.length; i++) {
            if ((this.content.voteOptions[i] as any).name.length > 50) {
              this.$set(this.content.voteOptions[i], 'type1', 1)
            } else {
              this.$set(this.content.voteOptions[i], 'type1', 0)
            }
          }
          // 设置底部样式
          const height = window.innerHeight
          const box = document.querySelector('.sub-page') as any
          if (height < box?.scrollHeight) {
            this.hide = true
          } else {
            this.hide = false
          }
        })
      })
    },
    // 获取余票
    getRest(_height: number) {
      service.voteRest({
        execer: 'user.p.szhtest.rankvote',
        funcName: 'GetRankVoteAccountInfo',
        payload: {
          id: this.$route.query.voteID as string,
          addr: this.address
        }
      }).then(res => {
        const lists =  res.result && res.result.dayAccount || [] as DayAccountItem[]
        const filter = lists.filter((item: DayAccountItem) => item.isToday)
        this.rest = +filter[0]?.balance || 0
        const endHeight = +filter[0]?.endHeight || 0
        // 头行显示文本判断, 结束时间 | 下次投票
        if (Math.abs(endHeight - +this.content.endHeight) < 5) {
          this.isEnd = 3
        } else {
          this.isEnd = this.content.status
        }
        this.getHeight(_height, endHeight)
      })
    },
    // 计算顶部条剩余时间
    getHeight(_height: number, endHeight: number) {
      service.getHeight().then(res => {
        loading.hideLoading()
        const height = +res.result.mainHeight
        if (this.canVote) {
          this.voteText = `投票`
        } else {
          this.voteText = '暂无权限'
        }
        if (this.content.status === 1) {
          this.count = Math.abs(_height - height)
        } else {
          this.count = Math.abs(endHeight - height)
        }
      })
    },
    // 设置按钮状态
    setStatus(v: boolean) {
      if (this.content.status === 0 || this.content.status === 1) {
        this.btnType = 3
      }
      if (!v) {
        this.btnType = 3
        this.voteText = '暂无权限'
      }
    },
    // 展开收起
    triggle(i: number, v: number) {
      if (v === 1) {
        this.$set(this.content.voteOptions[i], 'type1', 2)
      } else {
        this.$set(this.content.voteOptions[i], 'type1', 1)
      }
    },
    // 选项
    changeHandle(id: number) {
      if (!this.canVote || !this.voteClick || this.content.status === 1 || this.rest === 0) return
      this.selectId = id
    },
    // 输入检查
    checkInput() {
      if (!parseInt(this.voteNum)) {
        this.voteNum = ''
        return
      }
      const num = parseInt(this.voteNum)
      if (num > this.rest) {
        this.voteText = '余额不足，请去币钱包充值'
        this.btnType = 2
        this.voteClick = false
      } else {
        this.voteText = '投票'
        this.btnType = 1
        this.voteClick = true
      }
      this.voteNum = parseInt(this.voteNum) + ''
    },
    // 全部填入
    inAll() {
      this.voteNum = this.rest + ''
      this.voteText = '投票'
      this.btnType = 1
      this.voteClick = true
    },
    // 投票
    vote() {
      if (!this.canVote || !this.voteClick) return
      if (this.rest === 0) return
      if (!this.voteNum) {
        Toast('请先输入票数')
        return
      }
      if (!this.selectId) {
        Toast('请先选择投票选项')
        return
      }
      // this.$store.commit('app/SET_COMMITTEXT', '提交的投票')
      service.memberVote({
        voteId: ''+ this.$route.query.voteID,
        optionId: ''+this.selectId,
        amount: +this.voteNum
      }, {
        request: { text: '提交的投票' },
        result: { text: '投票' }
      }, () => {
        // this.$store.commit('app/SET_RESULTTEXT', '投票')
        this.$router.push({path: '/Square'})
      })
    }
  },
  mounted() {
    this.getDetails()
  },
})
</script>

<style scoped>
  .type-1 {
    display: -webkit-box;
    overflow: hidden;  
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
  }
  .initial-height {
    max-height: 60px;
  }
</style>