<template>
  <!-- 广告管理 -->
  <div class="advertPage flex-col">
    <s-header :name="$t('advertManage.advertisingManagement')" :noback="false"></s-header>
    <div class="advertBox flex-col">
      <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-if="isDelete" class="l-flex-between o-plr-20 o-pt-16 o-pb-6 kBordBott">
          <div class="l-flex-RC c-text-15 c-text-color c-text-b">
            {{ $t("advertManage.advertRule.selected") }}
            {{ selectTotals }}
            {{ $t("advertManage.advertRule.individual") }}
          </div>
          <div class="l-flex-RC">
            <div @click="cancelClk" class="c-text-c c-text-13 c-color">
              {{ $t("advertManage.advertRule.cancel") }}
            </div>
            <div @click="noticeClk" class="c-text-c o-ml-24 c-text-13" style="color: #df5e4c">
              {{ $t("advertManage.advertRule.confirmDel") }}
            </div>
          </div>
        </div>
        <div v-else class="searchRow l-flex-between o-plr-20 o-pt-16 o-pb-6 kBordBott">
          <div class="flex-col">
            <div class="flex-row justify-between bd3">
              <div class="flex-col outer4"></div>
              <span class="flex-col txt2 o-ml-10">{{ $t("advertManage.total")
              }}<span class="discountNumber">{{ adTotal }}</span>{{ $t("advertManage.ads") }}</span>
            </div>
          </div>
          <div class="flex-col">
            <div class="operBox">
              <div class="listBox" @click="pushAdRule()">
                <img class="iconImg" src="../../assets/accountPer/listIcon.png" />
                <span>{{ $t("advertManage.advertisingRules") }}</span>
              </div>
              <div class="addBox" @click="pushAdd()">
                <img class="iconImg" src="../../assets/accountPer/addicon.png" />
                <span>{{ $t("advertManage.add") }}</span>
              </div>
              <div @click="isDelete = true" class="searchBox">
                <img class="iconImg" src="../../assets/advertManage/closeIcon.png" />
                <span>{{ $t("advertManage.delete") }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="l-flex-between" v-for="(item, index) in adList" :key="index">
          <div class="adList" @click="adUpdate(item)">
            <img class="adImg o-mr-10" :src="isAdImgUrl(item)" />
            <div class="adInfoBox c-text-12">
              <div class="adTitle c-text-15 c-text-color o-mb-14">
                {{ item.name }}
              </div>
              <div class="adRow">
                <span class="adLeft">{{ $t("advertManage.locationType") }}：</span>{{
                  item.locationType === 0
                  ? $t("advertManage.advertising")
                  : $t("advertManage.externalAdvertising")
                }}
              </div>
              <div class="adRow">
                <span class="adLeft">{{ $t("advertManage.advertisingPosition") }}：</span>{{
                  item.screenType === 0
                  ? $t("advertManage.screenA")
                  : $t("advertManage.screenB")
                }}
              </div>
              <div class="adRow">
                <span class="adLeft">{{ $t("advertManage.advertisingType") }}：</span>{{
                  item.adType === 0
                  ? $t("advertManage.picture")
                  : $t("advertManage.video")
                }}
              </div>
              <div class="adRow">
                <span class="adLeft">{{ $t("advertManage.creationTime") }}：</span>{{ showDateTime(item.createDate) }}
              </div>
            </div>
          </div>
          <template v-if="isDelete">
            <van-checkbox v-model="item.checked">{{ " " }}</van-checkbox>
          </template>
        </div>
      </van-list>
    </div>
    <!-- 删除确认弹窗 -->
    <kDialog :dialogTitle="$t('advertManage.delPopTitle')" :cancelBtnTxt="$t('advertManage.cancelTxt')"
      :confirmBtnTxt="$t('advertManage.confirmDel')" ref="kDialogRef" :dialogContent="$t('advertManage.delPopContent')"
      @confirmclk="confirmClk">
    </kDialog>
  </div>
</template>

<script>
import kDialog from "@/components/commom/kDialog/index.vue";
import { getAdList, Api_getDelAd } from "@/service/advertManage";
import { onMounted, reactive, ref, computed } from "vue";
import sHeader from "@/components/SimpleHeader";
import { showFailToast, showToast } from 'vant';
import dateUtil from "@/utils/dateUtil";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { styleUrl } from "../../common/js/utils";

export default {
  components: { sHeader, kDialog },
  setup() {
    const { t } = useI18n();
    // 删除确认弹窗
    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) => {
        console.log(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();
    };

    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 () => {
      // 加载样式
      styleUrl('advertManage');
      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 isAdImgUrl = (item) => {
      return item.adType === 1 ? item.mediaPreview : item.url;
    };
    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,
    };
  },
};
</script>

<style lang="less" scoped>
@import "../../common/style/common.less";
</style>
