<template>
  <div class="app-container">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="起年月">
        <el-date-picker
          v-model="searchModel.startTime"
          type="month"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="截止年月">
        <el-date-picker
          v-model="searchModel.endTime"
          type="month"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="站点">
        <SelectStaion
          v-if="isComponentReady"
          ref="selectStaionRef"
          :startTime="this.formatDateToYearMonth(this.searchModel.startTime)"
          :endTime="this.formatDateToYearMonth(this.searchModel.endTime)"
          :type="this.type">
        </SelectStaion>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getWaterLeverListTableList">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="exportDate">导出</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="importSoft"
        >导入南方片
        </el-button>
      </el-form-item>
    </el-form>

    <div class="main-content">
      <div class="main-title">
        <div class="table-title">月水位表</div>
        <div class="table-header">
          <div class="table-time">年份：{{ new Date().getFullYear() }}</div>
          <div class="table-time" style="float: right">(单位水位: m)</div>
        </div>
      </div>
      <el-table
        :data="tableData"
        height="500"
        border
        style="width: 100%">
          <el-table-column label="序号" align="center">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column
            prop="stcd"
            align="center"
            label="站码"
          >
          </el-table-column>
          <el-table-column
            prop="stnm"
            align="center"
            label="站名"
          >
          </el-table-column>
          <el-table-column
            prop="addvcd"
            align="center"
            label="行政区划码">
          </el-table-column>
          <el-table-column
            prop="lysxm"
            align="center"
            label="流域水系码">
          </el-table-column>
          <el-table-column
            prop="yr"
            align="center"
            label="年">
          </el-table-column>
          <el-table-column
            prop="mth"
            align="center"
            label="月">
          </el-table-column>
          <el-table-column
            prop="avz"
            align="center"
            label="平均水位">
          </el-table-column>
          <el-table-column
            prop="avzrcd"
            align="center"
            label="平均水位注解码">
          </el-table-column>
          <el-table-column
            prop="htz"
            align="center"
            label="最高水位">
          </el-table-column>
          <el-table-column
            prop="htzrcd"
            align="center"
            label="最高水位注解码">
          </el-table-column>
          <el-table-column
            prop="htzdt"
            align="center"
            label="最高水位日期">
          </el-table-column>
          <el-table-column
            prop="mnz"
            align="center"
            label="最低水位">
          </el-table-column>
          <el-table-column
            prop="mnzrcd"
            align="center"
            label="最低水位注解码">
          </el-table-column>
          <el-table-column
            prop="mnzdt"
            align="center"
            label="最低水位日期">
          </el-table-column>
      </el-table>


      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchModel.pageNum"
        :page-sizes="[15, 30, 50,100]"
        :page-size="searchModel.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        style="padding: 30px 0; text-align: center;"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        class="upload-demo"
        drag
        :action="uploadUrl"
        :data="uploadData"
        accept=".xls,.xlsx"
        :http-request="handleUpload">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传Excel文件</div>
      </el-upload>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="softOpen" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="起年">
          <el-date-picker
            v-model="form.startTime"
            type="month"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="截止年">
          <el-date-picker
            v-model="form.endTime"
            type="month"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import {getToken} from '@/utils/auth'
import hourMaxRainApi from '@/api/basic/hourMaxRain.js'
import waterLeverApi from "@/api/month/waterLever";
import monthRainApi from "@/api/month/monthRain";
import SelectStaion from "@/components/SelectStaion/index.vue";

export default {
  name: "hourMaxRain",
  components: {SelectStaion},
  data() {
    return {
      tableData: [],
      uploadData: {},
      uploadUrl: '/year/importHourMaxRainData',
      total: 0,
      searchModel: {
        startTime: '',
        endTime: '',
        stcdIds: '',
        pageNum: 1,
        pageSize: 15
      },
      upload: {
        title: '导入数据',
        open: false
      },
      softOpen:false,
      title:'',
      form:{
        startTime:'',
        endTime:''
      },
      // 表单校验
      rules: {
        startTime: [
          { required: true, message: '开始时间不能为空', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '结束时间不能为空', trigger: 'blur' }
        ]
      },
      isComponentReady: false,
      type:"MthMtz",
    }
  },
  created() {
    this.getWaterLeverListTableList()
  },
  mounted() {
    this.$nextTick(() => {
      this.isComponentReady = true;
    });
    this.$nextTick(() => {
      if (this.$refs.selectStaionRef) {
        this.searchModel.stcd = this.$refs.selectStaionRef.stcds;
      }
    });
  },
  methods: {
    formatDateToYearMonth(date) {
      if (date == null){
        return '';
      }
      const d = new Date(date);
      if (isNaN(d.getTime())) {
        return '';
      }
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, '0');
      return `${year}${month}`;
    },
    async getWaterLeverListTableList() {
      this.searchModel.stcd = this.$refs.selectStaionRef?.stcds || '';
      const startYearAndMonth= this.formatDateToYearMonth(this.searchModel.startTime)
      const endYearAndMonth= this.formatDateToYearMonth(this.searchModel.endTime)
      const param = {
        pageNum: this.searchModel.pageNum,
        pageSize: this.searchModel.pageSize,
        startTime: startYearAndMonth,
        endTime: endYearAndMonth,
        stcd: this.searchModel.stcd,
        stnm: this.searchModel.stnm
      }
      const res = await waterLeverApi.getWaterLeverListTableList(param)
      this.tableData = res.data.map(item => {
        return {
          ...item,
          htzdt: item.htzdt?.substring(0, 10) ?? '', // 如果 mxdyeodt 是 null 或 undefined，则返回空字符串
          mnzdt: item.mnzdt?.substring(0, 10) ?? ''   // 如果 mndyeodt 是 null 或 undefined，则返回空字符串
        };
      });
      this.total = res.count;
    },
    handleImport() {
      this.upload.title = "数据导入";
      this.upload.open = true;
    },
    async handleUpload(file) {
      const formData = new FormData();
      formData.append('file', file.file); // file.file 是上传的文件对象
      // 添加其他需要发送的数据
      Object.keys(this.uploadData).forEach(key => {
        formData.append(key, this.uploadData[key]);
      });

      const config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${getToken()}` // 替换为你的 token 获取方式
        }
      };
      await hourMaxRainApi.importData(this.uploadUrl, formData, config)
        .then(response => {
          console.log('上传成功:', response.data);
          // 处理成功的响应
        })
        .catch(error => {
          console.error('上传失败:', error);
          // 处理上传失败
        });
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize
      this.getWaterLeverListTableList()
    },
    handleCurrentChange(pageNum) {
      this.searchModel.pageNum = pageNum
      this.getWaterLeverListTableList()
    },
    async exportDate() {
      const startYearAndMonth= this.formatDateToYearMonth(this.searchModel.startTime)
      const endYearAndMonth= this.formatDateToYearMonth(this.searchModel.endTime)
      const stcd = this.searchModel.stcd || '';  // 处理undefined
      const stnm = this.searchModel.stnm || '';  // 处理undefined

      const res = await this.$axiosPost('/report/monthWaterLever?startTime=' +
        startYearAndMonth + '&endTime=' + endYearAndMonth +
        '&stcd=' + stcd + '&stnm=' + stnm);
      if (res.code === 0) {
        this.$modal.msgSuccess(res.msg)
      }
    },
    importSoft(){
      this.reset();
      this.softOpen = true;
      this.title = "导入数据到南方片";
    },
    reset(){
      this.form={
        startTime: '',
        endTime: ''
      }
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      const startYear= this.formatDateToYearMonth(this.form.startTime)
      const endYear= this.formatDateToYearMonth(this.form.endTime)
      const param={
        startTime: startYear,
        endTime: endYear,
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          waterLeverApi.importDateToSoft(param).then(res => {
            if (res.code === 0) {
              this.$modal.msgSuccess(res.msg)
              this.softOpen = false;
            }
          })
        }
      });
    },
    cancel() {
      this.softOpen = false;
      this.reset();
    },
  },
}
</script>
<style scoped lang="scss">
.app-container {
  padding: 20px;
  background: #F2F2F2;
  height: calc(100vh - 100px);

  .el-form {
    background: #fff;
    padding: 10px;
    height: 6vh;
    border-radius: 4px;
    box-shadow: 0 0 10px 1px rgba(123, 123, 123, 0.4);
  }

  .main-content {
    height: calc(100vh - 150px);
    background: #fff;
    margin-top: 20px;
    padding: 5px;
    border-radius: 4px;
    box-shadow: 0 0 10px 1px rgba(123, 123, 123, 0.4);

    .main-title {
      height: 90px;

      .table-title {
        font-size: 25px;
        font-weight: bold;
        width: 100%;
        height: 60px;
        text-align: center;
      }

      .table-header {
        width: 100%;
        height: 30px;
        line-height: 30px;
        display: inline;
        padding: 0 20px;
        font-size: 14px;

        .table-time {
          display: inline;
          float: left;
          margin-left: 20px;
          font-size: 14px;
          color: #606266;
          font-weight: 700;
        }
      }
    }
  }

  :hover::-webkit-scrollbar {
    width: 0; /* 鼠标 hover 时显示滚动条 */
  }
}
</style>
