<template>
  <div class="publish-container">
    <div v-if="status === 1">
      <div class="qrcode-box">
        <img class="bg_img" :src="bg" alt="" />
        <div class="content">
          <p class="tit" style="overflow: auto; max-height: 50px">
            {{ surveyTitle ? surveyTitle : '' }}
          </p>
          <p style="margin-top: 6px; font-size: 500">扫码填写问卷</p>
        </div>
        <img class="qrcode-img" :src="publishInfo?.img_url" alt="" />
      </div>
      <div class="desc" v-html="introduction"></div>
      <van-divider dashed class="tip" :style="{ borderColor: '#979797', padding: '0 8px' }">
        移动端仅做数据回收，问卷数据分析请前往PC端浏览
      </van-divider>
      <div class="operation">
        <span v-for="(item, index) in operateList" :key="index" @click="operateBtn(item)">
          <img :src="item.icon" alt="" />
          {{ item.title }}
        </span>
      </div>
    </div>
    <div v-if="status === 0 || status === 2" class="enable-box">
      <img class="not-publish-icon" src="@/assets/img/publish/not_pulish.png" alt="" />
      <div class="content">点击"启用"按钮后，问卷才可以开始回收数据</div>
      <van-button
        type="primary"
        style="margin-top: 20px"
        class="btn"
        color="#70b936"
        @click="openPublishModal"
      >
        <template #icon>
          <i class="mobilefont mobilefont-fasong"></i>
        </template>
        启用
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router';
import { onMounted, reactive, ref, watch } from 'vue';
import { showFailToast, showToast } from 'vant';
import utils from '@/assets/js/common';
import appBridge from '@/assets/js/appBridge';
import { getQrcode, getSurveyInfo, publishSurvey } from '@/api/survey';
import { canPlanetPublish } from '@/layouts/utils.js';
import bg from '@/assets/img/publish/bg.png';
import copyIcon from '@/assets/img/publish/copy_icon.png';
import shareIcon from '@/assets/img/publish/share_icon.png';
import downloadIcon from '@/assets/img/publish/download_icon.png';

const route = useRoute();
const sn = route.query.sn;
const surveyTitle = ref('');
const surveyDesc = ref('');
const introduction = ref('');
// `0`: 编辑中 `1`: 投放中 `2`: 已结束
const status = ref<number>(0);
const publishType = ref(0);
const operateList = reactive([
  {
    title: '复制链接',
    type: 'copyLink',
    icon: copyIcon
  },
  {
    title: '转发至微信',
    type: 'shareLink',
    icon: shareIcon
  },
  {
    title: '下载二维码',
    type: 'qrCode',
    icon: downloadIcon
  }
]);

interface PublishInfo {
  download_url: {
    title: string;
    url: string;
  };
  desc?: string;
  img_url: string;
  url: string;
}

const publishInfo = ref<PublishInfo>({} as PublishInfo);
type OperateItem = (typeof operateList)[0];

const operateBtn = (item: OperateItem) => {
  switch (item.type) {
    case 'shareLink':
      shareLink();
      break;
    case 'copyLink':
      copyLink();
      break;
    case 'qrCode':
      downLoadImg();
      break;
    default:
      break;
  }
};
// 复制链接
function copyLink() {
  const input = document.createElement('input');
  input.value = publishInfo.value.url;
  document.body.appendChild(input);
  input.select();
  document.execCommand('Copy');
  document.body.removeChild(input);
  showToast('链接复制成功');
}
// 分享链接
function shareLink() {
  const params = {
    type: 'shareToWx',
    title: surveyTitle.value
      ? surveyTitle.value
      : publishInfo?.value?.download_url.title
        ? publishInfo.value.download_url.title.replace(/_发布二维码\.[a-zA-Z]+$/, '').trim()
        : '',
    description: surveyDesc.value || '',
    thumbImageUrl: publishInfo.value.img_url,
    webpageUrl: publishInfo.value.url,
    // 朋友圈1  微信好友0
    scene: 0
  };
  appBridge.shareToWeChat(params, () => {
    // 分享成功
  });
}

// 下载二维码
function downLoadImg() {
  const { title, url } = publishInfo.value.download_url;
  if (appBridge.isInReactNative()) {
    appBridge.save2Album(url, () => {
      showToast('二维码下载成功，请打开系统相册查看');
    });
  } else {
    const link = document.createElement('a');
    link.href = url;
    link.download = title;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}
async function openPublishModal() {
  const res = await canPlanetPublish(route.query.sn as string, publishType.value);
  if (res) {
    await publishSurvey({
      sn,
      publish_type: publishType.value
    })
      .then(() => {
        fetchInfo();
      })
      .catch((error) => {
        showFailToast(error.data?.message || error.message || '服务器错误');
      });
  }
}

function getCode() {
  getQrcode(sn)
    .then((res) => {
      if (res.data) {
        publishInfo.value = res.data.data || {};
      }
    })
    .catch((error) => {
      showFailToast(error.data?.message || error.message || '服务器错误');
    });
}
function fetchInfo() {
  getSurveyInfo(sn)
    .then((res) => {
      status.value = Number(res.data.data.status);
      surveyTitle.value = res?.data?.data?.project_name ? res.data.data.project_name.trim() : '';
      surveyDesc.value = res?.data?.data?.remarks || '';
      introduction.value = res?.data?.data?.introduction || '';
    })
    .catch((error) => {
      showFailToast(error.data?.message || error.message || '服务器错误');
    });
}
watch(status, (val) => {
  if (val === 1) {
    getCode();
  }
});
onMounted(async () => {
  fetchInfo();
});
</script>

<style lang="scss" scoped>
$primary-color: #70b936;
$secondary-color: #5477aded;
$text-color-dark: #666;
$text-color-light: #999;
$border-radius: 16px;
$box-shadow: 0 0 2px rgba(0, 0, 0, 0.1);

.publish-container {
  margin: 10px;
  border-radius: $border-radius;
  background: #fff;
  box-shadow: $box-shadow;
  max-height: 100vh;
  overflow: auto; // 添加滚动能力

  .qrcode-box {
    text-align: center;
    position: relative;
    width: 100%;

    .bg_img {
      width: 100%;
      height: auto; // 改为auto以保持宽高比
    }

    .content {
      position: absolute;
      width: 55%;
      top: 28%;
      left: 50%;
      transform: translateX(-50%);
      text-align: center;
      word-break: break-all;
      font-size: 16px;
      line-height: 24px;
      font-weight: 600;

      .tit {
        color: #fff;
        background: $secondary-color;
        border-radius: 3px;
        padding: 2px 0;
        max-height: 50px;
        overflow: auto;
      }
    }

    .qrcode-img {
      width: 145px;
      height: 145px;
      border: 1px solid rgba(151, 151, 151, 0.2);
      border-radius: 8px;
      position: absolute;
      z-index: 999;
      bottom: 11%;
      left: 50%;
      transform: translateX(-50%);
    }
  }

  .desc {
    width: 83%;
    margin: 5px auto;
    text-align: center;
    font-size: 13px;
    line-height: 20px;
    color: $text-color-dark;
  }

  .tip {
    margin: 10px 20px;
    color: $text-color-light;
    font-size: 12px;
    text-align: center;

    :deep(.van-divider--dashed::before),
    :deep(.van-divider--dashed::after) {
      margin: 0 -10px !important;
    }
  }

  .operation {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin: 15px 35px 20px;

    span {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: $text-color-dark;
      font-size: 12px;

      img {
        margin-bottom: 8px;
        width: 40px;
        height: 40px;
      }
    }
  }

  .enable-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 50vh;
    padding: 24px 32px 28px;

    .not-publish-icon {
      width: 150px;
      height: 150px;
    }

    .content {
      margin-top: 20px;
      color: $primary-color;
      font-size: 14px;
    }

    .btn {
      display: flex;
      align-items: center;
      height: 32px;
      border-radius: 4px;
    }
  }
}
</style>
