<template>
  <div ref="votePage" class="voteBg" @scroll="scroll">
    <img src="../../assets/image/top.png" />
    <div ref="vote" class="vote" v-if="appNameList.length">
      <van-checkbox-group v-model="checkboxGroup" :max="config.VOTE_MAX">
        <van-cell-group>
          <van-cell
            :label="voteLabel(item)"
            v-for="item in appNameList"
            :key="item.infoId"
            size="large"
          >
            <template #title>
              <van-checkbox
                :disabled="disable"
                checked-color="#e42417"
                icon-size="16px"
                :name="item.infoId"
              >
                {{ item.appName }}
              </van-checkbox>
            </template>
            <template #default v-if="item.appDesc">
              <van-icon
                position="bottom"
                @click="() => showPop(item)"
                name="question-o"
              />
            </template>
          </van-cell>
        </van-cell-group>
      </van-checkbox-group>
      <div class="bottom" v-if="!disable">
        <!-- <div class="bottom"> -->
        <van-button type="danger" color="#e42417" @click="submit" block>
          提 交
        </van-button>
      </div>
      <van-popup
        v-model="show"
        closeable
        round
        @close="closePop"
        position="bottom"
        :style="{ height: '80%' }"
      >
        <div class="introduction">
          <div class="head van-hairline--bottom">创意说明</div>
          <div class="body" v-text="doc"></div>
        </div>
      </van-popup>
    </div>
  </div>
</template>

<script>
import {
  Button as vanButton,
  Popup as vanPopup,
  Icon as vanIcon,
  Cell as vanCell,
  CellGroup as vanCellGroup,
  Checkbox as vanCheckbox,
  CheckboxGroup as vanCheckboxGroup,
  // Progress as vanProgress,
  Dialog,
  Toast
} from "vant";
import "vant/lib/field/style";
import "vant/lib/dialog/style";
import "vant/lib/toast/style";
import "vant/lib/checkbox/style";
import "vant/lib/button/style";
import "vant/lib/progress/style";
import "vant/lib/checkbox-group/style";

import { voteList, saveVote, isVote } from "@/api/vote/vote.js";
import { sysConfig } from "@/api/user/user.js";

import { isIphone, isAndroid } from "@/utils/isTerminal.js";
import { setToken } from "@/utils/common.js";

let data = {
  size: 50,
  total: 0
};
let getload = true;
export default {
  name: "app",
  data: function() {
    return {
      checkboxGroup: [],
      appNameList: [],
      show: false,
      doc: "",
      appName: "",
      config: {},
      disable: false
    };
  },
  methods: {
    voteLabel(item) {
      if (!this.disable) return;
      return "票数：" + item.vote;
    },
    refresh() {
      data = {
        size: 50,
        total: 0
      };
      this.appNameList = [];
      this.addList();
    },
    addList() {
      if (!getload) return;
      getload = false;
      let load = Toast.loading({
        message: "加载中...",
        duration: 0,
        forbidClick: false
      });
      voteList("size=" + data.size + "&total=" + data.total)
        .then(res => {
          this.appNameList.push(...(res || []));
          data.total = this.appNameList.length;
          this.$nextTick(() => {
            res.length && (getload = true);
            load.clear();
          });
        })
        .catch(() => {
          load.clear();
        });
    },
    showPop(item) {
      if (!item.appDesc) return;
      this.show = true;
      this.doc = item.appDesc;
      this.appName = item.appName;
    },
    closePop() {
      this.doc = "";
      this.appName = "";
    },
    scroll() {
      let a = this.$refs.votePage.scrollHeight;
      let b = this.$refs.votePage.clientHeight;
      let c = this.$refs.votePage.scrollTop;
      if (b + c + 20 < a) return;
      this.addList();
    },
    submit() {
      if (!this.$user.accessToken) {
        if (isAndroid) window.H5Listener.doLogin();
        if (isIphone) window.webkit.messageHandlers.doLogin.postMessage("");
        return;
      }
      Dialog.confirm({
        title: "提交投票",
        message: "结果提交后将无法修改，请确认是否提交？"
      })
        .then(() => {
          if (!this.checkboxGroup.length)
            return Toast({
              message: "请选择",
              position: "bottom"
            });
          let r = [];
          for (let i = 0; i < this.checkboxGroup.length; i++) {
            let v = this.appNameList.find(v => {
              return v.infoId === this.checkboxGroup[i];
            });
            r.push({
              infoId: v.infoId,
              view: ""
            });
          }

          let load = Toast.loading({
            message: "加载中...",
            duration: 0,
            forbidClick: false
          });
          saveVote({ source: "智慧融媒", items: r })
            .then(() => {
              this.disable = true;
              load.clear();
              Toast({
                message: "投票成功",
                position: "bottom"
              });
              this.refresh();
            })
            .catch(() => {
              load.clear();
            });
          return false;
        })
        .catch(err => {
          console.error(err);
        });
    }
  },
  mounted() {
    window.voteNext = () => {
      var payload = {
        type: "JSbridge",
        functionName: "getUserInfo",
        arguments: {}
      };
      if (isIphone) this.$user = window.prompt(JSON.stringify(payload)) || {};
      if (isAndroid && window.H5Listener)
        this.$user = window.H5Listener.getUserInfo() || {};
      this.$user = JSON.parse(this.$user);
      if (this.$user) setToken(this.$user.accessToken);
      else setToken("");
      this.$user.accessToken &&
        isVote().then(res => {
          this.disable = (res || []).length !== 0;
          this.checkboxGroup = (res || []).map(v => v.infoId);
          console.log(res);
          this.addList();
        });
      if (!this.$user.accessToken) {
        this.addList();
      }
    };
    window.voteNext();
    let height = document.body.offsetHeight || 0;
    let width = document.body.offsetWidth || 0;
    this.$refs.vote.style.minHeight = height - (856 / 1500) * width - 44 + "px";

    sysConfig().then(r => {
      this.config = r || {};
    });
  },
  beforeDestroy: function() {},
  components: {
    vanPopup,
    vanIcon,
    vanCell,
    vanButton,
    vanCheckbox,
    vanCellGroup,
    vanCheckboxGroup
  }
};
</script>
<style lang="scss">
$themeColor: #e6837c;

.voteBg {
  // background-image: url("../../assets/image/main.jpg");
  // background-repeat: no-repeat;
  // background-size: 100% 100%;
  height: 100%;
  font-size: 0;
  overflow-y: scroll;

  .vote {
    padding: 1em 1em 46px 1em;
    width: calc(100% - 20px);
    border-radius: 10px;
    margin: 0 auto;

    .van-cell__title {
      flex: 2;
    }

    .introduction {
      font-size: 14px;

      .head {
        height: 54px;
        line-height: 54px;
        text-align: center;
        font-size: 16px;
      }

      .body {
        line-height: 30px;
        text-indent: 2em;
        padding: 1em;
      }
    }

    .bottom {
      position: fixed;
      width: 100%;
      left: 0%;
      padding: 1em 0;
      bottom: 0;
      background-image: linear-gradient(
        0deg,
        rgba(170, 170, 170, 0.8) 5%,
        rgba(0, 0, 0, 0)
      );
    }

    .van-cell {
      background-color: rgba(255, 255, 255, 0.5);
    }

    .van-checkbox__icon--checked {
      background: #fff;

      .van-icon-success {
        background: $themeColor;
        border-color: $themeColor;
      }
    }

    .van-checkbox__label--disabled {
      color: #323233;
    }
  }
}
</style>
