<template>
  <!-- 广告管理页面 -->
  <div class="advert-page">
    <!-- 头部导航 -->
    <s-header
      :name="$t('advertManage.advertisingManagement')"
      :noback="false"
    />

    <!-- 主要内容区域 -->
    <!-- 顶部操作栏 -->
    <div class="top-action-bar" :class="{ 'delete-mode': isDelete }">
      <div class="status-display">
        <template v-if="isDelete">
          <span>{{ $t("advertManage.advertRule.selected") }}</span>
          <span class="count-highlight">{{ selectTotals }}</span>
          <span>{{ $t("advertManage.advertRule.individual") }}</span>
        </template>
        <template v-else>
          <span>{{ $t("advertManage.total") }}</span>
          <span class="count-highlight">{{ adTotal }}</span>
          <span>{{ $t("advertManage.ads") }}</span>
        </template>
      </div>

      <div class="action-buttons">
        <template v-if="isDelete">
          <van-button size="small" class="cancel-btn" @click="cancelClk">
            {{ $t("advertManage.advertRule.cancel") }}
          </van-button>
          <van-button
            size="small"
            type="danger"
            class="confirm-btn"
            @click="noticeClk"
          >
            {{ $t("advertManage.advertRule.confirmDel") }}
          </van-button>
        </template>
        <template v-else>
          <van-button plain size="small" icon="notes-o" @click="pushAdRule">
            {{ $t("advertManage.advertisingRules") }}
          </van-button>
          <van-button type="primary" size="small" icon="plus" @click="pushAdd">
            {{ $t("advertManage.add") }}
          </van-button>
          <van-button plain size="small" icon="delete" @click="isDelete = true">
            {{ $t("advertManage.delete") }}
          </van-button>
        </template>
      </div>
    </div>

    <!-- 广告列表 -->
    <div class="ad-list">
      <van-list
        v-model:loading="loading"
        v-model:error="error"
        :error-text="$t('advertManage.requestFailed')"
        :finished="finished"
        :finished-text="$t('advertManage.noMore')"
        :offset="300"
        :immediate-check="false"
        @load="onLoad"
      >
        <!-- 广告卡片 -->
        <div
          v-for="(item, index) in adList"
          :key="index"
          class="ad-card"
          :class="{ selectable: isDelete }"
        >
          <div class="card-content" @click="isDelete ? null : adUpdate(item)">
            <!-- 广告图片/视频预览 -->
            <div class="media-preview" @click.stop="loadVideo(item)">
              <img
                :src="isAdImgUrl(item)"
                :alt="item.name"
                class="preview-image"
              />
              <div v-if="item.adType === 1" class="video-indicator">
                <van-icon name="play-circle-o" size="24" />
              </div>
            </div>

            <!-- 广告信息 -->
            <div class="ad-info">
              <div class="ad-title">{{ item.name }}</div>

              <div class="info-row">
                <span class="info-label"
                  >{{ $t("advertManage.locationType") }}：</span
                >
                <span class="info-value">
                  {{
                    item.locationType === 0
                      ? $t("advertManage.advertising")
                      : $t("advertManage.externalAdvertising")
                  }}
                </span>
              </div>

              <div class="info-row">
                <span class="info-label"
                  >{{ $t("advertManage.advertisingPosition") }}：</span
                >
                <span class="info-value">
                  {{
                    item.screenType === 0
                      ? $t("advertManage.screenA")
                      : $t("advertManage.screenB")
                  }}
                </span>
              </div>

              <div class="info-row">
                <span class="info-label"
                  >{{ $t("advertManage.advertisingType") }}：</span
                >
                <span class="info-value">
                  {{
                    item.adType === 0
                      ? $t("advertManage.picture")
                      : $t("advertManage.video")
                  }}
                </span>
              </div>

              <div class="info-row">
                <span class="info-label"
                  >{{ $t("advertManage.creationTime") }}：</span
                >
                <span class="info-value">{{
                  showDateTime(item.createDate)
                }}</span>
              </div>
            </div>
          </div>

          <!-- 选择框 (删除模式下显示) -->
          <van-checkbox
            v-if="isDelete"
            v-model="item.checked"
            class="selection-checkbox"
            @click.stop
          />
        </div>
      </van-list>
    </div>
    <!-- 视频预览弹窗 -->
    <van-popup v-model:show="showVideo" round class="video-popup">
      <video ref="video" controls class="video-player" :src="videoUrl"></video>
    </van-popup>
  </div>

</template>

<script>
import { getAdList, Api_getDelAd } from "@/service/advertManage";
import { onMounted, reactive, ref, computed } from "vue";
import sHeader from "@/components/SimpleHeader";
import { showConfirmDialog, showFailToast, showToast } from "vant";
import dateUtil from "@/utils/dateUtil";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";

export default {
  components: { sHeader },
  setup() {
    const { t } = useI18n();
    // 删除确认弹窗
    const showVideo = ref(false);
    const videoUrl = ref("");
    const kDialogRef = ref(null);
    const confirmClk = () => {
      const ids = [];
      adList.value.forEach((item) => {
        if (item.checked) {
          ids.push(item.id);
        }
      });
      let param = {
        ids,
      };
      Api_getDelAd(param).then((res) => {
        if (res.data.code === "00000") {
          isDelete.value = false;
          showToast(res.data.message);
          setTimeout(() => {
            Init();
          }, 500);
        }
      });
    };
    // 点击确认删除
    const noticeClk = () => {
      if (selectTotals.value < 1) {
        showToast(t("advertManage.delTips"));
        return;
      }
      // kDialogRef.value.openDialog();
      showConfirmDialog({
        title: t("advertManage.delPopTitle"),
        message: t("advertManage.delPopContent"),
        onConfirm: () => {
          confirmClk();
        },
      });
    };

    const router = useRouter();
    const adList = ref([]);
    const adTotal = ref("");
    const pushAdRule = () => {
      router.push("/advertRule");
    };
    const pushAdd = () => {
      localStorage.removeItem("adverInfo");
      router.push({ path: "advertSet" });
    };
    let searchParams = reactive({ current: 1, size: 20 });
    const loading = ref(false);
    const error = ref(false);
    const finished = ref(false);
    // 初始化页面获取列表
    onMounted(async () => {
      // 加载样式
      Init();
    });
    const Init = () => {
      adList.value = [];
      searchParams.current = 1;
      loading.value = true;
      getAdListFun();
    };
    const onLoad = () => {
      if (!finished.value) {
        searchParams.current = searchParams.current + 1;
        loading.value = true;
        getAdListFun();
      }
    };
    // 获取广告列表
    const getAdListFun = async () => {
      const params = Object.assign({}, searchParams);
      const { data } = await getAdList(params);
      loading.value = false;
      if (data.code === "00000") {
        // 加入删除选中状态
        if (data.data.records.length > 0) {
          data.data.records.forEach((item) => {
            item.checked = false;
          });
        }
        adList.value = adList.value.concat(data.data.records);
        adTotal.value = data.data.total;
        if (adList.value.length === data.data.total) {
          finished.value = true;
        }
      } else {
        showFailToast(data.message);
      }
    };
    // const videoRef = ref(null);
    const loadVideo = (item) => {
      console.log("item>>", item);
      showVideo.value = true;
      videoUrl.value = item.url;
    };

    const isAdImgUrl = (item) => {
      return item.adType === 1
        ? item.mediaPreview
          ? item.mediaPreview
          : require("../../assets/start.png")
        : item.url;
      // return require('../../assets/start.png');
    };
    const showDateTime = (date) => {
      return date
        ? dateUtil.formateDate(new Date(date), "yyyy/MM/dd hh:mm:ss")
        : "";
    };
    const adUpdate = (item) => {
      // 如果是删除模式，则是选中和取消状态
      if (isDelete.value) {
        adList.value.forEach((row) => {
          if (row.id === item.id) {
            row.checked = !row.checked;
          }
        });
      } else {
        localStorage.setItem("adverInfo", JSON.stringify(item));
        router.push({ path: "advertSet" });
      }
    };
    // 删除操作
    // 是否删除状态
    const isDelete = ref(false); // 选中
    const selectTotals = computed(() => {
      let nums = 0;
      if (adList.value.length > 0) {
        adList.value.forEach((item) => {
          if (item.checked) {
            nums++;
          }
        });
      }
      return nums;
    });
    // 点击取消删除
    const cancelClk = () => {
      // 把选中状态去掉
      if (adList.value.length > 0) {
        adList.value.forEach((item) => {
          if (item.checked) {
            item.checked = false;
          }
        });
      }
      isDelete.value = false;
    };
    return {
      adList,
      adTotal,
      pushAdRule,
      pushAdd,
      loading,
      error,
      finished,
      onLoad,
      isAdImgUrl,
      showDateTime,
      adUpdate,
      isDelete,
      selectTotals,
      cancelClk,
      noticeClk,
      kDialogRef,
      confirmClk,
      showVideo,
      loadVideo,
      videoUrl,
    };
  },
};
</script>

<style lang="less" scoped>
@primary-color: #4d6add;

.advert-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.advert-container {
  background: #f5f6fa;
  height: calc(100% - 50px);
  overflow: auto;
  overflow-x: hidden;
}

// 顶部操作栏
.top-action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  margin: 12px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  &.delete-mode {
    background-color: #fff8f6;
  }

  .status-display {
    font-size: 15px;
    color: #666;

    .count-highlight {
      font-size: 18px;
      font-weight: bold;
      color: @primary-color;
      margin: 0 3px;
    }
  }

  .action-buttons {
    display: flex;
    gap: 8px;

    .cancel-btn {
      border: 1px solid #dcdee0;
    }

    .confirm-btn {
      background: linear-gradient(to right, #ff7062, #df5e4c);
    }
  }
}

.ad-list {
  flex: 1;
  overflow-y: auto;
}

// 广告卡片
.ad-card {
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  margin: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;

  &.selectable {
    cursor: pointer;

    &:hover {
      background-color: #fafafa;
    }
  }

  .card-content {
    display: flex;
    padding: 16px;
    cursor: pointer;
  }

  .selection-checkbox {
    position: absolute;
    top: 16px;
    right: 16px;
    z-index: 2;
  }

  .media-preview {
    position: relative;
    width: 100px;
    height: 100px;
    border-radius: 8px;
    overflow: hidden;
    flex-shrink: 0;
    margin-right: 12px;
    cursor: pointer;

    .preview-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
      background-color: #f0f2f5;
    }

    .video-indicator {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: rgba(0, 0, 0, 0.2);
      color: white;
    }
  }

  .ad-info {
    flex: 1;
    min-width: 0;

    .ad-title {
      font-size: 15px;
      font-weight: bold;
      color: #333;
      margin-bottom: 10px;
    }

    .info-row {
      display: flex;
      font-size: 13px;
      color: #666;
      margin-bottom: 6px;
      line-height: 1.4;

      .info-label {
        color: #999;
        flex-shrink: 0;
      }

      .info-value {
        flex: 1;
      }
    }
  }
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  background-color: white;
  border-radius: 12px;

  .empty-text {
    color: #999;
    font-size: 14px;
    margin: 15px 0 20px;
  }
}

// 视频弹窗
.video-popup {
  width: 85vw;
  max-width: 800px;

  .video-player {
    width: 100%;
    height: 50vw;
    max-height: 500px;
    background-color: #000;
  }
}

// 响应式适配
@media (max-width: 480px) {
  .top-action-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
    padding: 12px;

    .action-buttons {
      justify-content: space-between;
    }
  }

  .ad-card {
    .card-content {
      padding: 12px;
    }

    .media-preview {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 110px;
      height: 110px;
    }

    .ad-title {
      font-size: 14px;
    }

    .info-row {
      font-size: 12px;
    }
  }

  .video-popup {
    width: 95vw;
  }
}
</style>
