<template>
  <div>
    <BasicTable class="basic-table-cl" :clickToRowSelect="false" @row-click="rowCLick" @register="registerTable">
      <template #form-formHeader="{ model, field }">
        <div class="form-box">
          <a-row>
            <a-col :span="12">
              <span class="span-label"> 关键字: </span>
              <a-input class="custom-input" v-model:value="formState.value" placeholder="支持流域搜索" />
            </a-col>
            <a-col :span="12">
              <span class="span-label"> 监测站点: </span>
              <a-select class="custom-input sitemore" mode="multiple" placeholder="监测站点(可多选)" :maxTagCount="2"
                :maxTagTextLength="4" v-model:value="formState.senid" :options="optionArr" />
            </a-col>
          </a-row>
        </div>
      </template>
      <template #toolbar>
        <Authority>
          <a-button type="primary"
            @click="exportData(dataCenter.exportColumns, dataCenter.exportdataSource, '雨情查询.xlsx')">导出</a-button>
        </Authority>
      </template>
    </BasicTable>
    <BasicModal :maskClosable="false" :footer="null" @cancel="cancel" :visible="showModal" :width="1200"
      :title="basicModalTitle">
      <div>
        <div class="top-search">
          时间范围：
          <a-range-picker :value="timeData.time" :show-time="{ format: 'HH:mm:ss' }" format="YYYY-MM-DD HH:mm:ss"
            :placeholder="['开始时间', '结束时间']" @change="onChange" :allowClear="true" />
          <a-button @click="getHistoryRain" class="marg-left" type="primary">查询</a-button>
          <a-button class="right-position" type="primary"
            @click="exportData(tableDataModal.table_head, tableDataModal.table_value, basicModalTitle + '.xlsx')">导出</a-button>
        </div>
        <a-table class="ant-table-striped ant-table-striped-modal" :dataSource="tableDataModal.table_value"
          :rowClassName="(record, index) => (index % 2 === 1 ? 'table-striped' : null)" bordered size="middle"
          :pagination="false" :columns="tableDataModal.table_head" :scroll="{ y: '60vh' }"
          :rowKey="(record, index) => index">
          <template #diagram="{ record  }">
            <Progress :percent="record.factv/maxNum*100" :show-info="false" />
          </template>
        </a-table>
      </div>
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
import { defineComponent, ref, watch, onMounted, reactive } from 'vue';
import { BasicTable, useTable } from '/@/components/Table';
import { BasicModal } from '/@/components/Modal/index';
import { getRealRain, getRiverTree, historyRain } from '/@/api/swHome/index';
import { getNowTime, exportData } from '/@/utils/fnUtils.ts';
import { Authority } from '../../../components/Authority/index';
import { Progress } from 'ant-design-vue';
let columns = [];
let searchFormSchema = [];
let dataArr = []
const [registerTable, { reload, setColumns, setTableData }] = useTable({
  // 表格头部
  title: '雨情查询',
  inset: true,
  // api: getRealRain,
  columns,
  showIndexColumn: true,
  clickToRowSelect: false,
  beforeFetch: (T) => {
    console.log(T);
  },
  sortFn: (info) => {
    // console.log(info)
    // console.log(dataArr)
    if (info.order == 'descend') {
      
      dataArr.sort((a, b) => {
        let aNum = a[info.field] == '--'?-1:a[info.field]*1
        let bNum = b[info.field] == '--'?-1:b[info.field]*1
        if ( aNum < bNum) return 1;
        if ( aNum > bNum) return -1;
        return 0;
      });
    }
    if (info.order == 'ascend') {
      dataArr.sort((a, b) => {
        let aNum = a[info.field] == '--'?-1:a[info.field]*1
        let bNum = b[info.field] == '--'?-1:b[info.field]*1
        if (aNum < bNum) return -1;
        if (aNum > bNum) return 1;
        return 0;
      });
    }
    setTableData(dataArr);
  },
  // 搜索表格
  formConfig: {
    labelWidth: 120,
    schemas: searchFormSchema,
    // 自定义提交逻辑
    submitFunc: submitFunc,
    // 自定义重置逻辑
    resetFunc: resetFunc,
  },
  // 是否需要搜索框
  useSearchForm: true,
  // 是否需要表格设置框
  showTableSetting: true,
  tableSetting: {
    redo: false,
    setting: false,
  },
  // rowSelection: { type: 'checkbox' },
  // 是否需要边框
  bordered: true,
  rowKey: 'id',
  ellipsis: false,
  fetchSetting: {
    listField: 'data.table_value',
  },
  pagination: false
});
// 表单数据
let formState = reactive({
  value: '',
  senid: [],
});
// 所有的数据
let allAll = [];
// 弹窗控制
let tableDataModal = reactive({
  table_head: [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      align: 'center',
      width:100,
      customRender: (text, record, index) => {
        return text.index + 1;
      }, //此处为重点
    },
    {
      title: '时间',
      dataIndex: 'time',
      key: 'time',
      align: 'center',
    },
    {
      title: '时段雨量',
      dataIndex: 'factv',
      key: 'factv',
      align: 'center',
    },
    {
      title: '图示',
      dataIndex: 'factv',
      key: 'factv',
      align: 'center',
      width:200,
      slots: { customRender: 'diagram' },
    },
  ],
  table_value: [],
});
let basicModalTitle = ref('');
let showModal = ref(false);
let timeData = reactive({
  time: [],
});
function onChange(value, dateString) {
  timeData.time = dateString;
}
function cancel(e) {
  showModal.value = false;
}
// rowCLick
let activeItem = {};
function rowCLick(item) {
  (timeData.time = [getNowTime(2), getNowTime(1)]), (activeItem = item);
  basicModalTitle.value = `雨情历史数据(${item.st_name})`;
  showModal.value = true;
  getHistoryRain();
}
// 查询雨情历史数据
let historyFormData = reactive({
  senid: {},
  start_time: '',
  end_time: '',
});
function getHistoryRain() {
  historyFormData.senid = activeItem.senid;
  historyFormData.start_time = timeData.time[0] ? timeData.time[0] : '';
  historyFormData.end_time = timeData.time[1] ? timeData.time[1] : '';
  historyRain(historyFormData).then((res) => {
    tableDataModal.table_value = res.data;
    tableNumSet(res.data)
  });
}
// 设置项目
let maxNum = ref(0)
const tableNumSet = (table) => {
  maxNum.value = 0
  table.forEach(element => {
    let factv = element.factv*1
    if(maxNum.value<factv){
      maxNum.value = factv
    }
  });
}
// 所有雨量站数据
let optionArr = ref([]);
// 重置逻辑
function resetFunc() {
  formState.value = '';
  formState.senid = [];
}
// 提交事件
function submitFunc() {
  screenData();
}
// 筛选数据
function screenData() {
  console.log(formState);
  console.log(allAll);
  let arr = [];
  // 都有数据进行两次筛选
  if (formState.value != '' && formState.senid.length > 0) {
    allAll.forEach((element) => {
      formState.senid.forEach((elements) => {
        if (elements == element.st_name && element.basin_name.indexOf(formState.value) != -1) {
          arr.push(element);
        }
      });
    });
  } else if (formState.value != '') {
    allAll.forEach((element) => {
      if (element.basin_name.indexOf(formState.value) != -1) {
        console.log(element);
        arr.push(element);
      }
    });
  } else if (formState.senid.length > 0) {
    allAll.forEach((element) => {
      formState.senid.forEach((elements) => {
        if (elements == element.st_name) {
          arr.push(element);
        }
      });
    });
  } else {
    arr = allAll;
  }
  console.log(arr);
  setTableData(arr);
}
// 处理表头
function processingData(table_head) {
  table_head.forEach((element) => {
    for (let key in element) {
      let item = element[key];
      element.title = item;
      element.key = key;
      element.dataIndex = key;
      element.ellipsis = true;

      if (element.title == '时间') {
        element.width = 160;
      }
      // if (element.title == '传感器ID') {
      //   element.width = 147;
      // }
      if (element.title == '流域分区') {
        element.width = 140;
      }
      if (element.title == '测站') {
        element.width = 150;
      }
      if (element.title == '传感器ID') {
        element.width = 100;
      }
      if (element.title != '时间'
        && element.title != '流域分区'
        && element.title != '测站'
        && element.title != '传感器ID') {
        element.width = 140;
        element.sorter = true
      }
    }
  });
  return table_head;
}
let dataCenter = reactive({
  exportdataSource: [],
  exportColumns: []
})
// 获取请求头
async function getRealRainData() {
  await getRealRain().then((res) => {
    let { table_head, table_value } = res.data;
    dataCenter.exportdataSource = allAll = table_value;
    dataCenter.exportColumns = columns = processingData(table_head);
    setColumns(columns);
    setTableData(table_value);
    dataArr = table_value
    optionArr.value = measuringStation(table_value);
  });
}

// 筛选出所有测站
function measuringStation(table_value) {
  let measuringStationArr = [];
  table_value.forEach((element) => {
    measuringStationArr.push({ value: element.st_name });
  });
  return measuringStationArr;
}
onMounted(async () => {
  await getRealRainData();
  // getRiverTreeData();
});
</script>
<style scoped lang="less">
.form-box {
  position: absolute;
  z-index: 9;
  width: 66.6666%;

  .custom-input {
    width: calc(100% - 100px);
  }
}

.span-label {
  width: 90px;
  padding-right: 10px;
  display: inline-block;
  text-align: right;
  line-height: 32px;
}

.marg-left {
  margin-left: 10px;
}

.ant-table-striped-modal {
  margin-top: 20px;
  ::v-deep(.ant-table-fixed-header .ant-table-scroll .ant-table-header){
    width: 1182px !important;
  }
}

.vben-basic-table-form-container {
  padding: 0px;
}

.top-search {
  position: relative;

  .right-position {
    position: absolute;
    right: 0px;
    top: 0px;
  }
}
</style>
