<template>
  <div class="table-box">
    <div class="card table-main">
      <!-- 表格头部 操作按钮 -->
      <div class="table-header">
        <div class="header-button-lf">
          <el-form :model="pageable" label-width="auto"  :inline="true">
            <el-form-item label="站号:">
              <SelectItem :select-data="selectedData" :select-list="platformList" :is-checkbox="true" @update:selectedItems="selectedItems" style="width: 200px"> </SelectItem>
            </el-form-item>
            <el-form-item label="告警类型:">
              <el-select v-model="tact_state" filterable placeholder="请选择" clearable style="width: 200px">
                <el-option
                  v-for="item in tactList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="告警时间:">
              <el-date-picker
                v-model="timeBegin"
                type="date"
                placeholder="选择日期"
                @change="changeBeginTime"
                :clearable="false"
              >
              </el-date-picker>
              <!-- 减少一天 -->
              <el-button style="margin: 0 5px" @click="decreaseDay" icon="ArrowLeft"></el-button>
              <!-- 增加一天 -->
              <el-button @click="increaseDay" icon="ArrowRight" :disabled="isIncreaseDay"></el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"> 查询 </el-button>
              <el-button style="margin-left: 10px" @click="resetQuery"> 重置 </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- 表格主体 -->
      <el-table stripe ref="tableRef" :border="true" :data="processTableData"  size="small" @sort-change="handleSortChange">
        <el-table-column align="left" label="序号" width="45px" :show-overflow-tooltip="true" fixed >
          <template #default="scope">
            {{ (pageable.pageNum - 1) * pageable.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <template v-for="item in columns" :key="item">
          <el-table-column v-bind="item" :fixed="item.fixed" :align="item.align ?? 'left'" :reserve-selection="item.type == 'selection'" :sortable="item.sortable" :show-overflow-tooltip="true" >
            <template #default="scope">
              <template v-if="item.prop === 'tact_state'">
                {{findLabelByValue(tactStateList,scope.row.tact_state)}}
              </template>
              <template v-if="item.prop === 'tact_type'">
                {{findLabelByValue(dataTypeList,scope.row.data_type)}}
              </template>
              <template v-if="item.prop === 'alarm_on_time_i'">
                {{scope.row.alarm_on_time_i?formatDate(scope.row.alarm_on_time_i):'--'}}
              </template>
              <template v-if="item.prop === 'alarm_off_time_i'">
                {{scope.row.alarm_off_time_i?formatDate(scope.row.alarm_off_time_i):'--'}}
              </template>
              <template v-if="item.prop === 'notice_type'">
                {{findLabelByValue(noticeTypeList,scope.row.notice_type)}}
              </template>
            </template>
          </el-table-column>
        </template>
        <!-- 无数据 -->
        <template #empty>
          <div class="table-empty">
            <slot name="empty">
              <img src="@/assets/images/notData.png" alt="notData" />
              <div>暂无数据</div>
            </slot>
          </div>
        </template>
      </el-table>
      <!-- 分页组件 -->
      <Pagination :pageable="pageable" :handle-size-change="handleSizeChange" :handle-current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<script setup lang="ts" name="useProTable">
import Pagination from "@/components/ProTable/components/Pagination.vue";
import SelectItem from "@/components/SelectItem/index.vue";
import {ref, reactive, onMounted, computed} from "vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { getPlatformList, getTacRecordList} from "@/api/modules/allData";
import {Platform} from "@/api/interface";
import {useUserStore} from "@/stores/modules/user";
const pageable = ref<any>({
  as_code_list: [],
  tact_state_on: false,
  tact_data_on: false,
  begin_time: undefined,
  end_time: undefined,

  pageNum: 1,
  pageSize: 20,
  total: 1
});

const as_code_list = ref('')
const timeBegin = ref<Date | null>(null);
const isIncreaseDay =ref(true)

const changeBeginTime = (value: Date | string | null) => {
  if (!value) return;
  const timeStamp = new Date(value).getTime();
  const startTime = timeStamp + 60 * 1000; // 添加1分钟（60秒）
  const endTime = timeStamp + 24 * 60 * 60 * 1000; // 添加一天（24小时）
  pageable.value.begin_time = startTime / 1000;
  pageable.value.end_time = endTime / 1000;


  const newDate = new Date(value);
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 将时间设置为当天的0点0分0秒
  if (newDate < today) {
   isIncreaseDay.value = false
  }else {
    isIncreaseDay.value = true
  }
  getList()
};

const tact_state =ref(0)

const decreaseDay = () => {
  if (timeBegin.value) {
    pageable.value.pageNum = 1;
    const newDate = new Date(timeBegin.value);
    newDate.setDate(newDate.getDate() - 1);
    timeBegin.value = newDate;
    changeBeginTime(newDate);
    getList()
  }
};

const increaseDay = () => {
  if (timeBegin.value) {
    pageable.value.pageNum = 1;
    const newDate = new Date(timeBegin.value);
    newDate.setDate(newDate.getDate() + 1);
    timeBegin.value = newDate;
    changeBeginTime(newDate);
    getList()
  }
};

const tactList = [
  {
    value: 0,
    label: '全部',
  }
]

const noticeTypeList= [
  {
    value: 0,
    label: '字幕通知',
  },
  {
    value: 1,
    label: '声音通知',
  }
]

const tactStateList= [
  {
    value: 0,
    label: '告警中',
  },
  {
    value: 1,
    label: '已消警',
  }
]


const dataTypeList= [
  {
    value: 0,
    label: '能见度',
  },
  {
    value: 1,
    label: '风速',
  },
  {
    value: 2,
    label: '大气电场',
  },{
    value: 3,
    label: '云量',
  },{
    value: 4,
    label: '云高',
  },{
    value: 5,
    label: '温度',
  },{
    value: 6,
    label: '湿度',
  },{
    value: 7,
    label: '小时雨量',
  }
]

function findLabelByValue(noticeTypeList, value) {
  const item = noticeTypeList.find(item => item.value === value);
  return item ? item.label : null;
}

const handleSortChange = ({ column, prop, order }) => {

};


// 查询功能
const handleQuery = () => {
  pageable.value.pageNum = 1;
  getList()
};

//清空查询
const resetQuery = () => {
  selectedData.value = firstPlatform.value
  pageable.value.as_code_list = firstPlatform.value
  pageable.value.pageNum = 1;
  pageable.value.begin_time=undefined
  pageable.value.end_time=undefined
  as_code_list.value = ''
  timeBegin.value = undefined
  getTime()
  getList()
};

//搜索站号
const selectedData= ref()
const selectedItems =(data)=>{
  if(data.length>0){
    pageable.value.as_code_list = data
    selectedData.value = data
  }else {
    selectedData.value = firstPlatform.value
    pageable.value.as_code_list = firstPlatform.value
  }
};

const firstPlatform = computed(() => {
  if (platformList.value && platformList.value.length > 0) {
    return [platformList.value[0].as_code];
  } else {
    return [];
  }
});

/**
 * @description 每页条数改变
 * @param {Number} val 当前条数
 * @return void
 * */
const handleSizeChange = (val: number) => {
  pageable.value.pageSize = val
  getList()
};

/**
 * @description 当前页改变
 * @param {Number} val 当前页
 * @return void
 * */
const handleCurrentChange = (val: number) => {
  pageable.value.pageNum = val
  getList()
};

const processTableData = ref([]);

// 表格配置项
const columns = reactive<ColumnProps[]>([
  { prop: "as_code", label: "站号",fixed:true },
  { prop: "as_name", label: "站名",fixed:true },
  { prop: "tact_name", label: "策略名称" },
  { prop: "tact_state", label: "策略状态" },
  { prop: "tact_type", label: "告警类型" },
  { prop: "data_value", label: "观测值" },
  { prop: "alarm_on_time_i", label: "告警时间",width:150},
  { prop: "alarm_off_time_i", label: "消警时间",width:150},
  { prop: "notice_type", label: "通知方式" },
  { prop: "remark", label: "告警说明",width:400 }
]);


const getList = async () => {
  if(pageable.value.as_code_list===undefined||pageable.value.as_code_list.length===0){
    // 没有站不给数据
    processTableData.value = []
    pageable.value.total=0
    return;
  }
  const { data } = await getTacRecordList(pageable.value);
  processTableData.value = data.list
  pageable.value.total = data.total
};

onMounted(() => {
  getTime()
  selectedData.value = firstPlatform.value
  pageable.value.as_code_list = firstPlatform.value
  getList()
})

const getTime=()=>{
  const defaultDate = new Date();
  defaultDate.setHours(0, 0, 0, 0); // 将时间设置为当天的0点0分0秒
  timeBegin.value = defaultDate;
  changeBeginTime(defaultDate); // 调用changeBeginTime方法
}

const userStore = useUserStore();
const platformList =ref<any>(computed(() => userStore.stations))


function formatDate(timestamp) {
  const date = new Date(timestamp * 1000); // 将时间戳转换为毫秒
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}


</script>
<style scoped lang="scss">
::v-deep .el-table-fixed-column--left {
  border-right: 1px solid #80bdff !important;
}
</style>
