<template>
  <div class="survey-search">
    <van-search
      v-model="searchValue"
      placeholder="请输入关键词"
      class="theme-background"
      :border="false"
      background="#71b73c"
      @search="blurs"
    ></van-search>
  </div>
  <div class="new-survey-container">
    <div style="margin-bottom: 80px">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div v-for="item in survey" :key="item" class="new-survey_item">
          <!--  问卷详情    -->
          <div class="survey_item_info">
            <div style="position: relative">
              <div class="survey_item_info_title">
                <el-text>
                  <b v-html="item.project_name"></b>
                </el-text>
                <el-text>{{ item.answer_num }}份</el-text>
              </div>
              <div class="survey_item_info_status">
                <el-space spacer="|">
                  <!--报名签到-->
                  <div class="flex align-center">
                    <img
                      :src="setImg(item.scene_code_info)"
                      alt="Content Icon"
                      style="width: 15px; height: 15px"
                    />
                    <el-text size="small">{{ item.scene_name }}</el-text>
                  </div>
                  <!-- 问卷来源 -->
                  <div class="flex align-center">
                    <img v-if="item.source === 1" src="../../assets/img/publish/phone.png" alt="" />
                    <img v-else src="../../assets/img/publish/pc.png" alt="" />
                    <el-text size="small">{{ item.source === 1 ? '移动端' : 'PC端' }}</el-text>
                  </div>
                  <!-- 问卷时间 -->
                  <div class="flex align-center">
                    <img src="../../assets/img/publish/time.png" alt="" />
                    <el-text size="small">{{ item.created_at }}</el-text>
                  </div>
                </el-space>
              </div>
              <div class="survey_item_status">
                <img v-if="item.status === 0" src="../../assets/img/publish/edit.png" alt="" />
                <img
                  v-else-if="item.status === 1"
                  src="../../assets/img/publish/publish.png"
                  alt=""
                />
                <img v-else-if="item.status === 2" src="../../assets/img/publish/end.png" alt="" />
                <!--              <span class="survey_item_info_status_text">-{{ item.status_txt }}-</span>-->
              </div>
            </div>
            <!--问卷描述-->
            <div v-if="item.introduction">
              <div v-html="item.introduction" class="survey_item_info_desc"></div>
            </div>
          </div>
          <!-- action 功能位置 -->
          <div class="survey_item_action">
            <!--        <el-space direction="horizontal">-->
            <div>
              <el-button :disabled="item.source === 0" @click="deleteItem(item)"> 删除</el-button>
              <el-button :disabled="item.source === 0" @click="copyItem(item)"> 复制</el-button>
              <el-button style="border: 2px solid #71b73c" @click="toPreview(item)">
                <el-text style="color: #71b73c">预览</el-text>
              </el-button>
              <el-button color="#6fb937" :disabled="item.source === 0" @click="toPublish(item)">
                <el-text style="color: white">
                  {{ item.status === 1 ? '结束投放' : '开启投放' }}
                </el-text>
              </el-button>
            </div>
            <el-dropdown
              v-if="item.source === 1"
              placement="top-end"
              trigger="click"
              active-color="#71b73c"
            >
              <!--            <Io5EllipsisHorizontalSharp />-->
              <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="editItem(item)">编辑</el-dropdown-item>
                  <el-dropdown-item @click="saveTemplate(item)">存为模板</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <!--        </el-space>-->
          </div>
        </div>
      </van-list>
    </div>
    <NewSurvey></NewSurvey>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getSurveysPage, copySurveys, deleteSurveys, saveTemplates } from '@/api/home/index.js';
import { finish } from '@/api/survey/index.js';
import { showDialog, showConfirmDialog, showFailToast, showSuccessToast, showToast } from 'vant';
import { useRouter } from 'vue-router';
import NewSurvey from '@/views/Home/components/NewSurvey/index.vue';
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';
const router = useRouter();
const survey = ref([]);
const total = ref(0);
const loading = ref(false);
const finished = ref(false);
const form = ref({
  page: 0,
  pageSize: 10,
  project_name: ''
});

const searchValue = ref('');

const blurs = () => {
  form.value.page = 1;
  form.value.project_name = searchValue.value;
  survey.value = [];
  fetchSurveys();
};
const onLoad = () => {
  // 异步更新数据
  setTimeout(() => {
    form.value.page = form.value.page + 1;
    fetchSurveys();
  }, 500);
};
const fetchSurveys = async () => {
  const params = {
    page: form.value.page,
    per_page: form.value.pageSize,
    group_id: 0,
    project_name: searchValue.value
  };
  const res = await getSurveysPage(params);
  if (res.data.code === 0) {
    survey.value = survey.value.concat(res.data.data);
    total.value = res.data.meta.total;
    survey.value.forEach((item) => {
      const sceneName = JSON.parse(JSON.stringify(item.scene_name));
      const nameList = sceneName.split('-');
      if (nameList.length > 0) {
        item.scene_name = nameList[1] ? nameList[1] : nameList[0];
      }

      const timeList = item.created_at.split(' ');
      if (nameList.length) {
        item.created_at = timeList[0];
      }
    });
    loading.value = false;
    // 数据全部加载完成
    if (survey.value.length >= total.value) {
      finished.value = true;
    }
  } else {
    // Toast()
  }
};
const deleteItem = (item) => {
  showDialog({
    title: `确认删除问卷${item.project_name} ?`,
    showCancelButton: true,
    confirmButtonColor: '#03B03C'
  })
    .then(async () => {
      const res = await deleteSurveys(item.sn);
      if (res.data.message) {
        showToast(res.data.message);
      } else {
        showToast('删除成功！');
      }
      form.value.page = 1;
      survey.value = [];
      await fetchSurveys();
    })
    .catch(() => {
      if (res.data.message) {
        showToast(res.data.message);
      }
    });
};
const copyItem = (item) => {
  showDialog({
    title: `确认复制问卷${item.project_name} ?`,
    showCancelButton: true,
    confirmButtonColor: '#03B03C'
  })
    .then(async () => {
      const res = await copySurveys(item.sn);
      if (res.data.code === 200 || res.data.code === 201) {
        showSuccessToast('复制成功');
        form.value.page = 1;
        survey.value = [];
        await fetchSurveys();
      } else {
        showFailToast(res.data);
      }
    })
    .catch(() => {
      // on cancel
    });
};
const toPreview = (item) => {
  router.push({
    path: '/preview',
    query: {
      sn: item.sn,
      name: item.project_name,
      source: 0
    }
  });
};
const toPublish = (item) => {
  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
      }
    });
  }
};
const editItem = (item) => {
  router.push({
    path: '/create',
    query: {
      sn: item.sn
    }
  });
};
// 保存为模板
const saveTemplate = async (item) => {
  const data = JSON.parse(JSON.stringify(item));
  const res = await saveTemplates(item.sn, data);
  if (res.data.code === 200 || res.data.code === 201) {
    showConfirmDialog({
      message: '模板保存成功，请前往模板市场查看！',
      showCancelButton: false
    });
  } else {
    showFailToast(res.data);
  }
};
const setImg = (code) => {
  const imageMap = {
    11: png11,
    13: png13,
    14: png14,
    15: png15,
    16: png16,
    17: png17,
    18: png18,
    31: png31
  };
  // 默认返回 png11 如果 code 不存在
  return imageMap[code] || png11;
};
onMounted(() => {
  // fetchSurveys();
});
</script>

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

.el-dropdown-menu__item:not(.is-disabled):focus,
.el-dropdown-menu__item:not(.is-disabled):hover {
  background-color: #000;
}

.survey-search {
  position: sticky;
  top: 0;
  z-index: 1000;
  width: 100%;
  padding: 0;
  background-color: $theme-color;
}

.new-survey-container {
  //min-height: calc(100vh - 100px);
  //padding: 1px;

  //background: linear-gradient(to bottom, $theme-color 200px, #f2f2f2 300px);

  .new-survey_item {
    margin: 0 10px 10px;
    padding: 10px 0 8px 7px;
    border-radius: 8px;
    background-color: white;

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

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

      .survey_item_status {
        position: absolute;
        top: -16px;
        right: -10px;

        .survey_item_info_status_text {
          height: 12px;
          color: rgba(206, 206, 206, 1);

          //font-family: TBMCYXT;
          font-weight: normal;
          font-size: 11px;
          line-height: 13px;
          letter-spacing: 1.0083px;
          text-align: left;
          white-space: nowrap;
          overflow-wrap: break-word;
        }
      }

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

        & > :nth-child(2) {
          position: relative;
          left: 10px;
          padding: 1px 3px;
          border: 2px solid #f5f5f5;
          border-radius: 6px;
          font-size: 12px;
        }
      }

      .survey_item_info_desc {
        //padding: 7px 9px 6px;
        border-radius: 8px;
        //background-color: rgba(246, 247, 248, 0.5);

        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        box-sizing: border-box;
        margin: 0 10px 10px 10px;
        //padding: 8px;
        //border-radius: 8px;
        //background: #f6f7f8;
        color: #828282;
        font-weight: 400;
        font-style: normal;
        font-size: 12px;

        .el-text {
          width: 323px;
          height: 32px;
          color: rgba(130, 130, 130, 1);

          //font-family: PingFangSC-Regular;
          font-weight: normal;
          font-size: 12px;
          line-height: 16px;
          text-align: left;
          overflow-wrap: break-word;
        }
      }
    }

    .survey_item_action {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 5px;
      border-top: 1px dashed #f5f5f5;

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

      .el-space {
        display: flex;
        justify-content: space-evenly;
      }
    }
  }

  .new-survey_item + .new-survey_item {
    margin: 0 10px 10px;
  }
}
</style>
