<template>
  <div class="apk-management-page">
    <!-- 自定义头部 -->
    <s-header
      :name="$t('apkManage.apkManagement')"
      :noback="false"
      class="management-header"
    />

    <!-- 操作栏 -->
    <div class="action-bar">
      <div v-if="isDelete" class="delete-mode-bar">
        <div class="selected-count">
          <van-icon name="checked" color="#df5e4c" />
          <span>{{ $t("advertManage.advertRule.selected") }}</span>
          <span class="count-highlight">{{ selectTotals }}</span>
          <span>{{ $t("advertManage.advertRule.individual") }}</span>
        </div>
        <div class="action-buttons">
          <van-button round size="small" class="cancel-btn" @click="cancelClk">
            {{ $t("advertManage.advertRule.cancel") }}
          </van-button>
          <van-button
            round
            size="small"
            type="danger"
            class="delete-btn"
            @click="noticeClk"
          >
            {{ $t("advertManage.advertRule.confirmDel") }}
          </van-button>
        </div>
      </div>

      <div v-else class="normal-mode-bar">
        <div class="total-info">
          <van-icon name="description" color="#4d6add" />
          <span class="total-text">{{
            $t("advertManage.advertRule.total")
          }}</span>
          <span class="total-count">{{ ruleTotal }}</span>
          <span class="total-text">{{ $t("alarmHistory.recordsTotal") }}</span>
        </div>

        <div class="action-icons" v-if="user.type === 0">
          <div class="action-item" @click="toAdd">
            <van-button
              icon="plus"
              size="small"
              class="add-btn"
              @click="toAdd"
              color="#4d6add"
            >
              {{ $t("advertManage.advertRule.add") }}
            </van-button>
          </div>
          <div class="action-item" @click="isDelete = true">
            <van-button
              icon="delete"
              size="small"
              type="danger"
              plain
              class="delete-btn"
              @click="isDelete = true"
            >
              {{ $t("advertManage.advertRule.delete") }}
            </van-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 设备类型标签 -->
    <div class="model-tabs">
      <van-tabs
        v-model:active="active"
        @click-tab="clickModel"
        animated
        swipeable
      >
        <van-tab :title="$t('device.whole')" name="" />
        <van-tab
          v-for="item in modelList"
          :key="item.id"
          :title="item.name"
          :name="item.id"
        />
      </van-tabs>
    </div>

    <!-- 内容区域 -->
    <div class="content-container">
      <van-list
        v-model="loading"
        :finished="finished"
        :finished-text="$t('common.noMoreTxt')"
        @load="onLoad"
        :offset="20"
      >
        <div
          v-for="item in tableData"
          :key="item.id"
          class="apk-card"
          :class="{ 'card-selected': item.checked }"
        >
          <div class="card-content">
            <div class="apk-info">
              <div class="info-row">
                <van-icon name="info" class="info-icon" />
                <span class="info-label">{{ $t("apkManage.version") }}：</span>
                <span class="info-value">{{ item.version }}</span>
              </div>

              <div class="info-row">
                <van-icon name="info" class="info-icon" />
                <span class="info-label"
                  >{{ $t("apkManage.versionInfo") }}：</span
                >
                <span class="info-value">{{ item.versionName }}</span>
              </div>

              <div class="info-row">
                <van-icon name="phone" class="info-icon" />
                <span class="info-label">{{ $t("apkManage.model") }}：</span>
                <span class="info-value">{{ item.model }}</span>
              </div>

              <div class="info-row">
                <van-icon name="clock" class="info-icon" />
                <span class="info-label"
                  >{{ $t("advertManage.advertRule.createTime") }}：</span
                >
                <span class="info-value">{{
                  Format_time(item.modifyDate)
                }}</span>
              </div>
            </div>

            <div class="card-actions" v-if="user.type === 0">
              <template v-if="isDelete">
                <van-checkbox v-model="item.checked" shape="square" />
              </template>
              <template v-else>
                <van-button
                  round
                  size="small"
                  class="edit-btn"
                  @click="toEdit(item)"
                >
                  <van-icon name="edit" size="14" />
                  {{ $t("advertManage.advertRule.edit") }}
                </van-button>
              </template>
            </div>

            <div class="card-actions">
              <van-button
                round
                size="small"
                class="down-btn"
                @click="copyApkLink(item)"
              >
                <van-icon name="down" size="14" />
                复制apk链接
              </van-button>
            </div>
          </div>
        </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"
    />
  </div>
</template>

<script>
import { Format_time } from "@/common/js/utils";
import kDialog from "@/components/commom/kDialog/index.vue";
// 导入接口
import { Api_getPageApkInfo, Api_getDeletesApk } from "@/service/apkManage";
import { computed, onMounted, reactive, ref, toRefs } from "vue";
import sHeader from "@/components/SimpleHeader";
import { useRouter } from "vue-router";
import { showToast } from "vant";
import { useI18n } from "vue-i18n";
import { getLoginUser, styleUrl } from "../../common/js/utils";
export default {
  components: { sHeader, kDialog },
  setup() {
    const { t } = useI18n();
    const user = getLoginUser();
    // 点击标签
    const active = ref("");
    // 机型列表
    const modelList = ref([
      {
        name: "301",
        id: "301",
      },
      {
        name: "320",
        id: "320",
      },
      {
        name: "280",
        id: "280",
      },
      {
        name: "P10",
        id: "P10",
      },
      {
        name: "P20",
        id: "P20",
      },
      {
        name: "P30",
        id: "P30",
      },
      {
        name: "SI320",
        id: "SI320",
      },
      {
        name: "SBC320",
        id: "SBC320",
      },
      {
        name: "SBM10",
        id: "SBM10",
      },
      {
        name: "EF210",
        id: "EF210",
      },
    ]);
    // 删除确认弹窗
    const kDialogRef = ref(null);
    // 点击确认删除
    const noticeClk = () => {
      if (selectTotals.value < 1) {
        showToast(t("advertManage.delTips"));
        return;
      }
      kDialogRef.value.openDialog();
    };
    // 点击右侧按钮
    const confirmClk = () => {
      const ids = [];
      ruleData.tableData.forEach((item) => {
        if (item.checked) {
          ids.push(item.id);
        }
      });
      let param = {
        ids,
      };
      Api_getDeletesApk(param).then((res) => {
        console.log(res);
        if (res.data.code === "00000") {
          isDelete.value = false;
          showToast(res.data.message);
          setTimeout(() => {
            onRefresh(1);
          }, 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);
    onMounted(() => {
      // 加载样式
      styleUrl("apkManage");
      onRefresh();
    });
    // 下拉刷新
    const onRefresh = (idx) => {
      ruleData.tableData = [];
      // 解决请求两次问题
      if (!idx) {
        finished.value = false;
      }
      loading.value = true;
      // 初始化分页
      pageNo.value = 1;
      pageSize.value = 20;
      getList();
    };
    // 上拉加载
    const onLoad = () => {
      pageNo.value++;
      getList();
    };
    const param = ref({
      current: 1,
      size: 20,
      model: "",
    });
    const getList = () => {
      param.value.current = pageNo.value;
      param.value.size = pageSize.value;
      Api_getPageApkInfo(param.value).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("/apkManageAdd");
    };
    // 点击编辑
    const toEdit = (row) => {
      // 如果是删除模式，则是选中和取消状态
      if (isDelete.value) {
        ruleData.tableData.forEach((item) => {
          if (item.id === row.id) {
            item.checked = !item.checked;
          }
        });
      } else {
        router.push(`/apkManageAdd?row=${JSON.stringify(row)}`);
      }
    };
    // 点击复制链接
    const copyApkLink = (row) => {
      navigator.clipboard.writeText(row.downloadUrl);
      showToast("复制成功");
    };
    // 点击标签
    const clickModel = (item) => {
      console.log(item);
      ruleData.tableData = [];
      pageNo.value = 1;
      param.value.model = item.name;
      getList();
    };
    return {
      pageNo,
      pageSize,
      loading,
      finished,
      refreshing,
      onRefresh,
      onLoad,
      getList,
      ...toRefs(ruleData),
      isDelete,
      selectTotals,
      cancelClk,
      ruleTotal,
      toAdd,
      confirmClk,
      kDialogRef,
      noticeClk,
      toEdit,
      Format_time,
      modelList,
      active,
      clickModel,
      user,
      copyApkLink,
    };
  },
};
</script>

<style lang="less" scoped>
@primary-color: #4d6add;
@danger-color: #df5e4c;
@success-color: #07c160;
@card-bg: #ffffff;
@text-dark: #333;
@text-light: #666;
@border-color: #e4e7ec;
@shadow-color: rgba(77, 106, 221, 0.1);

.apk-management-page {
  min-height: 100vh;
  background-color: #f5f8ff;
  padding-bottom: 20px;
}

.management-header {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.action-bar {
  background-color: @card-bg;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 10;
}

.delete-mode-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 5px;

  .selected-count {
    display: flex;
    align-items: center;
    justify-self: center;
    font-size: 18px;
    color: @text-dark;

    .van-icon {
      margin-right: 6px;
    }

    .count-highlight {
      color: @danger-color;
      font-weight: bold;
      font-size: 20px;
      margin: 0 4px;
    }
  }

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

    .cancel-btn {
      background-color: #f5f7fa;
      color: @text-dark;
      border: none;
    }

    .delete-btn {
      min-width: 80px;
    }
  }
}

.normal-mode-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 5px;

  .total-info {
    display: flex;
    align-items: center;
    justify-self: center;
    font-size: 18px;
    color: @text-dark;

    .van-icon {
      margin-right: 6px;
    }

    .total-text {
      margin: 0 4px;
      font-size: 15px;
    }

    .total-count {
      color: @danger-color;
      font-weight: bold;
      font-size: 20px;
    }
  }

  .action-icons {
    display: flex;
    gap: 10px;

    .action-item {
      display: flex;
      // flex-direction: column;
      align-items: center;
      cursor: pointer;

      .action-label {
        font-size: 15px;
        color: @text-light;
      }
    }
  }
}

.model-tabs {
  background-color: @card-bg;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

  :deep(.van-tabs__wrap) {
    padding: 0 16px;
  }

  :deep(.van-tab) {
    font-size: 14px;
    padding: 0 12px;
  }

  :deep(.van-tab--active) {
    color: @primary-color;
    font-weight: bold;
  }
}

.content-container {
  padding: 16px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: @text-light;
  font-size: 14px;

  p {
    margin-top: 12px;
  }
}

.apk-card {
  background-color: @card-bg;
  border-radius: 12px;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px @shadow-color;
  overflow: hidden;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(77, 106, 221, 0.15);
  }

  &.card-selected {
    border-left: 4px solid @danger-color;
  }
}

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

  .apk-info {
    flex: 1;
  }

  .card-actions {
    display: flex;
    align-items: center;
    padding-left: 12px;

    .edit-btn {
      background: linear-gradient(to right, #4d6add, #6a89ff);
      color: white;
      border: none;
      padding: 0 16px;
    }

    .down-btn {
      margin-left: 10px;
      background: linear-gradient(to right, #4d6add, #6a89ff);
      color: white;
      border: none;
      // padding: 0 16px;
    }
  }
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;

  &:last-child {
    margin-bottom: 0;
  }

  .info-icon {
    color: @primary-color;
    margin-right: 8px;
    font-size: 16px;
  }

  .info-label {
    color: @text-light;
    min-width: 80px;
  }

  .info-value {
    color: @text-dark;
    font-weight: 500;
  }
}

.card-footer {
  padding: 10px 16px;
  background-color: #f9fafc;
  border-top: 1px solid @border-color;
}

@media (max-width: 480px) {
  .action-bar {
    padding: 12px;
  }

  .delete-mode-bar {
    gap: 12px;
  }

  .normal-mode-bar {
    gap: 12px;
  }

  .card-content {
    flex-direction: column;

    .card-actions {
      padding-left: 0;
      padding-top: 12px;
      justify-content: flex-end;
    }
  }
}
</style>
