<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;
}
</style>
<template>
  <div class="system-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">

      <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-input
            v-model="state.formQuery.userPhone"
            placeholder="用户手机号"
            clearable
            @blur="loadData(true)"
            class="wd150 mr10">
        </el-input>

        <el-input
            v-model="state.formQuery.userNickname"
            placeholder="用户昵称"
            clearable
            @blur="loadData(true)"
            class="wd150 mr10">
        </el-input>

        <el-select
            v-model="state.formQuery.status"
            placeholder="状态"
            clearable
            @change="loadData(true)"
            class="wd120 mr10">
          <el-option label="启用" :value="1"/>
          <el-option label="禁用" :value="0"/>
        </el-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.add'" size="default" plain type="primary" class="ml10" @click="onRowClick('add', null)">
          <SvgIcon name="ele-Plus"/>
          添加用户
        </el-button>

        <el-button v-auth="'station.whitelist.add'" size="default" plain type="warning" class="ml10" @click="onBatchAdd">
          <SvgIcon name="ele-DocumentAdd"/>
          批量添加
        </el-button>

        <el-button v-auth="'station.whitelist.delete'" size="default" plain type="danger" class="ml10" @click="onBatchRemove" :disabled="state.selectedIds.length === 0">
          <SvgIcon name="ele-Delete"/>
          批量移除
        </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"
          @selection-change="handleTableSelectionChange">
        <template #empty>
          <el-empty></el-empty>
        </template>
        <el-table-column type="selection" width="55" align="center"/>
        <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="'status' === field.prop">
              <el-tag :type="row[field.prop] === 1 ? 'success' : 'danger'">
                {{ row[field.prop] === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
            <template v-else-if="'action' === field.prop">
              <el-button v-auth="'station.whitelist.modify'" size="small" plain type="warning" @click="onRowClick('edit', row)">编辑</el-button>
              <el-button v-auth="'station.whitelist.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>

      <ext-page class="page-pager" v-model:value="state.pageQuery" @change="loadData(false)"/>
    </el-card>
  </div>
  <WhitelistDialog ref="whitelistDialogRef" @refresh="loadData(true)"/>
  <BatchAddDialog ref="batchAddDialogRef" @refresh="loadData(true)"/>
</template>

<script setup lang="ts" name="StationWhitelistList">
import {defineAsyncComponent, reactive, onMounted, onBeforeMount, ref, nextTick, onBeforeUnmount} from 'vue';
import {$body, $get, $delete} from "/@/utils/request";
import {Msg} from "/@/utils/message";
import ExtPage from '/@/components/form/ExtPage.vue'
import mittBus from '/@/utils/mitt';
import ExtSelect from "/@/components/form/ExtSelect.vue";
import {useRoute} from "vue-router";

const route = useRoute();
const WhitelistDialog = defineAsyncComponent(() => import("/@/views/admin/whitelist/dialog.vue"));
const BatchAddDialog = defineAsyncComponent(() => import("/@/views/admin/whitelist/batch.vue"));

const queryRef = ref();
const whitelistDialogRef = ref();
const batchAddDialogRef = ref();

const state = reactive({
  formQuery: {
    stationId: '',
    userPhone: '',
    userNickname: '',
    status: null as number | null
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false,
    columns: [
      {label: '站点名称', prop: 'stationName', width: 180, resizable: true},
      {label: '用户手机号', prop: 'userPhone', width: 140, resizable: true},
      {label: '用户昵称', prop: 'userNickname', width: 150, resizable: true},
      {label: '状态', prop: 'status', width: 100, align: 'center'},
      {label: '备注', prop: 'remark', minWidth: 200, resizable: true},
      {label: '创建时间', prop: 'createTime', width: 180, resizable: true},
      {
        label: '操作', prop: 'action', width: 160, align: 'center', fixed: 'right',
      }
    ],
  },
  selectedIds: [] as number[]
})

onBeforeMount(() => {
  const stationId = route.query.stationId as string;
  if (stationId) {
    state.formQuery.stationId = stationId;
  }
})

onMounted(() => {
  loadData();

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

  mittBus.on("stationWhitelist.refresh", () => {
    loadData();
  })
});

onBeforeUnmount(() => {
  mittBus.off("stationWhitelist.refresh")
})

const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  $get(`/station-whitelist/list`, { ...state.formQuery, ...state.pageQuery }).then((res: any) => {
    let { list, total } = res;
    state.tableData.data = list;
    state.pageQuery.total = total;
    state.tableData.loading = false;
  }).catch(e => {
    console.error(e)
    state.tableData.loading = false;
  })
};

const onRowClick = (type: string, row: any) => {
  whitelistDialogRef.value.open(type, row);
};

const onBatchAdd = () => {
  batchAddDialogRef.value.open();
};

const onBatchRemove = () => {
  if (state.selectedIds.length === 0) {
    Msg.message('请选择要移除的用户', 'warning');
    return;
  }
  Msg.confirm(`此操作将移除选中的 ${state.selectedIds.length} 个用户，是否继续?`).then(() => {
    $delete(`/station-whitelist/batchRemove`, state.selectedIds).then(() => {
      Msg.message("移除成功", 'success');
      loadData(true);
    }).catch(() => {
      Msg.message("移除失败", 'error');
    })
  });
};

const onRowDel = (row: any) => {
  Msg.confirm(`此操作将移除用户『${row.userNickname || row.userPhone}』，是否继续?`).then(() => {
    $delete(`/station-whitelist/remove/${row.id}`).then(() => {
      Msg.message("移除成功", 'success');
      loadData(true);
    }).catch(() => {
      Msg.message("移除失败", 'error');
    })
  });
};

const handleTableSelectionChange = (selection: any) => {
  state.selectedIds = selection.map((item: any) => item.id);
}
</script>
