<template>
  <div class="SilkRoadShanShiPinList">
    <img src="../../assets/img/siluchunwanlist.jpg" style="width: 100%" />
    <div class="guize" @click="showGuize">投票规则</div>
    <div class="guize" style="top: 4em" @click="paiming">查看排名</div>
    <van-cell-group style="padding: 8px">
      <template #title>
        <img
          src="../../assets/img/team.png"
          style="width: calc(100vw - 32px)"
        />
      </template>
      <van-row gutter="8">
        <van-col span="12" v-for="item in list" :key="item.id">
          <van-image
            :width="width"
            :height="height"
            fit="cover"
            @click="() => clickShowVideo(item)"
            position="left"
            :src="
              item.file + '?x-oss-process=video/snapshot,t_4000,f_jpg,m_fast'
            "
          />
          <van-row>
            <van-col span="24" style="text-align: center">{{
              item.name
            }}</van-col>
            <van-col span="24">
              <div class="btn" @click="() => toupiao(item)">
                <img src="../../assets/img/btn.png" />
              </div>
            </van-col>
          </van-row>
          <br />
        </van-col>
      </van-row>
    </van-cell-group>
    <van-cell-group style="padding: 8px">
      <template #title>
        <img
          src="../../assets/img/slef.png"
          style="width: calc(100vw - 32px)"
        />
      </template>
      <van-row gutter="8">
        <van-col span="12" v-for="item in listSelf" :key="item.id">
          <van-image
            :width="width"
            :height="height"
            @click="() => clickShowVideo(item)"
            fit="cover"
            position="left"
            :src="
              item.file + '?x-oss-process=video/snapshot,t_4000,f_jpg,m_fast'
            "
          />
          <van-row>
            <van-col span="24" style="text-align: center">{{
              item.name
            }}</van-col>
            <van-col span="24">
              <div class="btn" @click="() => toupiao(item)">
                <img src="../../assets/img/btn.png" />
              </div>
            </van-col>
          </van-row>
          <br />
        </van-col>
      </van-row>
    </van-cell-group>
    <Shanshipin v-if="!config.isShanShiPin" />
    <van-dialog v-model:show="showPaihang" confirm-button-text="关闭">
      <div style="height: 50vh">
        <van-tabs color="#ff2c2c">
          <van-tab title="个人">
            <div class="SilkList">
              <van-cell-group inset>
                <van-cell title="名称" value="投票量"></van-cell>
                <van-row v-for="item in rankListSelf" :key="item.id + 'self'">
                  <van-col span="16"
                    ><p class="text" v-text="item.name"></p
                  ></van-col>
                  <van-col span="8"
                    ><p
                      class="text"
                      style="text-align: right"
                      v-text="formmate(item.votes)"
                    ></p
                  ></van-col>
                </van-row>
              </van-cell-group>
            </div>
          </van-tab>
          <van-tab title="团队">
            <div class="SilkList">
              <van-cell-group inset>
                <van-cell title="名称" value="投票量"></van-cell>
                <van-row v-for="item in rankList" :key="item.id + 'team'">
                  <van-col span="16"
                    ><p class="text" v-text="item.name"></p
                  ></van-col>
                  <van-col span="8"
                    ><p
                      class="text"
                      style="text-align: right"
                      v-text="formmate(item.votes)"
                    ></p
                  ></van-col>
                </van-row>
              </van-cell-group>
            </div>
          </van-tab>
        </van-tabs>
      </div>
    </van-dialog>
    <van-overlay z-index="20" :show="showVideo" @click="showVideo = false">
      <van-icon
        @click="() => clickShowVideo()"
        size="25"
        name="close"
        class="close"
      />
      <div class="video" v-if="showVideo" @click.stop>
        <div class="videoText" v-text="video.introduction"></div>
      </div>
    </van-overlay>
    <video
      v-show="showVideo"
      loop
      x5-video-player-type="h5"
      preload="metadata"
      autoplay
      playsinline="true"
      webkit-playsinline="true"
      x-webkit-airplay="true"
      x5-video-orientation="portraint"
      x5-video-player-fullscreen="true"
      :src="video.file || ''"
      class="videoEle"
    ></video>
    <van-dialog
      theme="round-button"
      v-model:show="showLogin"
      confirm-button-text="登录"
      :before-close="beforeClose"
    >
      <van-cell-group inset>
        <van-field
          v-model="login.name"
          required
          label="姓名"
          placeholder="请输入姓名"
        />
        <van-field
          v-model="login.phone"
          required
          type="tel"
          label="手机号"
          placeholder="请输入手机号"
        >
          <template #button>
            <van-button
              v-if="codePhoen === 0"
              @click="getCode"
              size="small"
              type="primary"
            >
              发送验证码
            </van-button>
            <van-count-down format="ss 秒" v-else :time="codePhoen" />
          </template>
        </van-field>
        <van-field required v-model="login.code" type="digit" label="验证码" />
      </van-cell-group>
    </van-dialog>
  </div>
</template>
<script setup>
import { ref, reactive } from "vue";
import { showDialog, showConfirmDialog, showToast } from "vant";
// import { onMounted, reactive } from "vue";
// import { isIpad, isIpod, isIphone } from "../../utils/isTerminal";
import {
  getEnrollList,
  getEnrollRank,
  getVote,
  getTimes,
  getSendVerifyCode,
  verifyCode,
} from "@/api/SilkRoadSpringGala.js";

import Shanshipin from "@/components/shanshipin.vue";
/**
 * window.$originData.orginParames.title 页面标题
 * window.$originData.orginParames.parameters 固定参数值
 * window.$originData.urlParames url参数
 */
const getList = call => {
  Promise.all([
    getEnrollList({
      type: "团队",
      operateId: 2,
    }),
    getEnrollList({
      type: "个人",
      operateId: 2,
    }),
  ]).then(resList => {
    list.value = resList[0] || [];
    listSelf.value = resList[1] || [];
    call && call();
  });
};

const getRankList = Call => {
  Promise.all([
    getEnrollRank({
      type: "团队",
      operateId: 2,
    }),
    getEnrollRank({
      type: "个人",
      operateId: 2,
    }),
  ]).then(resList => {
    rankList.value = resList[0] || [];
    rankListSelf.value = resList[1] || [];
    Call && Call();
  });
};
const w = window.$originData.orginParames.availWidth || 0;
const width = ref((w - 16) / 2);
const height = ref(width.value * 0.57);
const showPaihang = ref(false);
const showLogin = ref(false);
const list = ref([]);
const listSelf = ref([]);
const rankList = ref([]);
const rankListSelf = ref([]);
const showVideo = ref(false);
const video = ref({});
const codePhoen = ref(0);
const config = reactive({
  times: -1,
  isShanShiPin: window.$shanshipin.UserId,
});
const t = config.isShanShiPin ? 5 : 1;
const login = reactive({
  name: localStorage.getItem("SilkRoadShanShiPinName") || "",
  phone:
    window.$shanshipin.Phone ||
    localStorage.getItem("SilkRoadShanShiPinPhone") ||
    "",
  code: "",
});

getList();

const getCode = () => {
  // 获取验证码
  if (!/1[0-9]{10}/.test(login.phone)) {
    showToast("请输入正确的手机号");
    return;
  }

  getSendVerifyCode({
    phone: login.phone,
  }).then(() => {
    codePhoen.value = 60000;
  });
};

const toupiao = function (item) {
  if (!login.phone || login.phone.length < 11) return (showLogin.value = true); //如果没有手机号提示登录
  showConfirmDialog({
    message: "确定投票给" + item.name + "么？",
    beforeClose: type => {
      console.log(type);
      if (type !== "confirm") return true;
      return new Promise(resolve => {
        getVote({
          target: item.phone,
          source: login.phone,
          client: config.isShanShiPin ? "闪视频" : "其他",
          operateId: 2,
        })
          .then(r => {
            console.log("----------->", r);
            showToast("投票成功！");
            resolve(true);
          })
          .catch(() => {
            console.log("----------->");
            resolve(true);
          });
      });
    },
  });
};

const beforeClose = () => {
  if (!login.phone || !login.name || !login.code) return false;

  getTimes({
    phone: login.phone,
  }).then(r => {
    config.times = r.times - t >= 0;
    verifyCode({
      phone: login.phone,
      code: login.code,
    })
      .then(() => {
        localStorage.setItem("SilkRoadShanShiPinPhone", login.phone);
        localStorage.setItem("SilkRoadShanShiPinName", login.name);
        return true;
      })
      .catch(() => false);
  });
  return true;
};

const showGuize = () => {
  showDialog({
    title: "投票规则",
    messageAlign: "left",
    confirmButtonText: "关闭",
    message: () => (
      <div class="art">
        <p>
          1、投票主题：“大美中国·多彩丝路”《2023丝路嘉年华·丝路春晚》之我要上丝路春晚。
        </p>
        <p>2、投票时间：2022年12月23日12:00至12月26日12:00（共3天）。</p>
        <p>
          3、投票范围：凡创作内容符合节目要求，且通过线上报名和导演组第一轮海选的团体、个人。
        </p>
        <p>
          4、投票形式：通过微信H5或者闪视频APP进行线上投票，可分享拉票，助力你支持的团体、个人上《2023丝路嘉年华·丝路春晚》。
        </p>
        <p>
          5、投票须知：每个用户每日的票数固定，即可分散投票，也可集中投票。微信H5打开每人每日可投2票，闪视频APP打开每人每日可投10票，欢迎大家下载闪视频APP参与投票，查看排行榜，为你支持的团体、个人助力打call。本次投票活动公开透明，排行榜实时更新，禁止刷票，如有违法一经查实将取消参赛资格，最终解释权归主办方所有。
        </p>
        <p>
          6、 荣誉：
          <p>
            1）网络投票人气第一的团体、个人直通丝路春晚晚会，在丝路春晚晚会中露出（陕西卫视、五大洲电视台播出）；网络投票第二、三名的团体、个人将直通丝路嘉年华，在丝路嘉年华露出（陕西卫视）具体呈现形式由导演组与入选作品的团体、个人分别充分沟通，优化包装作品。
          </p>
          <p>
            2）直通丝路嘉年华和丝路春晚的团体、个人在录制结束后，将获得闪视频独家个人专访和宣传形象照。
          </p>
          <p>
            3）网络投票人气前五的团体、个人将获得由丝路春晚导演组颁发的荣誉证书。
          </p>
        </p>
        <p>
          7、奖励：
          <p>
            网络投票人气第一、二、三名的团体分别获得奖金3000元、2000元、1000元。
          </p>
          <p>
            网络投票人气第一、二、三的个人分别获得奖金1000元、600元、300元。
          </p>
        </p>
      </div>
    ),
  });
};

const paiming = () => {
  if (!config.isShanShiPin) return showToast("下载闪视频查看投票结果。");
  getRankList(() => {
    showPaihang.value = true;
  });
};

const formmate = num => {
  if (num === 0) return num;
  let N = num || 0;
  switch (true) {
    case N >= 10000:
      N = (N / 10000).toFixed(2) - 0 + "万";
      break;
    case N >= 100000000:
      N = (N / 100000000).toFixed(2) - 0 + "亿";
      break;
  }
  return N;
};

let videoEleHTML = undefined;

const clickShowVideo = item => {
  showVideo.value = !showVideo.value;
  if (!item) return;
  video.value = item || {};
  if (!videoEleHTML) videoEleHTML = document.querySelector("video");
  videoEleHTML.currentTime = 0;
  videoEleHTML.play();
};
</script>
<style lang="scss">
.SilkRoadShanShiPinList {
  width: 100vw;
  padding-bottom: 80px;
  //   .van-cell-group__title {
  //     font-size: 1rem;
  //     font-weight: bold;
  //   }
  .van-cell__value {
    color: #000;
  }
  .text {
    padding: 10px 16px;
  }
  .guize {
    background-color: #ff2c2c;
    position: fixed;
    right: 0;
    top: 2em;
    color: #fff;
    font-weight: 400;
    font-size: 16px;
    padding: 3px 5px 3px 15px;
    border-top-left-radius: 1em;
    border-bottom-left-radius: 1em;
    z-index: 2;
  }
  .SilkList {
    height: calc(50vh - 60px);
    overflow-y: auto;
  }
  .btn {
    font-size: 0;
    text-align: center;
    color: #666;
    position: relative;
    padding: 3px 0;
    border-radius: 5px;
    img {
      display: block;
      margin: 0 auto;
      width: 80px;
    }
  }
  .videoEle {
    width: 100vw;
    position: fixed;
    background-color: #000;
    top: 50%;
    z-index: 21;
    transform: translateY(-50%);
  }
  .van-overlay {
    .video {
      width: 100vw;
      height: 100vh;
      top: 0;
      position: fixed;
      .videoText {
        color: #fff;
        position: absolute;
        bottom: 0;
        padding: 0.5em;
        text-indent: 2em;
      }
    }

    .close {
      position: absolute;
      top: 10px;
      right: 10px;
      z-index: 22;
      color: #fff;
      font-size: 20px;
    }
  }
}
</style>
