<template>
  <div>
    <div class="title text-center text-lg py-10">发起活动</div>
    <div class="scroll-controller">
      <div class=" form-contianer w-11/12 rounded-lg mx-auto border border-app-blue-3">
        <div class="form p-3 text-sm">
          <div class="input py-3">
            <div class="flex justify-between">
                <div class="inpu-title">投票标题</div>
                <div v-show="isExist" class=" text-xs text-app-red">{{ name }}已被占用</div>
            </div>
              <input
                type="text"
                placeholder="请输入投票标题（限10字）"
                class="w-full text-sm py-2 px-3 mt-2 rounded text-app-blue-1"
                maxlength="10"
                v-model="form.name"
                @blur="checkName">
            </div>
            <div class="time-picker py-3">
              <app-calendar
                :blockTime="blockTime"
                :blockHeight="blockHeight"
                :value.sync="form.startHeight" />
                <!-- <div class='flex justify-between'>
                  <div>投票开始时间</div>
                  <div class='flex items-center'>        
                    <span class="mr-2 text-xs">{{dateStart}}</span>        
                    <div @click="showStart = true">
											<app-icon customize type='icon-rili' size='20px'> </app-icon>
										</div>
										<van-calendar
											class="text-black"
											v-model="showStart"
											:default-date="new Date(dateStart)"
											:min-date="minDate"
											:max-date="maxDate"
											:show-confirm="false"
											@select="selectStart" />
                  </div>
                </div>
                <input
                  type="number"
                  :placeholder="'请输入开始区块               当前区块' + blockHeight"
                  class="w-full text-sm py-2 px-3 mt-2 rounded text-app-blue-1"
                  v-model="form.startHeight"
									@blur="getDateStart"> -->
            </div>
            <div class="time-picker py-3">
              <app-calendar
                :blockTime="blockTime"
                :blockHeight="blockHeight"
                :value.sync="form.endHeight"
                title="投票结束时间"
                placeholder="请输入结束区块               当前区块" />
                <!-- <div class='flex justify-between'>
                  <div>投票截止时间</div>
                  <div class='flex items-center'>        
                    <span class="mr-2 text-xs">{{dateEnd}}</span>        
                    <div @click="showEnd = true">
											<app-icon customize type='icon-rili' size='20px'> </app-icon>
										</div>
										<van-calendar
											class="text-black"
											v-model="showEnd"
											:default-date="new Date(dateEnd)"
											:min-date="minDate"
											:max-date="maxDate"
											:show-confirm="false"
											@select="selectEnd" />
                  </div>
                </div>
                <input
                  type="number"
                  :placeholder="'请输入结束区块               当前区块' + blockHeight"
                  class="w-full text-sm py-2 px-3 mt-2 rounded text-app-blue-1"
                  v-model="form.endHeight"
									@blur="getDateEnd"> -->
            </div>
            <div class="cell flex justify-between items-center border-b py-2 border-app-dark-4 ">
              <div>每人参与次数设置</div>
              <div class="flex items-center cursor-pointer" @click="pickToggle">
                <div class=" text-xs">
                  {{ times }}
                </div>
                    <app-icon customize type='icon-arrow-right-copy-copy'></app-icon>
                 </div>
            </div>

            <div class="cell flex justify-between items-center py-2 ">
              <div>是否公开投票</div>
              <van-switch v-model="checked" size="18px"/>
            </div>
            <!-- <div class="space h-11"></div> -->
						<!-- <div v-show="!checked" class="cell flex justify-between items-center py-2 ">
            <div>成员数设置</div>
            <div class="flex items-center cursor-pointer" @click="setPerson">
              <div class=" text-xs opacity-60">
                {{ num }}人
              </div>
                  <app-icon customize type='icon-arrow-right-copy-copy'></app-icon>
                </div>
						</div> -->
						<div class="space h-11"></div>
        </div>
      </div>
      <van-action-sheet v-model="show" description="每人参与次数">
        <div
          v-for="item in actions"
          :key="item.name"
          class="w-full h-12 flex items-center justify-center text-white text-sm"
          :style="{background: times === item.name ? '#3832AC' : '#1c1485'}"
          @click="onSelect(item)">
          {{ item.name }}
        </div>
      </van-action-sheet>
      <div class="w-11/12 mx-auto mt-5" @click="submit">
        <app-btn text='发起活动' size="full" border='border-none' class=" bg-app-blue-3 rounded py-3"></app-btn>
      </div>
    </div>
      
  </div>
</template>

<script lang="ts">
// import DatePick from 'vue-date-pick';
import Vue from "vue";
// import 'vue-date-pick/dist/vueDatePick.css';
import { Switch, ActionSheet, Toast, Calendar } from 'vant';
import { service } from '@/service/index'
import { getPreDay } from '@/utils/date'
Vue.use(Switch);
Vue.use(ActionSheet);
Vue.use(Toast)
Vue.use(Calendar)
export default Vue.extend({
  name: 'Founder',
  components:{
    // DatePick,
    "app-icon":()=>import('@/components/common/Icon.vue'),
    "app-btn":()=>import('@/components/common/Btn.vue'),
    'app-calendar': () => import('@/components/common/Calendar.vue')
  },
  data() {
    return {
      dateStart: getPreDay('YYYY-MM-DD'),
      dateEnd: getPreDay('YYYY-MM-DD'),
			checked:true,
			form: {
				name: '',  // 测试
				startHeight: '',
				endHeight: '',
				type: 2
			},
			actions: [
				{ name: '每天一次', id: 2 },
				{ name: '仅一次', id: 1 }
			],
			show: false,
			times: '每天一次',
			showStart: false,
			showEnd: false,
			blockHeight: '',
			blockTime: '',
      minDate: new Date(2019, 0, 1),
      maxDate: new Date(2023, 0, 1),
			length: 100,                          // 输入框与当前区块差值,当前1天高度86400/5
			num: 0,
      isExist: false,
      name: ''
    };
  },
  methods:{
    checkName() {
      if (!this.form.name) return
      service.checkName(this.form.name).then(res => {
        if (res.data.result) {
          this.isExist = false
        } else {
          this.name = this.form.name
          this.isExist = true
        }
      })
    },
		init() {
			this.form = {
				name: '',
				startHeight: '',
				endHeight: '',
				type: 2
			}
			this.dateStart = getPreDay('YYYY-MM-DD')
      this.dateEnd = getPreDay('YYYY-MM-DD')
		},
		getBlockHeight() {
      service.getHeight().then(res => {
        // console.log(res)
        this.blockHeight = res.data.result.mainHeight
        this.blockTime = res.data.result.mainBlockTime
      })
    },
    pickToggle(){
      this.show = true
    },
    onSelect(v: object) {
      this.times = (v as any).name
      this.show = false
    },
    submit() {
      if (!this.form.name || !this.form.startHeight || !this.form.endHeight) {
        Toast('请先填写表单内容')
        return
      }
      if (this.isExist) {
        Toast('请确认表单名称正确')
        return
      }
      const params = JSON.parse(JSON.stringify(this.form))
      params.numType = this.times === '每天一次' ? 2 : 1
      params.isOpen = this.checked
      params.startHeight = parseInt(params.startHeight)
      params.endHeight = parseInt(params.endHeight)
      this.$store.commit('app/SET_TEXT', '发起的提案')
      service.createVote(params).then(() => {
        this.$store.commit('app/SET_TEXT1', '提案')
      })
    },
    setPerson() {
      this.$router.push('/Initiate/Member')
    },
    getDateEnd() {
      if (!this.form.endHeight) return
      let stamp = 0
      const r = +this.form.endHeight - +this.blockHeight
      stamp = +(this.blockTime + '000') + r * 5000
      const hour =  new Date(stamp).getHours()
      const n = hour === 23 ? 1 : 0
      this.dateEnd = new Date(stamp).getFullYear() + '-' + 
          (new Date(stamp).getMonth() + 1 < 10 ? '0' + (new Date(stamp).getMonth() + 1) : new Date(stamp).getMonth() + 1) + '-' + 
          (new Date(stamp).getDate() < 10 ? '0' + (new Date(stamp).getDate()+n) : new Date(stamp).getDate()+n)
    },
    getDateStart() {
      if (!this.form.startHeight) return
      let stamp = 0
      const r = +this.form.startHeight - +this.blockHeight
      stamp = +(this.blockTime + '000') + r * 5000
      const hour =  new Date(stamp).getHours()
      const n = hour === 23 ? 1 : 0
      this.dateStart = new Date(stamp).getFullYear() + '-' + 
          (new Date(stamp).getMonth() + 1 < 10 ? '0' + (new Date(stamp).getMonth() + 1) : new Date(stamp).getMonth() + 1) + '-' + 
          (new Date(stamp).getDate() < 10 ? '0' + (new Date(stamp).getDate() + n) : new Date(stamp).getDate() + n)
    },
    selectStart(v: Date) {
      const r = new Date(v).getFullYear() + '-' + 
          (new Date(v).getMonth() + 1 < 10 ? '0' + (new Date(v).getMonth() + 1) : new Date(v).getMonth() + 1) + '-' + 
          (new Date(v).getDate() < 10 ? '0' + (new Date(v).getDate()) : new Date(v).getDate())
      this.dateStart = r
      this.showStart = false
      const t = new Date(v).getTime()
      const ra = t - +(this.blockTime + '000')
      this.form.startHeight = Math.round(+this.blockHeight + ra/5000) + ''
    },
    selectEnd(v: Date) {
      const r = new Date(v).getFullYear() + '-' + 
          (new Date(v).getMonth() + 1 < 10 ? '0' + (new Date(v).getMonth() + 1) : new Date(v).getMonth() + 1) + '-' + 
          (new Date(v).getDate() < 10 ? '0' + (new Date(v).getDate()) : new Date(v).getDate())
      this.dateEnd = r
      this.showEnd = false
      const t = new Date(v).getTime()
      const ra = t - +(this.blockTime + '000')
      this.form.endHeight = Math.round(+this.blockHeight + ra/5000) + ''
    }
  },
	mounted() {
		this.getBlockHeight()
    this.num = this.$store.state.app.members?.length
	},
	watch: {
		$route: {
      immediate: true,
      handler(n, o) {
        // if (n?.path !== '/Initiate' || n?.path.indexOf('MyInitiate') <= -1) return
        if (n?.path !== '/Initiate') return
        if (o?.path !== '/Initiate/Member') {
          this.checked = true
          this.init()
          this.getBlockHeight()
          this.$store.commit('app/CLEAR_MEMBER')
        }
        this.num = this.$store.state.app.members?.length
      }
    },
	}

});
</script>
<style scoped>
input::placeholder{
  font-size: 0.75rem;
}
.scroll-controller {
    height: calc(100vh - 160px);
    overflow-y: scroll;
}
>>> .van-action-sheet__item, >>> .van-action-sheet__description {
  background: #1c1485;
  color: #fff;
}
>>> .van-action-sheet__description::after {
  border: none;
}
</style>