<template>
  <div class="advert-rule-page">
    <!-- 头部导航 -->
    <s-header :name="$t('advertManage.advertRule.sysTitle')" :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.advertRule.total") }}</span>
          <span class="count-highlight">{{ ruleTotal }}</span>
          <span>{{ $t("advertManage.advertRule.rules") }}</span>
        </template>
      </div>

      <div class="action-buttons">
        <template v-if="isDelete">
          <van-button size="small" @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 size="small" icon="plus" type="primary" @click="toAdd">
            {{ $t("advertManage.advertRule.add") }}
          </van-button>
          <van-button size="small" plain icon="delete" @click="isDelete = true">
            {{ $t("advertManage.advertRule.delete") }}
          </van-button>
        </template>
      </div>
    </div>

    <!-- 规则列表 -->
    <div class="rules-list-container">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        :finished-text="$t('common.noMoreTxt')"
        :offset="20"
        :immediate-check="false"
        @load="onLoad"
      >
        <div
          v-for="item in tableData"
          :key="item.id"
          class="rule-card"
          @click="!isDelete ? toEdit(item) : null"
        >
          <div class="card-content">
            <div class="rule-info">
              <div class="rule-name">{{ item.name }}</div>
              <div class="create-date">
                <span class="date-label"
                  >{{ $t("advertManage.advertRule.createTime") }}：</span
                >
                <span class="date-value">{{
                  Format_time(item.createDate)
                }}</span>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="action-buttons">
              <template v-if="!isDelete">
                <van-button
                  size="small"
                  class="push-btn"
                  @click.stop="pushRuleClk(item.id)"
                >
                  {{ $t("advertManage.advertRule.push") }}
                </van-button>
                <van-button
                  size="small"
                  plain
                  class="edit-btn"
                  @click.stop="toEdit(item)"
                >
                  {{ $t("advertManage.advertRule.edit") }}
                </van-button>
              </template>

              <template v-else>
                <van-checkbox
                  v-model="item.checked"
                  class="delete-checkbox"
                  @click.stop
                />
              </template>
            </div>
          </div>
        </div>
      </van-list>
    </div>
  </div>
</template>

<script>
import { useStore } from "vuex";
import { Format_time } from "../../../common/js/utils";
// 导入接口
import {
  Api_postPageTimeRule,
  Api_getPushAdRule,
  Api_getDelAdRule,
} from "../../../service/advertManage";
import { computed, onMounted, reactive, ref, toRefs } from "vue";
import sHeader from "../../../components/SimpleHeader";
import { useRouter } from "vue-router";
import { showConfirmDialog, showToast } from "vant";
import { useI18n } from "vue-i18n";
export default {
  components: { sHeader },
  setup() {
    const { t } = useI18n();
    // 删除确认弹窗
    const kDialogRef = ref(null);
    // 点击确认删除
    const noticeClk = () => {
      if (selectTotals.value < 1) {
        showToast(t("advertManage.delTips"));
        return;
      }
      showConfirmDialog({
        title: t("advertManage.delPopTitle"),
        message: t("advertManage.delPopContent"),
        confirmButtonText: t("advertManage.confirmDel"),
        cancelButtonText: t("advertManage.cancelTxt"),
        onConfirm: () => {
          confirmClk();
        },
        onCancel: () => {
          cancelClk();
        },
      });
    };
    // 点击右侧按钮
    const confirmClk = () => {
      const ids = [];
      ruleData.tableData.forEach((item) => {
        if (item.checked) {
          ids.push(item.id);
        }
      });
      let param = {
        ids,
      };
      Api_getDelAdRule(param).then((res) => {
        console.log(res);
        if (res.data.code === "00000") {
          isDelete.value = false;
          showToast(res.data.message);
          setTimeout(() => {
            onRefresh();
          }, 500);
        }
      });
    };
    // 是否删除状态
    const isDelete = ref(false);
    // 选中
    const selectTotals = computed(() => {
      let nums = 0;
      if (ruleData.tableData.length > 0) {
        ruleData.tableData.forEach((item) => {
          if (item.checked) {
            nums++;
          }
        });
      }
      return nums;
    });
    // 点击取消删除
    const cancelClk = () => {
      // 把选中状态去掉
      if (ruleData.tableData.length > 0) {
        ruleData.tableData.forEach((item) => {
          if (item.checked) {
            item.checked = false;
          }
        });
      }
      isDelete.value = false;
    };
    // 多少条规则
    const ruleTotal = ref(0);
    // 分页
    const pageNo = ref(1);
    const pageSize = ref(20);
    let ruleData = reactive({
      tableData: [],
    });
    // 上拉刷新
    const loading = ref(true);
    const finished = ref(false);
    // 下拉刷新
    const refreshing = ref(false);
    // 导入vuex
    const store = useStore();
    onMounted(() => {
      // 加载样式
      onRefresh();
      // 初始化
      init();
    });
    const init = () => {
      // 储存数据到vuex
      store.commit("MUTA_A_ADVERTLIST", []);
      store.commit("MUTA_B_ADVERTLIST", []);
      localStorage.removeItem("advertManage-A-advertList");
      localStorage.removeItem("advertManage-B-advertList");
    };
    // 下拉刷新
    const onRefresh = () => {
      ruleData.tableData = [];
      finished.value = false;
      loading.value = true;
      // 初始化分页
      pageNo.value = 1;
      pageSize.value = 20;
      getList();
    };
    // 上拉加载
    const onLoad = () => {
      pageNo.value++;
      getList();
    };
    const getList = () => {
      let param = {
        current: pageNo.value,
        size: pageSize.value,
      };
      Api_postPageTimeRule(param).then((res) => {
        const { data } = res.data;
        refreshing.value = false;
        // 加入删除选中状态
        if (data.records.length > 0) {
          data.records.forEach((item) => {
            item.checked = false;
          });
        }
        ruleData.tableData.push(...data.records);
        // 加载状态结束
        loading.value = false;
        // 总共
        ruleTotal.value = data.total;
        if (ruleData.tableData.length >= data.total) {
          finished.value = true;
        }
      });
    };
    const router = useRouter();
    // 点击添加按钮
    const toAdd = () => {
      router.push("/advertRuleAdd");
    };
    // 点击推送按钮
    const pushRuleClk = (id) => {
      Api_getPushAdRule({ id }).then((res) => {
        if (res.data.code === "00000") {
          showToast("推送成功");
        }
      });
    };
    // 点击编辑
    const toEdit = (row) => {
      // 如果是删除模式，则是选中和取消状态
      if (isDelete.value) {
        ruleData.tableData.forEach((item) => {
          if (item.id === row.id) {
            item.checked = !item.checked;
          }
        });
      } else {
        router.push(`/advertRuleAdd?id=${row.id}`);
      }
    };
    return {
      pageNo,
      pageSize,
      loading,
      finished,
      refreshing,
      onRefresh,
      onLoad,
      getList,
      ...toRefs(ruleData),
      isDelete,
      selectTotals,
      cancelClk,
      ruleTotal,
      toAdd,
      pushRuleClk,
      confirmClk,
      kDialogRef,
      noticeClk,
      toEdit,
      Format_time,
    };
  },
};
</script>

<style lang="less" scoped>
@primary-color: #4d6add;
@error-color: #f56c6c;
@text-color: #333;
.advert-rule-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.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);
    }
  }
}

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

.rule-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 12px;
  transition: all 0.2s;
  overflow: hidden;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }

  .card-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;

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

      .rule-name {
        font-size: 15px;
        font-weight: bold;
        color: #333;
        margin-bottom: 8px;
      }

      .create-date {
        font-size: 13px;
        color: #666;

        .date-label {
          color: #999;
        }
      }
    }

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

      .push-btn {
        background-color: @primary-color;
        color: white;
        min-width: 60px;
      }

      .edit-btn {
        color: @text-color;
        border-color: #dcdee0;
        min-width: 60px;
      }
    }
  }
}

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

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

@media (max-width: 480px) {
  .top-action-bar {
    display: flex;
    justify-content: space-between;
    .action-buttons {
      justify-content: space-between;
      display: flex;
      gap: 10px;
    }
  }

  .rules-list-container {
    padding: 12px;
  }

  .rule-card {
    .card-content {
      padding: 12px;

      .rule-info {
        .rule-name {
          font-size: 14px;
        }

        .create-date {
          font-size: 12px;
        }
      }

      .action-buttons {
        flex-direction: column;
        gap: 6px;

        .push-btn,
        .edit-btn {
          min-width: 50px;
          padding: 0 8px;
        }
      }
    }
  }
}
</style>
