<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { getSmartCabinetList, type SmartCabinetDTO } from "@/api/cabinet/smart-cabinet";
import { type PaginationProps } from "@pureadmin/table";
import { CommonUtils } from "@/utils/common";
import { useRouter } from "vue-router";
import { CabinetImgMap } from "@/utils/cabinetImgMap";
import { getShopListApi, type ShopDTO } from "@/api/shop/shop";

import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import View from "@iconify-icons/ep/view";
import AddFill from "@iconify-icons/ri/add-circle-line";
import SmartCabinetCardFormModal from "./smart-cabinet-card-form-modal.vue";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { getModeText } from "@/api/shop/shop";
import { useBtnPermissionStore } from "@/store/modules/btnPermission";
import { useWxStore } from "@/store/modules/wx";
const { VITE_PUBLIC_IMG_PATH: IMG_PATH } = import.meta.env;

defineOptions({
  name: "SmartCabinetCard"
});

const router = useRouter();
const wxStore = useWxStore();
const { hasPermission } = useBtnPermissionStore();
const formRef = ref();
const modalVisible = ref(false);
const searchFormParams = ref({
  cabinetName: "",
  cabinetType: null,
  shopId: null,
  corpid: wxStore.corpid
});

const pageLoading = ref(false);
const dataList = ref<SmartCabinetDTO[]>([]);
const shopList = ref<ShopDTO[]>([]);
const pagination = ref<PaginationProps>({
  total: 0,
  pageSize: 12,
  currentPage: 1,
  background: true
});

async function onSearch() {
  pagination.value.currentPage = 1;
  getList();
}

async function getList() {
  try {
    pageLoading.value = true;
    const { data } = await getSmartCabinetList({
      ...searchFormParams.value,
      corpid: wxStore.corpid,
      pageSize: pagination.value.pageSize,
      pageNum: pagination.value.currentPage
    });
    dataList.value = data.rows;
    pagination.value.total = data.total;
  } finally {
    pageLoading.value = false;
  }
}

async function getShopList() {
  try {
    const { data } = await getShopListApi();
    shopList.value = data;
  } catch (error) {
    console.error("获取店铺列表失败", error);
  }
}

const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  onSearch();
};

const handleViewDetail = (row: SmartCabinetDTO) => {
  // 保存信息到标签页
  useMultiTagsStoreHook().handleTags("push", {
    path: `/cabinet/card/detail`,
    name: "smartCabinetCardDetail",
    query: { id: row.cabinetId },
    meta: {
      title: `${row.cabinetName}`,
      dynamicLevel: 3
    }
  });
  router.push({
    path: '/cabinet/card/detail',
    query: {
      id: row.cabinetId
    }
  });
};

onMounted(() => {
  getList();
  getShopList();
});
</script>

<template>
  <div class="main">
    <div class="float-right w-full">
      <el-form ref="formRef" :inline="true" :model="searchFormParams"
        class="search-form bg-bg_color flex w-[99/100] pl-[22px] pt-[12px]">
        <el-form-item label="" prop="cabinetName">
          <el-input @keydown.enter.prevent="onSearch" v-model="searchFormParams.cabinetName" placeholder="请输入柜体名称"
            clearable class="!w-[200px]" />
        </el-form-item>
        <el-form-item label="" prop="shopId">
          <el-select v-model="searchFormParams.shopId" placeholder="请选择机柜地址" clearable class="!w-[180px]">
            <el-option v-for="shop in shopList" :key="shop.shopId" :label="shop.shopName" :value="shop.shopId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="useRenderIcon(Search)" :loading="pageLoading" @click="onSearch">
            搜索
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
            重置
          </el-button>
        </el-form-item>
        <el-form-item class="space-item">
        </el-form-item>
        <el-form-item>
          <el-button v-if="hasPermission('shop:cabinet:write')" type="primary" :icon="useRenderIcon(AddFill)" @click="modalVisible = true"
            style="margin-right: 10px;">
            新增设备
          </el-button>
        </el-form-item>
      </el-form>

      <div class="grid-container">
        <el-row :gutter="12">
          <el-col v-for="(item, index) in dataList" :key="item.cabinetId" :xs="24" :sm="12" :md="8" :lg="4" :xl="4">
            <el-card class="cabinet-card" :body-style="{ padding: '8px 10px' }">
              <div class="card-content">
                <img :src="`${IMG_PATH}img/cabinet/${CabinetImgMap[item.templateNo]?.img || 'default.jpg'}`"
                  class="cabinet-image" />
                <el-descriptions class="cabinet-info" :column="1">
                  <el-descriptions-item class="name">模式：{{ getModeText(item.mode) }}
                  </el-descriptions-item>
                  <!-- <div class="type">柜体类型：{{ item.cabinetType === 0 ? '主柜' : '副柜' }}</div> -->
                  <el-descriptions-item class="template">格式：{{ CabinetImgMap[item.templateNo]?.name || '-' }}
                  </el-descriptions-item>
                  <el-descriptions-item class="shop">已用：{{ item.usedCells }}
                  </el-descriptions-item>
                  <el-descriptions-item class="shop">未用：{{ item.availableCells }}
                  </el-descriptions-item>
                  <el-descriptions-item class="shop">柜址：{{ item.shopName || '-' }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>
              <el-divider class="divider" />
              <el-button class="detail-btn" link @click="handleViewDetail(item)">
                {{ item.cabinetName }}
              </el-button>
            </el-card>
          </el-col>
        </el-row>
        <div class="pagination-wrapper">
          <el-pagination background layout="prev, pager, next" :page-size="pagination.pageSize"
            :total="pagination.total" v-model:current-page="pagination.currentPage" @current-change="getList"
            @size-change="getList" />
        </div>
      </div>
    </div>
    <el-drawer v-model="modalVisible" title="新增智能柜" size="30%" direction="rtl">
      <smart-cabinet-card-form-modal v-model="modalVisible" @refresh="getList" />
    </el-drawer>
  </div>
</template>

<style scoped lang="scss">
.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
    margin-right: 12px;
  }
}

:deep(.el-descriptions__cell) {
  padding-bottom: 1px !important;
}

.cabinet-card {
  margin-bottom: 12px;
  min-height: 210px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .cabinet-image {
    width: 55%;
    height: 200px;
    object-fit: contain;
    border-radius: 4px;
    margin-bottom: 10px;
  }

  .card-content {
    flex: 1;
    margin: 0px;
    display: flex;
    flex-direction: row;

    .cabinet-info {
      text-align: left;
      padding: 16px 0px;

      .name,
      .type,
      .shop,
      .location,
      .template {
        width: 100%;
        font-size: 14px;
        color: #606266;
        margin-bottom: 12px;
        line-height: 1;
        text-align: left;
      }

      .name {
        width: 100%;
        font-weight: 500;
        color: #303133;
      }
    }
  }

  .divider {
    margin: 5px 0px;
  }

  .detail-btn {
    width: 100%;
    border: 0;
    margin-top: auto;
    padding: 8px 0;

    &:hover {
      color: var(--el-color-primary);
    }
  }
}

.grid-container {
  margin: 12px 0;
  position: relative;

  .el-row {
    margin-bottom: -20px;
  }
}

.pagination-wrapper {
  position: relative;
  background: var(--el-bg-color);
  padding: 8px 12px;
  margin-top: 20px;
  text-align: center;

  :deep(.el-pagination) {
    margin: 0;
    padding: 4px 0;
  }
}

.space-item {
  flex: 1;
  width: 100%;
}
</style>