<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-date-picker
                v-model="recordDate"
                type="month"
                placeholder="选择月份"
                :disabled-date="disabledDate"
                @change="changeMultiTime">
              </el-date-picker>
            </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 class="header-button-ri">
          <slot name="toolButton">
            <div class="zt-box">
              <img class="img-documented" src="@/assets/images/documented.png"/>
              <span class="zt-title">正常</span>
              <img class="img-documented" src="@/assets/images/documented_not.png"/>
              <span class="zt-title">缺测</span>
            </div>
          </slot>
        </div>
      </div>
      <!-- 表格主体 -->
      <el-table stripe ref="tableRef" :border="true" :data="processTableData"  size="small" class="el-table--small">
        <el-table-column align="center" width="50">
          <template #header>
            <div class="group-bias-divide">
              <div class="top">日</div>
              <div class="bottom">时</div>
            </div>
          </template>
          <template #default="scope">
            {{ (scope.$index+1).toString().padStart(2, '0') }}
          </template>
        </el-table-column>
        <template v-for="item in columns" :key="item">
          <el-table-column v-bind="item" :align="item.align ?? 'center'">
            <template #default="scope">
              <img v-if="scope.row[item.prop]===1" class="img-documented" src="@/assets/images/documented.png">
              <img v-else class="img-documented" src="@/assets/images/documented_not.png">
            </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>
    </div>
  </div>
</template>

<script setup lang="ts" name="useProTable">
import SelectItem from "@/components/SelectItem/index.vue";
import {ref, computed, onMounted} from "vue";
import { ColumnProps } from "@/components/ProTable/interface";
import {useUserStore} from "@/stores/modules/user";
import {getDataItemList, getDataItemList2} from "@/api/modules/allData";

//获取站列表
const userStore = useUserStore();
const platformList =ref<any>(computed(() => userStore.stations))

//搜索日期
const recordDate = ref();
const disabledDate = (time) => {
  const today = new Date();
  const month = today.getMonth();
  const year = today.getFullYear();
  // 将时间转换为日期对象
  const date = new Date(time);
  // 比较月份和年份，如果大于当前月份，则禁用
  return date.getFullYear() === year && date.getMonth() > month;
};

const changeMultiTime = (time) => {
  if (time) {
    const year = new Date(time).getFullYear();
    const month = new Date(time).getMonth();
    const firstDayOfMonth = new Date(year, month, 1).setHours(1, 0, 0, 0); // 当月第一天1点的时间戳
    const firstDayOfNextMonth = new Date(year, month + 1, 1).getTime(); // 下一个月第一天的时间戳，设置为00:00:00.000
    // 更新时间戳
    pageable.value.begin_time = Math.floor(firstDayOfMonth / 1000); // 转换为秒
    pageable.value.end_time = Math.floor(firstDayOfNextMonth / 1000); // 转换为秒

    //重置表头
    columns.value = generateColumns(year,month+1)

  } else {
    // 如果没有选择月份，则默认为当前月份
    const today = new Date();
    const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1).getTime();
    const firstDayOfNextMonth = new Date(today.getFullYear(), today.getMonth() + 1, 1).getTime();
    // 更新时间戳
    pageable.value.begin_time = Math.floor(firstDayOfMonth / 1000); // 转换为秒
    pageable.value.end_time = Math.floor(firstDayOfNextMonth / 1000); // 转换为秒

    // 重置表头
    columns.value = generateColumns(today.getFullYear(),today.getMonth()+1)
  }

  getList()
};

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


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

const pageable = ref<any>({
  data_type: false,
  time_order: 0,
  time_space:60,
  begin_time:undefined,
  end_time: undefined,
  as_code_list:[],
  data_items:[],
  pageNum: 1,
  pageSize: 1000,
  total: 0
});

const customizeColumns= ref<any>([
  {
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_id: 2,
    data_type: "风",
    data_item: "ER_FEN_ZHONG_PING_JUN_FENG_XIANG",
    data_name: "2分钟风向",
    data_unit: "°",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  },
  {
    data_id: 1,
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_type: "风",
    data_name: "2分钟风速",
    data_item: "ER_FEN_ZHONG_PING_JUN_FENG_SU",
    data_unit: "m/s",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  },
  {
    data_id: 4,
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_type: "风",
    data_name: "10分钟风向",
    data_item: "SHI_FEN_ZHONG_PING_JUN_FENG_XIANG",
    data_unit: "°",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  },
  {
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_id: 3,
    data_type: "风",
    data_item: "SHI_FEN_ZHONG_PING_JUN_FENG_SU",
    data_name: "10分钟风速",
    data_unit: "m/s",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  },
  {
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_id: 501,
    data_type: "能见度",
    data_item: "YI_FEN_ZHONG_PING_JUN_NENG_JIAN_DU",
    data_name: "1分钟平均能见度",
    data_unit: "m",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  },
  {
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_id: 101,
    data_type: "温湿度",
    data_item: "QI_WEN",
    data_name: "气温",
    data_unit: "℃",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  },
  {
    data_id: 201,
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_type: "气压",
    data_name: "水汽压",
    data_item: "SHUI_QI_YA",
    data_unit: "hPa",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  },
  {
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_id: 109,
    data_type: "温湿度",
    data_item: "LU_DIAN_WEN_DU",
    data_name: "露点温度",
    data_unit: "℃",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  },
  {
    data_id: 202,
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_type: "气压",
    data_name: "本站气压",
    data_item: "BEN_ZHAN_QI_YA",
    data_unit: "hPa",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  },{
    data_id: 207,
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_type: "气压",
    data_name: "海平面气压",
    data_item: "HAI_PING_MIAN_QI_YA",
    data_unit: "hPa",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  },
  {
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_id: 312,
    data_type: "降水",
    data_item: "XIAO_SHI_LEI_JI_JIANG_SHUI_LIANG_CHENG_ZHONG",
    data_name: "小时累计降水量(称重)",
    data_unit: "mm",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  }
])

//重置功能
const resetQuery = () => {
  initData()
};


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

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

const processTableData = ref([]);
const processTableData2 = ref([]);

function processTableDatas(){
  // 初始化数据数组
  const datas = [];
  const daysInMonth = new Date(yearDate.value, monthDate.value, 0).getDate();
  for (let x = 1; x <= 24; x++) {
    const hourStr = x.toString().padStart(2, '0');
    const datas2 = {};
    for (let i = 1; i <= daysInMonth; i++) {
      const dayStr = i.toString().padStart(2, '0');
      const monthDateStr = monthDate.value.toString().padStart(2, '0');
      const t = `${yearDate.value}-${monthDateStr}-${dayStr}`;

      if(x==24){
        // 创建一个新的 Date 对象，表示当前时间
        let currentDate = new Date(`${yearDate.value}-${monthDateStr}-${dayStr}T00:00`);

        // 将日期增加一天
        currentDate.setDate(currentDate.getDate() + 1);

        // 格式化新的日期为所需的字符串格式
        let year = currentDate.getFullYear();
        let month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
        let day = String(currentDate.getDate()).padStart(2, '0');
        let hour = String(currentDate.getHours()).padStart(2, '0');

        const t2 = `${year}-${month}-${day} ${hour}:00`;
        datas2[t] = checkDataTimeExists(t2);
      }else {
        const  t2 = `${yearDate.value}-${monthDateStr}-${dayStr} ${hourStr}:00`;
        datas2[t] = checkDataTimeExists(t2);
      }
    }
    datas.push(datas2);
  }
  return datas;

}
const checkDataTimeExists = (targetDataTime) => {
  if (!processTableData2.value || processTableData2.value.length === 0) {
    // 数组为空或未定义，返回0
    return 0;
  }
  return processTableData2.value.some(item => {
    return item.data_time === targetDataTime;
  }) ? 1 : 0;
};

const yearDate = ref();
const monthDate = ref()
// 表格配置项  默认获取当时
const columns = ref<ColumnProps[]>();

// 根据月份生成表头
function generateColumns(year: number, month: number): ColumnProps[] {
  yearDate.value = year
  monthDate.value = month
  const daysInMonth = new Date(year, month, 0).getDate();
  const columns: ColumnProps[] = [];
  for (let i = 1; i <= daysInMonth; i++) {
    columns.push({ prop: `${year}-${month.toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`, label: i.toString().padStart(2, '0'), width: 51 });
  }
  return columns;
}

const initData=()=>{
  recordDate.value = new Date()
  selectedData.value = firstPlatform.value
  pageable.value.as_code_list = firstPlatform.value
  changeMultiTime(recordDate.value)
  columns.value = generateColumns(new Date().getFullYear(),new Date().getMonth()+1)
  processTableData.value = processTableDatas()
  getList()
}

onMounted(() => {
  initData()
});

</script>
<style scoped>
:deep .el-table--small .el-table__row {
  height: 29px !important;
  font-size: 13px !important;
}
:deep .el-table--small .el-table__header th {
  height: 40px !important;
  font-size: 14px !important;
}

:deep .el-table--small .cell {
  line-height: 22px!important;
}
</style>
<style lang='scss' scoped>
:deep(.group-bias-divide) {
  .top {
    text-align: right;
    padding-right: 0px;
    box-sizing: border-box;
    line-height: 11px;
    font-size: 11px;
  }

  .bottom {
    text-align: left;
    padding-left: 0px;
    padding-top: 1px;
    box-sizing: border-box;
    line-height: 10px;
    font-size: 11px;

    &::before {
      content: "";
      position: absolute;
      width: 1px !important;
      height: 90px !important;
      top: auto !important;
      left: auto !important;
      bottom: 0 !important;
      right: 0 !important;
      background-color: #C7E2FF;
      display: block;
      transform: rotate(309deg);
      transform-origin: bottom;
    }
  }
}

.img-documented{
  width: 15px;
  height: 15px;
}

.zt-title{
  color: var(--el-text-color-regular);
  font-size: var(--el-form-label-font-size);
}

.zt-box{
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  margin-top: 10px
}
</style>
