<template>
  <div class="box-main">
    <div class="left-box">
      <div class="left-title"> 测站列表 </div>
      <div class="left-tree">
        <a-tree checkable :tree-data="dataCenter.treeData" v-model:expandedKeys="expandedKeys"
          v-model:selectedKeys="selectedKeys" v-model:checkedKeys="checkedKeys">
        </a-tree>
      </div>
    </div>
    <div>
      <div>
        <a-row>
          <a-col class="line-height-box" :span="10">
            <span class="title-form-title">日期范围：</span>
            <a-range-picker class="title-form-picker" :show-time="{ format: 'HH:mm:ss' }" v-model:value="dataCenter.time3"
              format="YYYY-MM-DD HH:mm:ss" :placeholder="['开始时间', '结束时间']" />
          </a-col>
          <a-col class="line-height-box" :span="14">
            <span class="title-form-title">时段类型：</span>
            <a-radio-group @change="changeStepSize" :options="dataCenter.groupOption" v-model:value="dataCenter.formData.step_size" />
          </a-col>
          <a-col class="line-height-box" :span="18">
            <span class="title-form-title">统计特征：</span>
            <a-checkbox-group :disabled="dataCenter.formData.step_size == 'R'" v-model:value="dataCenter.formData.attr" :options="dataCenter.checkboxOption" />
          </a-col>
          <a-col class="line-height-box" :span="4">
            <div class="line-btn">
              <a-button class="margin-btn" @click="resetting">重置</a-button>
              <a-button class="margin-btn" type="primary" @click="queryForm">查询</a-button>
            </div>
          </a-col>
          <a-col class="line-height-box" :span="2">
            <div class="line-btn">
              <a-button class="margin-btn" type="primary" v-if="!dataCenter.editableData" @click="eidt">编辑</a-button>
              <a-popconfirm title="是否确认保存?" @confirm="cancel">
                <a-button class="margin-btn" type="primary" v-if="dataCenter.editableData">保存</a-button>
              </a-popconfirm>
            </div>
          </a-col>
        </a-row>
      </div>
      <div>
        <a-table :pagination="false" class="ant-table-striped" bordered :scroll="{ x: 1000, y:`calc(100vh - 300px)` }" size="middle"
          :dataSource="dataCenter.dataSource" :columns="dataCenter.columns">
          <template v-for="col in dataCenter.tabSlots" #[col]="{ text, record }" :key="col">
            <div>
              <div v-if="dataCenter.editableData">
                <a-input v-if="col.indexOf('maxt') == -1 && col.indexOf('mint') == -1" v-model:value="record[col]" style="margin: -5px 0" />
                <div v-else>
                  <a-date-picker v-model:value="record[col]" valueFormat="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" show-time placeholder="日期时间"/>
                </div>
              </div>
              <template v-else>
                {{ text }}
              </template>
              <!-- <a-input v-model:value="record[col]" style="margin: -5px 0" /> -->
              
            </div>
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>
<script lang="tsx" setup>
import { ref, onMounted, reactive } from 'vue'
import moment from 'moment';
import { message, Modal } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import {
  getRiverTree,
  getHistCompute,
  postDataModify
} from '/@/api/swHome/index';
let dataCenter = reactive({
  editableData: false,
  tabSlots: [],
  treeOriginalData: {},
  treeData: [],
  time3: [],
  tableList: {},
  formData: {
    step_size: 'R',
    attr: [],
    senid: []
  },
  groupOption: [
    { label: '实时', value: 'R' },
    { label: '小时', value: 'H' },
    { label: '日', value: 'D' },
    { label: '月', value: 'M' },
    { label: '年', value: 'Y' },
  ],
  checkboxOption: [
    { label: '整点值', value: 'v' },
    { label: '平均值', value: 'avgv' },
    { label: '最大值', value: 'maxv' },
    { label: '最大值时间', value: 'maxt' },
    { label: '最小值', value: 'minv' },
    { label: '最小值时间', value: 'mint' },
  ],
  columns: [],
  dataSource: []
})
const expandedKeys = ref<string[]>([]);
const selectedKeys = ref<string[]>([]);
const checkedKeys = ref<string[]>([]);
const eidt = () => {
  if (dataCenter.dataSource.length == 0) {
    message.warning('请先查询数据再进行编辑！');
    return false
  }
  dataCenter.editableData = true
}
// const save = () => {
//   console.log(dataCenter.dataSource)
//   // dataCenter.editableData = false
// }
const cancel = () => {
  let formData = {
    step_size:dataCenter.formData.step_size,
    modify_data:[]
  }
  dataCenter.dataSource.forEach((element,index) => {
    let arrName = []
    for (const key in element) {
      if (Object.prototype.hasOwnProperty.call(element, key)) {
        const element1 = element[key];
        if(key.indexOf('&')!=-1){
          let dataArr = key.split('&')
          arrName.push(dataArr[0])
        }
      }
    }
    let uniqueArrName = unique(arrName)
    uniqueArrName.forEach(element1 => {
      if(element.time == '最小值' || element.time == '最大值'){
        return
      }
      let obj = {
        time : element.time
      }
      for (const key in element) {
        if (Object.prototype.hasOwnProperty.call(element, key)) {
          const element2 = element[key];
          if(key.indexOf(element1)!=-1){
            let dataArr = key.split('&')
            obj.senid = element1
            obj[dataArr[1]] = element2
          }
        }
      }
      formData.modify_data.push(obj)
     
    });
  });
  postDataModify(formData).then(res => {
    console.log(res)
    if(res.code == 200 && res.data.result =='修改成功'){
      message.success(res.data.result);
      queryForm()
    }else{
      message.warning(res.data.result);
    }
  })
  // dataCenter.editableData = false
}
const unique = (arr) => {
    var newArr = []
    for (var i = 0; i < arr.length; i++) {
        if (!newArr.includes(arr[i])) {
            newArr.push(arr[i])
        }
    }
    return newArr
}
const handleTree = () => {
  console.log(dataCenter.treeOriginalData)
  dataCenter.treeData.push({
    title: dataCenter.treeOriginalData.basin_name,
    key: dataCenter.treeOriginalData.basin_name,
    children: []
  })
  let arr = []
  // 获取第二层
  for (const key in dataCenter.treeOriginalData.station) {
    if (Object.prototype.hasOwnProperty.call(dataCenter.treeOriginalData.station, key)) {
      const element = dataCenter.treeOriginalData.station[key];
      let obj = {
        title: key,
        key: key,
        children: []
      }
      element.forEach((elements, indexs) => {
        let obj2 = {
          title: elements.st_name,
          key: elements.st_name,
          children: []
        }
        elements.sensor.forEach((element3, index3) => {
          obj2.children.push({
            title: element3.sensor_name,
            key: element3.senid,
            children: []
          })
        });
        obj.children.push(obj2)
      });
      dataCenter.treeData[0].children.push(obj)
    }
  }
}
const setTheadName = (name) => {
  switch (name) {
    case 'v':
      return '整点值'
    case 'avgv':
      return '平均值'
    case 'maxv':
      return '最大值'
    case 'maxt':
      return '最大值时间'
    case 'minv':
      return '最小值'
    case 'mint':
      return '最小值时间'
    case 'factv':
      return '实时'
    default:
      break;
  }
}
const changeStepSize = (item) => {
  console.log(item.target.value)
  if(item.target.value == 'R'){
    dataCenter.formData.attr = []
  }
}
const handleTable = () => {
  //处理头部数据
  dataCenter.tabSlots = []
  dataCenter.columns = []
  dataCenter.dataSource = []
  dataCenter.columns.push(
    {
      title: '时间',
      dataIndex: 'time',
      key: 'time',
      width: 200,
      align: 'center'
    }
  )
  // 处理时间数据
  dataCenter.tableList.time.forEach(element => {
    dataCenter.dataSource.push({ time: element })
  });
  // 处理表头数据
  //判断实时表头
  if (dataCenter.formData.step_size == 'R') {
    dataCenter.tableList.thead.forEach(element => {

      element.value.forEach((element1, index1) => {
        let obj = {
          title: element.sensor_name,
          dataIndex: element.senid + '&' + element1,
          key: element.senid + '&' + element1,
          align: 'center',
          width: 100,
          slots: { customRender: element.senid + '&' + element1 },
        }
        dataCenter.tabSlots.push(element.senid + '&' + element1)
        dataCenter.columns.push(obj)
      });
    });
  } else {
    dataCenter.tableList.thead.forEach(element => {
      let obj = {
        title: element.sensor_name,
        dataIndex: element.sensor_name,
        key: element.sensor_name,
        align: 'center',
        children: []
      }
      element.value.forEach((element1, index1) => {
        obj.children.push({
          title: setTheadName(element1),
          dataIndex: element.senid + '&' + element1,
          key: element.senid + '&' + element1,
          align: 'center',
          width: setTheadName(element1).indexOf("时间") != -1 ? 220 : 100,
          slots: { customRender: element.senid + '&' + element1 },
        })
        dataCenter.tabSlots.push(element.senid + '&' + element1)
      });
      dataCenter.columns.push(obj)

    });
  }
  // 处理数据体
  let tbodyArr = Object.values(dataCenter.tableList.tbody[0])
  tbodyArr.forEach((element, index) => {
    dataCenter.tableList.thead.forEach((element1, index1) => {
      element1.value.forEach((element2, index2) => {
        let name = element1.senid + "&" + element2
        dataCenter.dataSource[index][name] = element[index1][element2]
        dataCenter.dataSource[index].key = index
      });

    });
  });
  // dataCenter.columns.push({
  //   title: '操作',
  //   dataIndex: 'operation',
  //   fixed: 'right',
  //   width:100,
  //   align:'center',
  //   slots: { customRender: 'operation' },
  // })


}
const getCorrespondingOptimazeData = () => {
  getRiverTree().then(res => {
    dataCenter.treeOriginalData = res.data.data_value
    handleTree()
  })
}

const resetting = () => {
  dataCenter.time3 = []
  dataCenter.formData.step_size = 'R'
  dataCenter.formData.attr = []
}

const queryForm = () => {
  dataCenter.editableData = false
  dataCenter.formData.senid = []
  if (dataCenter.time3.length != 2) {
    message.warning('请选择查询时间');
    return false
  }
  if (dataCenter.formData.attr.length == 0 && dataCenter.formData.step_size != 'R') {
    message.warning('请选择统计特征');
    return false
  }
  checkedKeys.value.forEach(element => {
    if (typeof element === 'number') {
      dataCenter.formData.senid.push(element)
    }
  });
  if (dataCenter.formData.senid.length == 0) {
    message.warning('请选择测站');
    return false
  }
  dataCenter.formData.start_time = moment(dataCenter.time3[0]).format('YYYY-MM-DD HH:mm:ss')
  dataCenter.formData.end_time = moment(dataCenter.time3[1]).format('YYYY-MM-DD HH:mm:ss')
  console.log(dataCenter.formData)
  getHistCompute(dataCenter.formData).then(res => {
    dataCenter.tableList = res.data
    handleTable()
  })
}

onMounted(() => {
  getCorrespondingOptimazeData()
})
</script>
<style scoped lang="less">
.box-main {
  display: flex;
  height: 100%;

  &>div:nth-child(1) {
    width: 300px;
    background-color: #fff;
  }

  &>div:nth-child(2) {
    flex: 1;
    margin-left: 10px;
    height: calc(100vh - 80px);
    background-color: #fff;
    padding: 10px;
    overflow: hidden;
  }
}

.left-box {
  height: calc(100vh - 80px);
  overflow: hidden;
}

.left-title {
  background-color: #f8f8f8;
  line-height: 45px;
  text-align: center;
  font-weight: 500;
  margin: 10px;
}

.left-tree {
  background-color: #f8f8f8;
  height: calc(100% - 75px);
  margin: 10px;
  overflow: auto;
}

.title-form-title {
  display: inline-block;
  width: 80px !important;
  text-align: right;
}

.title-form-picker {
  width: calc(100% - 120px) !important;
  display: inline-block;
}

.line-height-box {
  line-height: 52px;
}

.line-btn {
  text-align: right;

  .margin-btn {
    margin-right: 10px;
  }
}

// ::v-deep(.ant-table-striped .ant-table-body){
//   height: calc(100vh - 318px);
// }
.editable-row-operations a {
  margin-right: 8px;
}
</style>