<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="form.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="show = true">
              <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="form.isOpen" size="18px" />
          </div>
          <div
            v-show="!form.isOpen"
            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">{{ form.members.length }}人</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="handleClickSubmit"
        ></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";
import { CreateVoteDto, MemberItem, ListItem } from "@/types/Dto";
import { TICKET_COUNT } from "@/utils/config";
import { mapState } from "vuex";
Vue.use(Switch);
Vue.use(ActionSheet);

const baseForm = (): CreateVoteDto => {
  return {
    name: "",
    description: "",
    url: "",
    type: 1,
    startHeight: undefined,
    endHeight: undefined,
    options: [] as ListItem[],
    members: [] as MemberItem[],
    isOpen: true,
    numType: 2,
  };
};

export default Vue.extend({
  name: "userInitiate",
  props: {
    showTitle: {
      type: Boolean,
      default: true,
    },
    formContent: {
      type: Object as any
    }
  },
  data() {
    return {
      // 验重
      form: baseForm(),
      isExist: false,
      name: "",
      blockHeight: "",
      blockTime: "",
      length: TICKET_COUNT, // 输入框与当前区块差值,当前1天高度86400/5
      actions: [{ name: "每天一次" }, { name: "仅一次" }],
      times: "每天一次",
      show: false,
      disabled: false,
    };
  },
  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"),
  },
  computed: {
    ...mapState({
      storeForm: (state: any) => state.app.form,
    }),
  },
  mounted() {
    this.form = this.storeForm;
    console.log(this.form)
    this.getBlockHeight();
  },
  activated() {
    this.form = this.storeForm;
  },
  watch: {
    $route(n) {
      if (n.path !== "/Initiate/Member" || n.path !== '/Mine/MyInitiate') {
        this.$store.commit("app/CLEAR_FORM");
      }
    },
    formContent: {
      deep: true,
      handler(n) {
        this.form = n
      }
    }
  },
  methods: {
    getBlockHeight() {
      service.getHeight().then((res) => {
        this.blockHeight = res.result.mainHeight;
        this.blockTime = res.result.mainBlockTime;
      });
    },
    checkName() {
      if (!this.form.name) return;
      service.checkName(this.form.name).then((res) => {
        if (res.result) {
          this.isExist = false;
        } else {
          this.name = this.form.name;
          this.isExist = true;
          this.disabled = true;
        }
      });
    },
    isValid() {
      // 检测合理性
      return new Promise((resolve) => {
        if (this.isExist || !this.form.name) {
          Toast("项目名称有误，请重新输入");
          this.disabled = true;
        } else if (!this.form.startHeight || !this.form.endHeight) {
          Toast("请选择起止时间");
          this.disabled = true;
        } else if (!this.checkOptionValid(this.form.options as ListItem[])) {
          Toast("选项管理内容不得少于2个");
          this.disabled = true;
        } else if (
          (this.form.startHeight as number) <
          +this.blockHeight + this.length
        ) {
          Toast("起始高度不得小于主链高度+" + this.length + "的高度");
          this.disabled = true;
        } else if (
          (this.form.startHeight as number) > (this.form.endHeight as number)
        ) {
          Toast("结束高度不得小于起始高度");
          this.disabled = true;
        } else {
          this.disabled = false;
        }
        if (!this.disabled) {
          resolve(true);
        }
      });
    },
    handleClickSubmit() {
      this.isValid().then((res) => {
        if (res) {
          Dialog.confirm({
            title: "提示",
            message:
              "提案项目发起后不可修改，并将扣除 0.002 BTY作为燃料费,是否确认发起投票？",
          })
            .then(() => {
              this.submit();
            })
        }
      });
    },
    setPerson() {
      this.$router.push("/Initiate/Member");
    },
    onSelect(item: { id: number; name: string }) {
      this.times = item.name;
      this.show = false;
      this.form.numType = item.id;
    },
    checkOptionValid(v: any[]) {
      if (v.length < 2) {
        return false;
      }
      const set = new Set(v);
      if (set.size !== v.length || v.some((item) => !item.name)) {
        this.disabled = false;
        return false;
      } else {
        this.disabled = false;
        return true;
      }
    },
    getVal(v: any[]) {
      this.form.options = [];
      for (const item of v) {
        this.form.options.push(item);
      }
      this.checkOptionValid(v);
    },
    submit() {
      // this.$store.commit("app/SET_COMMITTEXT", "发起的提案");
      console.log(this.form);
      const params = JSON.parse(JSON.stringify(this.form));
      params.startHeight = parseInt(params.startHeight);
      params.endHeight = parseInt(params.endHeight);
      service.createVote(params, {
        request: { text: '发起的提案' },
        result: { text: '提案' }
      }, () => {
        // this.$store.commit("app/SET_RESULTTEXT", "提案");
        this.$store.commit("app/CLEAR_FORM");
        this.$router.replace({ path: "/Square" });
      });
    },
  },
});
</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>