<style scoped lang="scss">
.system-container {

  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
    overflow: auto;

    .el-table {
      flex: 1;
    }

  }
}

.page-content {
  margin-bottom: 20px;
}

.page-pager {
  background-color: #fff;
  height: 24px;
}

.tip-card {
  margin-bottom: 15px;
  
  :deep(.el-card__body) {
    padding: 12px 20px;
  }
}
</style>
<template>
  <div class="system-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">

      <el-card class="tip-card" shadow="never">
        <el-alert
            title="白名单功能说明"
            type="info"
            :closable="false"
            show-icon>
          <template #default>
            <p>1. 启用站点白名单后，只有白名单中的用户才能在该站点启动充电</p>
            <p>2. 适用于内部专用站点或需要限制使用人数的场景</p>
            <p>3. 白名单启用后，非白名单用户尝试充电将被拒绝</p>
          </template>
        </el-alert>
      </el-card>

      <el-form
          :model="state.formQuery"
          ref="queryRef"
          size="default" label-width="0px" class="mt5 mb5">

        <ext-select
            v-model="state.formQuery.stationId"
            placeholder="选择站点"
            clearable
            url="station/listStation"
            urlMethod="get"
            data-key=""
            label-key="stationName"
            value-key="stationId"
            @on-change="loadData(true)"
            class="wd200 mr10">
        </ext-select>

        <el-button class="ml10" plain size="default" type="success" @click="loadData(true)">
          <SvgIcon name="ele-Search"/>
          查询
        </el-button>

        <el-button v-auth="'station.whitelist.config.modify'" size="default" plain type="primary" class="ml10" @click="onAddConfig">
          <SvgIcon name="ele-Plus"/>
          添加配置
        </el-button>
      </el-form>

      <el-table
          border
          stripe
          :height="state.tableData.height"
          highlight-current-row
          current-row-key="id"
          row-key="id"
          :data="state.tableData.data"
          v-loading="state.tableData.loading">
        <template #empty>
          <el-empty></el-empty>
        </template>
        <el-table-column
            v-for="field in state.tableData.columns"
            :key="field.prop"
            :label="field.label"
            :column-key="field.prop"
            :width="field.width"
            :min-width="field.minWidth"
            :fixed="field.fixed"
            :sortable="field.sortable"
            :show-overflow-tooltip="!field.fixed && field.width > 150">
          <template #default="{ row }">
            <template v-if="'enabled' === field.prop">
              <el-switch
                  v-model="row.enabled"
                  :active-value="1"
                  :inactive-value="0"
                  active-text="启用"
                  inactive-text="禁用"
                  @change="handleStatusChange(row)"
                  v-auth="'station.whitelist.config.modify'">
              </el-switch>
            </template>
            <template v-else-if="'action' === field.prop">
              <el-button v-auth="'station.whitelist.list'" size="small" plain type="primary" @click="handleManageWhitelist(row)">
                管理白名单
              </el-button>
              <el-button v-auth="'station.whitelist.config.delete'" size="small" plain type="danger" @click="onRowDel(row)">
                删除
              </el-button>
            </template>
            <template v-else>
              <div>{{ row[field.prop] }}</div>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
        v-model="state.dialog.isShowDialog"
        title="添加白名单配置"
        width="500px"
        append-to-body
        destroy-on-close>
      <el-form label-width="100px" class="mt20">
        <el-form-item label="选择站点" required>
          <ext-select
              v-model="state.dialog.stationId"
              placeholder="请选择站点"
              url="station/listStation"
              urlMethod="get"
              data-key=""
              label-key="stationName"
              value-key="stationId"
              clearable
              class="w100">
          </ext-select>
        </el-form-item>
        <el-form-item label="初始状态">
          <el-tag type="success">启用</el-tag>
          <span class="ml10 text-gray">添加后默认启用白名单功能</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onClose">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="StationWhitelistConfigList">
import { reactive, onMounted, ref, nextTick } from 'vue';
import { $body, $get, $put, $delete } from "/@/utils/request";
import { Msg } from "/@/utils/message";
import ExtSelect from "/@/components/form/ExtSelect.vue";
import { useRouter } from 'vue-router';

const router = useRouter();
const queryRef = ref();

const state = reactive({
  formQuery: {
    stationId: ''
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false,
    columns: [
      {label: '站点ID', prop: 'stationId', width: 160, resizable: true},
      {label: '站点名称', prop: 'stationName', width: 200, resizable: true},
      {label: '白名单状态', prop: 'enabled', width: 180, align: 'center'},
      {label: '创建时间', prop: 'createTime', width: 180, resizable: true},
      {label: '更新时间', prop: 'updateTime', width: 180, resizable: true},
      {
        label: '操作', prop: 'action', width: 150, align: 'center', fixed: 'right',
      }
    ],
  },
  dialog: {
    isShowDialog: false,
    stationId: ''
  }
})

onMounted(() => {
  loadData();

  nextTick(() => {
    let bodyHeight = document.body.clientHeight;
    let queryHeight = queryRef.value.$el.clientHeight;
    state.tableData.height = bodyHeight - queryHeight - 380
  })
});

const loadData = (refresh: boolean = false) => {
  state.tableData.loading = true;
  $get(`/station-whitelist/config/list`, state.formQuery).then((res: any) => {
    state.tableData.data = res || [];
    state.tableData.loading = false;
  }).catch(e => {
    console.error(e)
    state.tableData.loading = false;
  })
};

const handleStatusChange = (row: any) => {
  const statusText = row.enabled === 1 ? '启用' : '禁用';
  $body(`/station-whitelist/config/update`, {
    stationId: row.stationId,
    enabled: row.enabled
  }).then(() => {
    Msg.message(`${statusText}成功`, 'success');
  }).catch(() => {
    Msg.message(`${statusText}失败`, 'error');
    row.enabled = row.enabled === 1 ? 0 : 1;
  });
};

const handleManageWhitelist = (row: any) => {
  router.push({
    path: '/whitelist/list',
    query: { stationId: row.stationId }
  });
};

const onAddConfig = () => {
  state.dialog.stationId = '';
  state.dialog.isShowDialog = true;
};

const onClose = () => {
  state.dialog.isShowDialog = false;
  state.dialog.stationId = '';
};

const onSubmit = () => {
  if (!state.dialog.stationId) {
    Msg.message('请选择站点', 'warning');
    return;
  }
  // 检查是否已存在配置
  const exists = state.tableData.data.some((item: any) => item.stationId === state.dialog.stationId);
  if (exists) {
    Msg.message('该站点已存在白名单配置', 'warning');
    return;
  }
  
  $body(`/station-whitelist/config/update`, {
    stationId: state.dialog.stationId,
    enabled: 1
  }).then(() => {
    Msg.message('添加成功', 'success');
    loadData(true);
    onClose();
  }).catch(() => {
    Msg.message('添加失败', 'error');
  });
};

const onRowDel = (row: any) => {
  Msg.confirm(`确定要删除站点『${row.stationName}』的白名单配置吗？删除后将清空该站点的所有白名单用户。`).then(() => {
    $delete(`/station-whitelist/config/delete/${row.stationId}`).then(() => {
      Msg.message("删除成功", 'success');
      loadData(true);
    }).catch(() => {
      Msg.message("删除失败", 'error');
    })
  });
};
</script>
