<script setup lang="ts">
import png11 from '@/assets/img/home/11.png';
import png13 from '@/assets/img/home/13.png';
import png14 from '@/assets/img/home/14.png';
import png15 from '@/assets/img/home/15.png';
import png16 from '@/assets/img/home/16.png';
import png17 from '@/assets/img/home/17.png';
import png18 from '@/assets/img/home/18.png';
import png31 from '@/assets/img/home/31.png';
import { showDialog, showFailToast, showSuccessToast } from 'vant';
import { finish } from '@/api/survey';
import { copySurveys } from '@/api/home';
import { useRoute, useRouter } from 'vue-router';
import {
  fetchSurveys,
  deleteItem,
  saveTemplate,
  currentSurvey,
  clearSurveys
} from '@/views/Survey/hooks/useSurveyData';
import ai from '@/assets/img/analysis/ai.svg';
import { computed, onMounted, ref, useTemplateRef, type CSSProperties } from 'vue';
import { formatTime } from '@/utils/date';
import { windowWidth } from 'vant/lib/utils';

const form = ref({
  page: 0,
  pageSize: 10,
  project_name: ''
});

const titleRef = useTemplateRef('titleRef');

// router
const router = useRouter();
const route = useRoute();

const emit = defineEmits(['post-analysis', 'post-surveys']);
const survey = defineModel<SurveyItem>('survey', { required: true });
const isAnalysis = defineModel('isAnalysis', { default: false, type: Boolean });
// 禁用 action 功能
const disableActionButton = defineModel('disableActionButton', { default: false, type: Boolean });

const postAnalysis = defineModel<Function>('post-analysis');
function setImg(code: number) {
  const imageMap: { [key: number]: string } = {
    11: png11,
    13: png13,
    14: png14,
    15: png15,
    16: png16,
    17: png17,
    18: png18,
    31: png31
  };
  // 默认返回 png11 如果 code 不存在
  return imageMap[code] || png11;
}

// 是否显示 title 的 popover
const showTitlePop = ref(false);
// 是否是短标题 title; 在组件挂载之后会根据 title 的宽度来判断
const isShortTitle = ref(false);
onMounted(() => {
  // console.log(titleRef.value);
  if (titleRef.value) {
    const offsetWidth = titleRef.value.$el.offsetWidth;
    isShortTitle.value = 120 <= offsetWidth;
  }
});

const surveyTitleStyle = computed<CSSProperties>(() => {
  const isPublishNumber = survey.value.is_publish_number;
  const isSurveyTime = survey.value.is_time;
  let width = '';
  if (isSurveyTime && isPublishNumber) {
    if (isShortTitle.value) {
      width = '25vw';
    }
  } else if (isSurveyTime) {
    width = '170px';
  }
  return {
    maxWidth: width
  };
});

function editItem(item: SurveyItem) {
  router.push({
    path: '/create',
    query: {
      sn: item.sn
    }
  });
}

function toPreview(item: SurveyItem) {
  router.push({
    path: '/preview',
    query: {
      sn: item.sn,
      name: item.project_name,
      source: 0,
      is_template: 1
    }
  });
}

/**
 * 跳转 统计分析 页面
 * @param item
 */
function toAnalysis(item: SurveyItem) {
  // 设置当前的节点信息
  currentSurvey.value = item;
  // 跳转
  router.push({
    path: '/analysis',
    query: {
      sn: item.sn
    }
  });
}

function toPublish(item: SurveyItem) {
  if (item.status === 1) {
    showDialog({
      title: `确定要取消投放${item.project_name}?`,
      showCancelButton: true
    })
      .then(() => {
        finish(item.sn).then((res) => {
          if (res.data) {
            // 把数据改掉
            item.status = 2;
          }
        });
      })
      .catch(() => {
        // on cancel
      });
  } else {
    router.push({
      path: '/publish',
      query: {
        sn: item.sn
      }
    });
  }
}

function copyItem(item: SurveyItem) {
  showDialog({
    title: `确认复制问卷${item.project_name} ?`,
    showCancelButton: true,
    confirmButtonColor: '#03B03C'
  })
    .then(() => {
      copySurveys(item.sn).then((res) => {
        if (res.data.code === 200 || res.data.code === 201) {
          showSuccessToast('复制成功');
          form.value.page = 1;
          clearSurveys();
          fetchSurveys(form.value);
        } else {
          showFailToast(res.data);
        }
      });
    })
    .catch(() => {
      // on cancel
    });
}
</script>

<template>
  <section style="width: 100%">
    <!--  问卷详情    -->
    <div class="survey_item_info">
      <div style="position: relative">
        <div style="display: flex; justify-content: space-between; margin: 10px 0">
          <div class="survey_item_info_title">
            <el-text ref="titleRef" :style="surveyTitleStyle">
              <b v-html="survey.project_name"></b>
            </el-text>
            <el-text v-if="survey.is_publish_number" class="wrap">
              {{ survey.publish_number }}份
            </el-text>
            <el-text v-if="survey.is_time" class="wrap" style="text-wrap: nowrap">
              {{ `${survey.start_time}${survey.end_time ? ' 至 ' + survey.end_time : ''}` }}
            </el-text>
          </div>

          <!-- AI 洞察图片 -->
          <img
            v-if="!isAnalysis"
            :src="ai"
            class="survey_item_info_title-survey"
            @click="emit('post-analysis')"
          />
        </div>
        <div class="survey_item_info_status">
          <el-space spacer="|">
            <!--报名签到-->
            <div class="flex align-center">
              <img src="@/assets/img/publish/user.png" alt="Content Icon" />
              <el-text size="small">{{ survey.owner ?? '未知用户' }}</el-text>
            </div>
            <!-- 问卷来源 -->
            <div class="flex align-center">
              <img v-if="survey.source === 1" src="@/assets/img/publish/phone.png" alt="" />
              <img v-else src="@/assets/img/publish/pc.png" alt="" />
              <el-text size="small">
                {{ survey.source === 1 ? '移动端' : 'PC端' }}
              </el-text>
            </div>
            <!-- 问卷时间 -->
            <div class="flex align-center">
              <img src="@/assets/img/publish/time.png" alt="" />
              <el-text size="small">
                创建时间 {{ formatTime(survey.created_at, '-', '.') }}
              </el-text>
            </div>
          </el-space>
        </div>
        <!-- 单独为主页做适配 -->
        <div
          v-if="isAnalysis"
          class="survey_item_status"
          :style="{
            top: route.path === '/home' ? '-20px' : '-25px',
            right: route.path === '/home' ? '-20px' : '-25px'
          }"
        >
          <img v-if="survey.status === 0" src="@/assets/img/publish/edit.png" alt="" />
          <img v-else-if="survey.status === 1" src="@/assets/img/publish/publish.png" alt="" />
          <img v-else-if="survey.status === 2" src="@/assets/img/publish/end.png" alt="" />
        </div>
      </div>
      <!--问卷描述-->
      <el-space class="survey_item_info_desc" spacer="|">
        <section>
          <el-text size="small">回收数量</el-text>
          <el-text> {{ survey.answer_num_h5 }}</el-text>
        </section>
        <section>
          <el-text size="small">回收数量进度</el-text>
          <el-text>{{ survey.recycle_progress_h5 }}</el-text>
        </section>
        <section>
          <el-text size="small">投放时间进度</el-text>
          <el-text> {{ survey.recycle_time }}</el-text>
        </section>
      </el-space>
    </div>
    <!-- action 功能位置 -->
    <div v-if="!disableActionButton" class="survey_item_action">
      <div>
        <el-button :disabled="survey.source === 0" @click="editItem(survey)"> 编辑 </el-button>
        <el-button style="border: 1px solid #71b73c" @click="toAnalysis(survey)">
          <el-text style="color: #71b73c">统计</el-text>
        </el-button>

        <el-button color="#6fb937" @click="toPublish(survey)">
          <el-text style="color: white">
            {{ survey.status === 1 ? '结束投放' : '开启投放' }}
          </el-text>
        </el-button>
      </div>
      <!-- 移除 PC 端不能操作 -->
      <!-- v-if="survey.source === 1" -->
      <el-dropdown placement="top-end" trigger="click" active-color="#71b73c">
        <van-icon class-prefix="mobilefont" name="gengduo" size="0.7rem"></van-icon>
        <template #dropdown>
          <el-dropdown-menu
            active-color="#71b73c"
            :close-on-click-overlay="false"
            :close-on-click-outside="false"
          >
            <el-dropdown-item @click="toPreview(survey)"> 预览 </el-dropdown-item>
            <el-dropdown-item v-if="survey.source === 1" @click="copyItem(survey)">
              复制
            </el-dropdown-item>
            <el-dropdown-item v-if="survey.source === 1" @click="deleteItem(survey, form)">
              删除
            </el-dropdown-item>
            <el-dropdown-item @click="saveTemplate(survey)"> 存为模板 </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </section>
</template>

<style scoped lang="scss">
@import '@/assets/css/base';
@import '@/assets/css/main';

.survey_item_info {
  .survey_item_info_status {
    display: flex;
    margin-bottom: 15px;
    color: #666;

    img {
      height: 12px;
      margin-right: 3px;
    }
  }

  .survey_item_status {
    position: absolute;
    top: -25px;
    right: -25px;

    img {
      transform: translate(0%, -7%);
      width: 98px;
    }
  }

  .survey_item_info_title {
    display: flex;

    .el-text {
      font-size: 15px;

      &:first-child {
        display: inline-block;
        max-width: 200px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-weight: 500;
        font-size: 14px;
        color: #000;
      }
    }

    .wrap {
      margin-left: 5px;
      padding: 1px 3px;
      border: 0.5px solid rgba(192, 192, 192, 0.35);
      border-radius: 6px;
      font-size: 12px;
      text-wrap: nowrap;
      color: #333333;
    }
    & > :nth-child(3) {
      padding: 0 4px;
      border-radius: 6px;
      font-size: 12px;
      color: #333333;
      margin-left: 7px;
      border: 0.5px solid rgba(192, 192, 192, 0.35);
    }
  }

  .survey_item_info_desc {
    display: flex;
    flex-flow: row wrap;
    align-items: center;
    justify-content: space-around;
    border-radius: 8px;
    background-color: #f6f7f8;
    overflow: hidden;
    text-overflow: ellipsis;
    padding: 14px 30px;
    box-sizing: border-box;
    color: #828282;
    //font-weight: 400;
    font-size: 12px;

    section {
      display: flex;
      flex-flow: column nowrap;
      align-items: center;
      justify-content: center;

      & > :nth-last-child(-n + 1) {
        font-size: 20px;
        font-weight: bold;
        color: $theme-color;
      }
    }
  }
}

.survey_item_action {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 5px;
  margin-top: 10px;
  font-weight: 400;

  .el-button {
    width: 18vw;
    border-radius: 8px;
  }

  .el-space {
    display: flex;
    justify-content: space-evenly;
  }
}
</style>
