<template>
  <div class="dashboard-container" :style="containerStyle">
    <main class="main-content">
      <!-- 左侧区域 -->
      <div class="left-section">
        <!-- 左侧上部分 -->
        <div class="left-top">
          <!-- 区域信息概览 -->
          <div class="info-card region-overview">
            <searchtop :searchShowData="searchShowData"></searchtop>
          </div>
        </div>

        <!-- 左侧下部分：统计区域 -->
        <div class="info-card stats-alerts">
          <div class="card-tabs">
            <span class="title">建筑列表</span>
            <div class="card-actions">
              <el-button class="operation-button" type="primary" size="small">导出</el-button>
              <el-button class="operation-button" type="primary" size="small" @click="handleAddInfoFn">新增建筑</el-button>
              <el-button class="operation-button" type="primary" size="small" @click="handleRefreshInfoFn"><el-icon>
                  <RefreshRight />
                </el-icon></el-button>
              <el-button class="operation-button" type="primary" size="small"><el-icon>
                  <FullScreen />
                </el-icon></el-button>
            </div>
          </div>
          <div class="card-table">
            <tabledata :tableShowData="tableShowData" @tableDataRefresh="handleRefreshInfoFn"></tabledata>
          </div>
        </div>
      </div>
    </main>

    <!-- 新增建筑抽屉 -->
    <el-drawer v-model="isAddDrawer" title="添加建筑信息" :with-header="false" :before-close="beforeCloseAddBuildDrawer">
      <Addbuild @closeAddDrawer="closeAddDrawer" @tableDataRefresh="handleRefreshInfoFn"></Addbuild>
    </el-drawer>

    <!-- 修改建筑抽屉 -->
    <el-drawer v-model="isBuildingEditDrawer" title="修改用户信息" :with-header="false"
      :before-close="beforeCloseAddBuildDrawer">

      <showResetBuildingInfo :rowData="rowData" :isBuildingEditDrawer="isBuildingEditDrawer"
        @closeEditDrawer="closeBuildingEditDrawer" @tableDataRefresh="handleRefreshInfoFn"></showResetBuildingInfo>

    </el-drawer>
  </div>
</template>

<script setup>
import { reactive, computed, ref, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import searchtop from '../commentcomponents/searchtop/index.vue';
import tabledata from '../commentcomponents/tabledata/index.vue';
import showResetBuildingInfo from './components/showResetBuildingInfo.vue';
import Addbuild from './components/addbuild.vue';
import router from '../../router';
import { buildingPageApi, buildingRemoveApi, buildingGetBuildCodeListApi } from '../../api/build';
import { useRoute, useRouter } from 'vue-router';
import useAppStore from '../../store/module/app';
const useAppStoreInstance = useAppStore();
const route = useRoute();
// 搜索栏配置
const searchShowData = ref([
  { label: '功能描述', placeholder: "请输入", type: 'input', content: '', isShow: true },
  { label: '建筑编号', placeholder: "请选择", type: 'autocomplete', content: '', isShow: true, click: 'buildingGetBuildCodeListApiFn', options: [] },
  { label: '建筑层数', placeholder: "请选择", type: 'autocomplete', content: '', isShow: true, click: 'buildingGetTotalFloorNumListFn', options: [] },
  { label: '建筑名称', placeholder: "请选择", type: 'autocomplete', content: '', isShow: true, click: 'buildingGetBuildNameListFn', options: [] },
]);



// 布局配置
const layoutConfig = reactive({
  containerMinHeight: '100vh',
  cardSpacing: '1rem'
});

// 抽屉控制
const isAddDrawer = ref(false);
const isBuildingEditDrawer = ref(false);
const rowData = ref([]);



// 方法定义
const handleAddInfoFn = () => {
  isAddDrawer.value = true;
}

const handleRefreshInfoFn = () => {
  console.log("刷新数据");
  initTableDateFn()
}
const closeAddDrawer = () => {
  isAddDrawer.value = false;
}

const beforeCloseAddBuildDrawer = () => {
  // 关闭前的处理逻辑
}



const buildingSeeDetails = (data) => {
  console.log("查看详情", data);
  router.push({
    path: '/showdetaildate',

  });
  useAppStoreInstance.setPushParameter({ buildId: data.buildId })
}

const buildingDdeleteData = (data) => {
  ElMessageBox.confirm('是否删除该建筑？此操作将无法撤销', '删除', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      try {
        // 用户点击「确认」
        const { buildId, buildName } = data;
        buildingRemoveApi({ buildId: buildId })
          .then(res => {
            if (res.code === 200) {
              ElMessage.success("`${buildName}已删除`");
              handleRefreshInfoFn();
            } else {
              ElMessage.error(res.message || '删除失败'); // 更明确的错误提示
            }
          })
          .catch(err => {
            // API 请求失败
            ElMessage.error(err?.message || '删除请求失败');
          });
      } catch (error) {
        console.error(error, 'API 请求失败');
      }

    })
    .catch(() => {
      // 用户点击「取消」
      ElMessage.info('已取消删除'); // 移除多余的 `err` 参数
    });
};

const resetBuildingShowInfo = (data) => {

  isBuildingEditDrawer.value = true;
  rowData.value = data;
  console.log("000000------------0000000000", rowData.value)
}

const closeBuildingEditDrawer = () => {
  isBuildingEditDrawer.value = false;
  // console.log("000000------------0000000000",isBuildingEditDrawer.value)
}
// 表格数据
const tableShowData = ref([{
  tableHeader: [
    { label: '建筑编号', prop: 'buildCode' },
    { label: '建筑名称', prop: 'buildName' },
    { label: '建筑层数', prop: 'totalFloorNum' },
    { label: '火情次数', prop: 'fireNum' },
    { label: '更新时间', prop: 'updateTime' },
    { label: '操作', prop: 'Operation' }
  ],
  tableBody: []
}]);
const Operation = ref([
  { label: '查看详情', type: 'primary', icon: 'EditPen', click: buildingSeeDetails },
  { label: '删除', type: 'danger', icon: 'Delete', click: buildingDdeleteData },
  { label: '修改', type: 'primary', icon: 'EditPen', click: resetBuildingShowInfo }
]);
// onMounted(() => { 
//   initTableDateFn()
// });
const initTableDateFn = () => {
  console.log('初始化数据');
  buildingPageApi({ currentPageNum: 1, currentPageSize: 10 }).then(res => {
    if (res.code === 200) {

      let { list, total, pageSize } = res.data;
      if (!list) {
        ElMessage.warning('建筑列表暂无数据，请先添加建筑数据');
      } else {
        tableShowData.value[0].tableBody = []
        list = list.filter(element => {
          return element.isDeleted === 0;
        });
        list.forEach(element => {
          element.Operation = [...Operation.value]
        });
        tableShowData.value[0].tableBody = list
        tableShowData.value[0].total = total
        tableShowData.value[0].pageSize = pageSize
        console.log(tableShowData.value, '展示数据');
      }
    }

  }).catch(err => {
    ElMessage.error(err?.message || "建筑列表请求失败")

  })
};

// 监听路由变化
watch(route, () => {
  initTableDateFn()
}, { immediate: true });

// 计算属性
const containerStyle = computed(() => ({
  minHeight: layoutConfig.containerMinHeight,
  '--card-spacing': layoutConfig.cardSpacing,
}));
</script>

<style scoped>
.dashboard-container {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background-color: rgba(0, 0, 0, 0.05);
  color: #333;
  overflow: hidden;
}

.main-content {
  display: flex;
  gap: var(--card-spacing);
  padding: 0.4rem;
  height: 100vh;
  box-sizing: border-box;
}

.left-section {
  flex: 2;
  display: flex;
  flex-direction: column;
  gap: var(--card-spacing);
  height: 100%;
}

.left-top {
  height: auto;
}

.info-card {
  background-color: #fff;
  padding: 1rem;
  border-radius: 8px;
  box-sizing: border-box;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: auto;
}

.region-overview {
  flex: 1;
  min-width: 200px;
}

.stats-alerts {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  height: 67%;
}

.card-tabs {
  display: flex;
  border-bottom: 1px solid #292828;
  font-size: 1.2rem;
  color: #000000;
  height: 8%;
  align-items: center;
  width: 100%;
  padding: 10px;
}

.title {
  width: 70%;
}

.card-actions {
  display: flex;
  flex: 1;
  justify-content: space-between;
  align-items: center;
  height: 8%;
}

.operation-button {
  width: 15%;
}

.card-table {
  width: 100%;
  flex: 1;
  overflow: hidden;
  border-radius: 8px;
}

@media (max-width: 1024px) {
  .left-top {
    flex-direction: column;
  }

  .region-overview {
    width: 100%;
    flex: none;
  }
}

@media (max-width: 768px) {
  .stats-alerts {
    flex-direction: column;
  }
}
</style>