<template>
  <div class="finance">
    <img src="../../assets/img/financeBanner.jpg" style="width: 100%" />
    <div class="guize" @click="showGuize">投票规则</div>
    <div class="guize" style="top: 10em" @click="paiming">查看排名</div>
    <van-search
      :background="background"
      clearable
      v-model="search"
      shape="round"
      placeholder="请输入搜索关键词"
    />
    <van-tabs :color="theme" :background="background">
      <van-tab :title="_sort[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>
    <!-- 候选人详情框 -->
    <van-dialog
      v-model:show="hxrDialog"
      confirm-button-text="投票"
      cancel-button-text="为他拉票"
      :show-cancel-button="true"
      @close="close"
      @cancel="cancel"
      @confirm="shear_page"
      style="padding: 5px"
    >
      <div
        class="van-ellipsis"
        style="margin: 0.5em 0"
        v-text="selectItem.name"
      ></div>
      <div
        class="van-ellipsis unit"
        style="margin: 0.5em 0"
        v-text="selectItem.university"
      ></div>
      <div style="position: relative" @click="toDetal(selectItem.file)">
        <van-icon
          size="50"
          color="#fff"
          name="play-circle-o"
          style="
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
          "
        />
        <img
          :src="create_url_image(selectItem.workTitle)"
          style="width: 100%"
        />
      </div>
    </van-dialog>

    <div class="zhezhao" v-show="imgObj.image">
      <div class="zhezhao_img">
        <img :src="imgObj.image" style="width: 100%" />
        <p style="text-align: center; color: #fff; margin: 1em 0">
          长按保存图片，发给好友一起参与
        </p>
        <van-button
          @click="
            () => {
              imgObj = {};
            }
          "
          color="#fff"
          style="
            margin: 0 auto;
            display: block;
            border: none;
            background-color: #ffffff00;
          "
          icon="cross"
          type="default"
          round
        />
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import QRCode from 'qrcode';
import { showDialog, showConfirmDialog, showToast } from 'vant';
import {
  getEnrollList,
  getEnrollRank,
  getVote,
  getTimes,
  getSendVerifyCode,
  verifyCode,
} from '@/api/SilkRoadSpringGala.js';
import { canvasToImage } from '@/utils/tool.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 hxrDialog = ref(false);
const showPaihang = ref(false);
const showLogin = ref(false);
const selectItem = ref({});
const imgObj = ref({});

const rankList = ref({});
const orilist = ref([]);
const _sort = ['党建引领', '金融知识', '风险防范', '金融服务', '优秀宣讲员'];

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;
let time_old = undefined;
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 = [];
    let item = undefined;

    for (let i = 0; i < array.length; i++) {
      const v = array[i];
      v.noShow = false;
      const num = getIndex(v.type);
      if (obj[num]) obj[num].push(v);
      else obj[num] = [v];

      ids_list[v.phone] = {
        select: false,
        name: v.name,
        phone: v.phone,
      };

      if (
        window.$originData.urlParames.id &&
        v.phone === window.$originData.urlParames.id
      ) {
        // 默认打开卡片
        item = v;
      }
    }
    if (item) {
      time_old = setTimeout(() => {
        clickShowVideo(item);
        clearTimeout(time_old);
      }, 500);
    }
    ids.value = ids_list;
    orilist.value = obj;
    call && call();
  });
};
onMounted(() => {
  getList();
});

const getIndex = key => {
  const sort_list = {
    党建引领: 0,
    金融知识: 1,
    风险防范: 2,
    金融服务: 3,
    优秀宣讲员: 4,
  };
  return sort_list[key] || 0;
};

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();
  });
};

const shear_page = () => {
  // 投票
  if (!login.phone || login.phone.length < 11) return (showLogin.value = true); //如果没有手机号提示登录
  showConfirmDialog({
    message: '确定投票给' + selectItem.value.name + '么？',
    beforeClose: type => {
      if (type !== 'confirm') return true;
      return new Promise(resolve => {
        getVote({
          target: [selectItem.value.phone],
          source: login.phone,
          client: config.isShanShiPin ? '闪视频' : '其他',
          operateId,
        })
          .then(() => {
            showToast('投票成功！');
            resolve(true);
          })
          .catch(err => {
            showToast(err.message || '投票失败！');
            resolve(true);
          });
      });
    },
  });
};
const toDetal = file => {
  location.href = file;
};
const cancel = async () => {
  const w = 900 * window.devicePixelRatio;
  const w1 = w * 0.8;
  const fs = w / 20;
  const bs = w / 15;
  const title_text = selectItem.value.name.replace(/《|》/g, '');
  const title =
    title_text.length >= 16
      ? title_text.split('').splice(0, 13).join('') + '...'
      : title_text;
  const qt = await QRCode.toDataURL(
    [location.protocol, '//', location.host, '/finance.html?id=', selectItem.value.id].join('')
  );
  const layers = {
    list: [
      {
        type: 'image',
        src: 'https://cxzx.smcic.net/topic/tool/img/0.jpg',
        width: w,
        height: w,
        x: 0,
        y: 0,
      },
      {
        type: 'image',
        src: create_url_image(selectItem.value.workTitle),
        width: w1,
        height: (w1 / 16) * 9,
        x: w / 10,
        y: bs,
      },
      {
        type: 'text',
        color: '#ffffff',
        font: fs + 'px Arial',
        text: title,
        x: w / 10,
        y: (w1 / 16) * 9 + bs * 2,
      },
      {
        type: 'text',
        color: '#ffffff',
        font: fs + 'px Arial',
        text: '快来为我投上一票把！',
        x: w / 10,
        y: (w1 / 16) * 9 + bs * 3,
      },
      {
        type: 'image',
        src: qt,
        width: w / 5,
        height: w / 5,
        x: w1 + bs - w / 5,
        y: (w1 / 16) * 9 + bs * 4,
      },
    ],
    width: w,
    height: w,
  };
  imgObj.value = await canvasToImage(layers);
};

let time = null;
watch(search, res => {
  if (time) clearTimeout(time);
  time = setTimeout(() => {
    const rex = res ? new RegExp(res) : /[.\n]*/;
    for (let o = 0; o < orilist.value.length; o++) {
      const v = orilist.value[o];
      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、投票时间：2023年12月15日9:00至12月21日9:00（共7天）。</p>
        <p>
          3、投票内容：网络短视频作品137件。（分为党建引领、金融知识类、风险防范、金融服务四大类），优秀宣讲员作品27件。
        </p>
        <p>
          4、投票形式：通过微信H5或者闪视频APP进行线上投票，可分享拉票，助力你支持的作品、宣讲员登上排名。
        </p>
        <p>
          5、投票须知：每个用户每日的票数固定，即可分散投票，也可集中投票，每人每天10票。
        </p>
        <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 => {
  selectItem.value = item || {};
  hxrDialog.value = true;
};
const close = () => {};
</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: 8em;
    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;
  }

  .zhezhao {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.8);
    z-index: 10;

    .zhezhao_img {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 80vw;
    }
  }
}
</style>
