<template>
  <div class="finance">
    <img src="../../assets/img/financeBanner.jpg" style="width: 100%" />
    <div class="guize" @click="showGuize">投票规则</div>
    <div class="guize" style="top: 6em" @click="paiming">查看排名</div>
    <van-search
      :background="background"
      clearable
      v-model="search"
      shape="round"
      placeholder="请输入搜索关键词"
    />
    <van-tabs :color="theme" :background="background">
      <van-tab :title="i" v-for="(v, i) in orilist" :key="i">
        <van-row gutter="8">
          <van-col
            span="12"
            :style="{
              position: 'relative',
              display: item.noShow ? 'none' : 'inline-block',
            }"
            v-for="item in v"
            :key="item.id"
          >
            <van-image
              :width="width"
              :height="height"
              fit="cover"
              @click="() => clickShowVideo(item)"
              position="left"
              :src="create_url_image(item.workTitle)"
            />
            <van-row>
              <van-col
                span="24"
                style="text-align: center"
                class="van-ellipsis unit"
                >{{ item.university }}</van-col
              >
              <van-col span="24" style="text-align: center">
                <div class="van-multi-ellipsis--l2">
                  {{ item.name }}
                </div>
              </van-col>
            </van-row>
            <br />
            <van-checkbox
              class="act"
              v-model="ids[item.phone].select"
              :checked-color="theme"
            />
          </van-col>
        </van-row>
      </van-tab>
    </van-tabs>
    <div
      class="btn"
      :style="{ bottom: config.isShanShiPin ? '5px' : '75px' }"
      @click="toupiao"
    >
      投票
    </div>
    <Shanshipin v-if="!config.isShanShiPin" :color="background" />
    <!-- 投票框 -->
    <van-dialog v-model:show="showPaihang" confirm-button-text="关闭">
      <div style="height: 50vh">
        <van-tabs :color="theme">
          <van-tab :title="key" v-for="(v, key) in rankList" :key="key">
            <div class="SilkList">
              <van-cell-group inset>
                <van-cell title="名称" value="投票量"></van-cell>
                <van-row v-for="item in v" :key="item.id + 'team'">
                  <van-col span="16"
                    ><p class="text van-ellipsis--l2" 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-dialog
      theme="round-button"
      v-model:show="showLogin"
      confirm-button-text="登录"
      :before-close="beforeClose"
    >
      <van-cell-group inset>
        <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"
              :color="theme"
            >
              发送验证码
            </van-button>
            <van-count-down
              format="ss 秒"
              v-else
              :time="codePhoen"
              @finish="() => (codePhoen = 0)"
            />
          </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, watch } from 'vue';
import { showDialog, showConfirmDialog, showToast } from 'vant';
import {
  getEnrollList,
  getEnrollRank,
  getVote,
  getTimes,
  getSendVerifyCode,
  verifyCode,
} from '@/api/SilkRoadSpringGala.js';

import Shanshipin from '@/components/shanshipin.vue';
const theme = '#38379f';
const background = '#e0f2fa';
const w = window.$originData.orginParames.availWidth || 0;
const operateId = window.$originData.orginParames.operateId;
const width = (w - 16) / 2;
const height = width * 0.57;
const showPaihang = ref(false);
const showLogin = ref(false);

const rankList = ref({});
const orilist = ref({});

const ids = ref({});
const codePhoen = ref(0);
const config = reactive({
  times: -1,
  isShanShiPin: window.$shanshipin.UserId,
});
const search = ref('');
const t = config.isShanShiPin ? 5 : 1;
const phone =
  window.$shanshipin.Phone && window.$shanshipin.Phone != 0
    ? window.$shanshipin.Phone
    : localStorage.getItem('financePhone') || '18439106376';
const login = reactive({
  phone,
  code: '',
});
const getList = call => {
  getEnrollList({
    operateId,
  }).then(r => {
    const array = r || [];
    const obj = {};
    const ids_list = [];
    for (let i = 0; i < array.length; i++) {
      const v = array[i];
      v.noShow = false;
      if (obj[v.type]) obj[v.type].push(v);
      else obj[v.type] = [v];

      ids_list[v.phone] = {
        select: false,
        name: v.name,
        phone: v.phone,
      };
    }
    ids.value = ids_list;
    orilist.value = obj;
    call && call();
  });
};
getList();

const getRankList = Call => {
  getEnrollRank({
    operateId,
  }).then(r => {
    const l = r || [];
    const obj = {};
    for (let i = 0; i < l.length; i++) {
      const v = l[i];
      if (obj[v.type]) obj[v.type].push(v);
      else obj[v.type] = [v];
    }
    rankList.value = obj;
    Call && Call();
  });
};

let time = null;
watch(search, res => {
  if (time) clearTimeout(time);
  time = setTimeout(() => {
    const rex = res ? new RegExp(res) : /[.\n]*/;
    for (const key in orilist.value) {
      if (!Object.hasOwnProperty.call(orilist.value, key)) continue;
      const v = orilist.value[key];
      for (let i = 0; i < v.length; i++) {
        const vv = v[i];
        vv.noShow = !rex.test(vv.name) && !rex.test(vv.university);
      }
    }
    clearTimeout(time);
    time = null;
  }, 200);
});

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

  getSendVerifyCode({
    phone: login.phone,
  }).then(() => {
    codePhoen.value = 60000;
  });
};
const toupiao = function () {
  let names = [];
  let phones = [];
  for (let i = 0; i < ids.value.length; i++) {
    const v = ids.value[i] || {};
    if (!v.select) continue;
    names.push(v.name);
    phones.push(v.phone);
  }
  if (!phones.length) return showToast('请选择您中意的候选人');
  if (phones.length > 10) return showToast('最多只能投10人');
  if (!login.phone || login.phone.length < 11) return (showLogin.value = true); //如果没有手机号提示登录
  showConfirmDialog({
    message: '确定投票给' + names.join(',') + '么？',
    beforeClose: type => {
      if (type !== 'confirm') return true;
      return new Promise(resolve => {
        getVote({
          target: phones.join(','),
          source: login.phone,
          client: config.isShanShiPin ? '闪视频' : '其他',
          operateId,
        })
          .then(() => {
            showToast('投票成功！');
            resolve(true);
          })
          .catch(err => {
            showToast(err.message || '投票失败！');
            resolve(true);
          });
      });
    },
  });
};

const create_url_image = url => {
  if (/\.mp4$/.test(url))
    url = url + '?x-oss-process=video/snapshot,t_4000,f_jpg';
  return url;
};

const beforeClose = () => {
  if (!login.phone || !login.code) return false;
  getTimes({
    phone: login.phone,
  }).then(r => {
    config.times = r.times - t >= 0;
    verifyCode({
      phone: login.phone,
      code: login.code,
    })
      .then(r => {
        localStorage.setItem('financePhone', login.phone);
        localStorage.setItem('financeToken', r.token);
        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;
};

const clickShowVideo = item => {
  location.href = item.file;
};
</script>
<style lang="scss">
.finance {
  $color: #38379f;
  width: 100vw;
  padding-bottom: 120px;
  background-color: #e0f2fa;
  min-height: 100vh;

  .van-cell__value {
    color: #000;
  }
  .act {
    position: absolute;
    top: 2px;
    left: 2px;
    z-index: 1;
  }
  .text {
    padding: 10px 16px;
  }
  .guize {
    background-color: $color;
    position: fixed;
    right: 0;
    top: 4em;
    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 {
    text-align: center;
    color: #fff;
    position: fixed;
    line-height: 2.5em;
    height: 2.5em;
    left: 5%;
    width: 90%;
    background-color: $color;
    z-index: 2;
    padding: 3px 0;
    border-radius: 5px;
  }
  .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;
    }
  }
  .unit {
    font-size: 14px;
    color: #646566;
  }
}
</style>
