<template>
  <child-view>
    <div ref="box" class="sub-page">
      <div>
        <time-line v-if="showLine" ref="timeline" :status="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 && status === 2, 'pb-20': (hide && status !== 2) || (hide && !canVote)}">
          <div
            v-for="(item, index) in lists"
            :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">
          <input v-show="canVote && status === 2" class="x-input text-sm" type="text" v-model="voteNum" @input="checkInput">
          <div v-if="canVote && 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 && 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 && status === 2" class="x-input text-sm" type="text" v-model="voteNum" @input="checkInput">
          <div v-if="canVote && 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 && 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 { test } from '@/constants/test'
import { Toast } from 'vant'
export default Vue.extend({
  components: {
    childView,
    CommunityCard,
    AppIcon,
    TimeLine
  },
  data() {
    return {
      canVote: true,
      lists: [],
      type1: true,
      voteNum: '',
      rest: 0,
      hide: false,
      selectId: 0,
      voteText: '投票',
      content: {} as any,
      btnType: 1,
      voteClick: true,
      status: 0,     // 按钮状态依据
      height: 0,
      blockTime: '',
      count: 0,
      endHeight: 0,         // 下次投票参数
      end: 0,               // 截至时间
      isEnd: 0,
      showLine: true,
    }
  },
  methods: {
    // 获取详情数据
    getDetails() {
      service.voteDetails({
        execer: 'user.p.szhtest.rankvote',
        funcName: 'GetRankVoteInfo',
        payload: {
          voteID: this.$route.query.voteID as string
        }
      }).then(res => {
        this.content = res.data.result
        this.status = res.data.result.status
        this.isEnd = res.data.result.status
        this.end = res.data.result.endHeight
        this.lists = res.data.result.voteOptions
        const isOpen = res.data.result.isOpen
        const list = res.data.result.members
        if (this.status === 2 && this.content.numType === 1) {
          this.showLine = false
        }
        if (!isOpen) {
          this.canVote = list.some((item: { addr: string }) => item.addr === this.$store.state.app.address)
          // this.canVote = list.some((item: { addr: string }) => item.addr === test.addr)
        }
        // const start = res.data.result.startHeight
        if (this.status === 1) {
          this.height = +res.data.result.startHeight
        } else {
          this.height = +res.data.result.endHeight
        }
        this.setStatus(this.canVote)
        this.getRest()
        this.$nextTick(() => {
          // 设置高度
          for (let i = 0; i < this.lists.length; i++) {
            if ((this.lists[i] as any).name.length > 50) {
              this.$set(this.lists[i], 'type1', 1)
            } else {
              this.$set(this.lists[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() {
      service.voteRest({
        execer: 'user.p.szhtest.rankvote',
        funcName: 'GetRankVoteAccountInfo',
        payload: {
          id: this.$route.query.voteID as string,
          addr: this.$store.state.app.address
          // addr: test.addr
        }
      }).then(res => {
        const lists =  res.data.result && res.data.result.dayAccount || []
        let o = []
        o = lists.filter((item: any) => item.isToday)
        this.rest = +(o as any)[0]?.balance || 0
        this.endHeight = +(o as any)[0]?.endHeight || 0
        // 头行显示文本为结束时间或下次投票
        if (Math.abs(this.endHeight - +this.end) < 5) {
          this.isEnd = 3
        } else {
          this.isEnd = this.status
        }
        // console.log(this.end)
        // console.log(this.endHeight)
        this.getHeight()
      })
    },
    // 计算剩余时间
    getHeight() {
      service.getHeight().then(res => {
        const height = +res.data.result.mainHeight
        if (this.canVote) {
          this.voteText = `投票`
        } else {
          this.voteText = '暂无权限'
        }
        if (this.status === 1) {
          this.count = Math.abs(this.height - height)
        } else {
          this.count = Math.abs(this.endHeight - height)
        }
        
      })
    },
    // 设置按钮状态
    setStatus(v: boolean) {
      if (this.status === 0 || this.status === 1) {
        this.btnType = 3
        // this.voteText = '未开始'
      }
      if (!v) {
        this.btnType = 3
        this.voteText = '暂无权限'
      }
    },
    // 展开收起
    triggle(i: number, v: number) {
      if (v === 1) {
        this.$set(this.lists[i], 'type1', 2)
      } else {
        this.$set(this.lists[i], 'type1', 1)
      }
    },
    // 选项
    changeHandle(i: number) {
      if (!this.canVote || !this.voteClick || this.status === 1 || this.rest === 0) return
      this.selectId = i
    },
    // 输入检查
    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
        // this.voteNum = this.rest + ''
      } 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_TEXT', '提交的投票')
      service.memberVote({
        voteId: ''+ this.$route.query.voteID,
        optionId: ''+this.selectId,
        amount: +this.voteNum
      }, () => {
        this.$store.commit('app/SET_TEXT1', '投票')
        this.$router.push({path: '/Square'})
        // Toast('投票成功')
      })
    }
  },
  mounted() {
    this.hide = false
    this.getDetails()
    // this.getRest()
    // window.onresize = () => {
    //   if (height + 50 < box.scrollHeight) {
    //     this.hide = true
    //   } else {
    //     this.hide = false
    //   }
    // }
  },
  watch: {
    // $route: {
    //   handler(n) {
    //   if (n.path.indexOf('/SquareVote') <= -1) return
    //     this.voteNum = ''
    //     this.selectId = 0
    //     this.getDetails()
    //     this.getRest()
    //   }
    // }
  }
})
</script>

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