<template>
  <div>
    <div v-if="showTitle" class="title text-center text-lg py-6">发起提案</div>
    <div class="scroll-controller" :style="{ height: !showTitle? 'calc(100vh - 90px)' : ''}">
    <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="input py-3">
            <div class="flex justify-between">
                <div class="inpu-title">补充描述（可选）</div>
            </div>
              <textarea
                type="text"
                placeholder="这里写项目描述简介（限500字）"
                maxlength="500"
                rows="2"
                cols="50"
                class="w-full text-sm py-2 px-3 mt-2 rounded text-app-blue-1"
                v-model="form.description" />
          </div>
          <div class="input py-3">
            <div class="flex justify-between">
                <div class="inpu-title">项目详情链接（可选）</div>
            </div>
              <input
                type="text"
                placeholder="请输入项目详情链接"
                class="w-full text-sm app py-2 px-3 mt-2 rounded text-app-blue-1"
                v-model="form.url">
          </div>
          <app-option ref="optionEl" key="option" @getVal="getVal" :options="options"></app-option>
          <div class="space py-2"></div>
      </div>
    </div>
      <div class="form-contianer w-11/12 mt-3 rounded-lg mx-auto border border-app-blue-3">
      <div class="form p-3 text-sm">
          <div class="time-picker py-3">
            <app-calendar
              :blockTime="blockTime"
              :blockHeight="blockHeight"
              :value.sync="form.startHeight" />
          </div>
          <div class="time-picker py-3">
            <app-calendar
              :blockTime="blockTime"
              :blockHeight="blockHeight"
              :value.sync="form.endHeight"
              title="投票结束时间"
              placeholder="请输入结束区块               当前区块" />
          </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 opacity-60">
                {{ times }}
              </div>
                <app-icon customize type='icon-arrow-right-copy-copy'></app-icon>
              </div>
          </div>
          <div class="cell flex justify-between items-center border-b py-2 border-app-dark-4 ">
            <div>是否公开投票</div>
            <van-switch v-model="checked" size="18px"/>
          </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>
    <div class="w-11/12 mx-auto mt-5">
      <app-btn text='发起提案' size="full" border='border-none' class=" bg-app-blue-3 rounded py-3" @btnClicked="checkSomething"></app-btn>
    </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>
</template>

<script lang="ts">

import Vue from "vue";
import 'vue-date-pick/dist/vueDatePick.css';
import { Switch, Dialog, ActionSheet, Toast } from 'vant';
import { service } from '@/service/index'
Vue.use(Switch);
Vue.use(ActionSheet);
export default Vue.extend({
  name: 'userInitiate',
  props: {
    showTitle: {
      type: Boolean,
      default: true
    },
    formContent: {
      type: Object
    }
  },
  data() {
    return {
      // 验重
      isExist: false,
      name: '',
      checked:true,
      times: '每天一次',
      blockHeight: '',
      blockTime: '',
      length: 100,                          // 输入框与当前区块差值,当前1天高度86400/5
      actions: [
        { name: '每天一次' },
        { name: '仅一次' }
      ],
      show: false,
      form: {
        name: '',
        description: '',
        url: '',
        type: 1,
        startHeight: '',
        endHeight: '',
        options: [] as any,
        members: [] as any
      },
      num: 0,
      options: [] as any,
      isOptionValid: true
    };
  },
  components:{
    "app-btn":()=>import('@/components/common/Btn.vue'),
    'app-icon':()=>import('@/components/common/Icon.vue'),
    'app-option':()=>import('@/components/common/Option.vue'),
    'app-calendar': () => import('@/components/common/Calendar.vue')
  },
  methods:{
    init() {
      this.form = {
        name: '',
        description: '',
        url: '',
        type: 1,
        startHeight: '',
        endHeight: '',
        options: ['', ''],
        members: []
      }
      this.options = ['', '']
    },
    getBlockHeight() {
      service.getHeight().then(res => {
        this.blockHeight = res.data.result.mainHeight
        this.blockTime = res.data.result.mainBlockTime
      })
    },
    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
        }
      })
    },
    checkSomething() {
      // 检测合理性
      if (!this.isOptionValid) {
        Toast('选项内容有误，请确认选项内容')
        return
      }
      if (this.isExist || !this.form.name) {
        Toast('项目名称有误，请重新输入')
        return
      }
      if (+this.form.startHeight < +this.blockHeight + this.length) {
        Toast('起始高度不得小于主链高度+'+ this.length + '的高度')
        return
      }
      if (+this.form.startHeight > +this.form.endHeight) {
        Toast('结束高度不得小于起始高度')
        return
      }
      Dialog.confirm({
        title: '提示',
        message: '提案项目发起后不可修改，并将扣除 0.002 BTY作为燃料费,是否确认发起投票？',
      }).then(() => {
        this.submit()
      }).catch(() => {
        // on cancel
      });
    },
    setPerson() {
      if (this.$route.path === '/Mine/MyInitiate') {
        this.form.options = this.options
      }
      this.$store.commit('app/SET_FORM', this.form)
      console.log(this.form)
      this.$router.push('/Initiate/Member')
    },
    pickToggle(){
      this.show = true
    },
    onSelect(v: object) {
      this.times = (v as any).name
      this.show = false
    },
    checkOptionValid(v: any[]) {
      const set = new Set(v)
      if (set.size !== v.length || v.includes('')) {
        this.isOptionValid = false
      } else {
        this.isOptionValid = true
      }
    },
    getVal(v: any[]) {
      this.form.options = []
      for (const item of v) {
        this.form.options.push({name: item})
      }
      this.options = this.form.options
      this.checkOptionValid(v)
      console.log(this.options)
    },
    submit() {
      this.$store.commit('app/SET_TEXT', '发起的提案')
      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)
      if (!params.isOpen) {
        params.members = this.$store.state.app.members
      }
      console.log(params)
      service.createVote(params, () => {
        this.$store.commit('app/SET_TEXT1', '提案')
        this.$store.commit('app/CLEAR_MEMBER')
        this.$store.commit('app/CLEAR_FORM')
        this.$router.replace({path: '/Square', query: { t: Date.now() + '' }})
      })
    },
  },
  watch: {
    $route: {
      immediate: true,
      handler(n, o) {
        if (n?.path !== '/Initiate') return
        if (o?.path !== '/Initiate/Member' && o?.path !== '/Initiate') {
          this.checked = true
          this.init()
          this.getBlockHeight()
          this.$store.commit('app/CLEAR_MEMBER')
        }
        this.num = this.$store.state.app.members?.length
        if (Object.keys(this.$store.state.app.form).length > 0) {
           this.form = this.$store.state.app.form
        }
      }
    },
    formContent(n) {
      // 重新发起时的数据渲染
      const status = Object.keys(this.$store.state.app.form)
      if (status.length > 0) {
        // 人员编辑完成
        this.checked = false
        this.form = this.$store.state.app.form
        this.options = this.form.options
        // service.getHeight().then(res => {
        //   this.blockHeight = res.data.result.mainHeight
        //   this.blockTime = res.data.result.mainBlockTime
        //   this.getDateStart()
        //   this.getDateEnd()
        // })
      } else {
        // 初始进入重新发起
        this.form = n
        this.checked = (this.form as any).isOpen
        this.$store.commit('app/SET_MEMBER', n.members)
        this.options = (this.form as any).voteOptions
        this.form.options = this.options
        delete (this.form as any).voteOptions
        this.num = this.$store.state.app.members?.length
        // service.getHeight().then(res => {
        //   this.blockHeight = res.data.result.mainHeight
        //   this.blockTime = res.data.result.mainBlockTime
        //   this.getDateStart()
        //   this.getDateEnd()
        // })
      }
      // 检测名称是否重复
      this.checkName()
    },
  },
  mounted() {
    console.log(this.form)
    this.num = this.$store.state.app.members.length
    this.getBlockHeight()
  },
});
</script>
<style scoped>
.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>