<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="断面名称" prop="stnm">
        <el-input v-model="queryParams.stnm" placeholder="请输入断面名称" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="测站编码" prop="stcd">
        <el-input v-model="queryParams.stcd" placeholder="请输入测站编码" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="数据来源" prop="addvcd">
        <el-select v-model="queryParams.addvcd" placeholder="请选择数据来源" clearable>
          <el-option label="无锡(WX)" value="WX"/>
          <el-option label="江苏(JS)" value="JS"/>
          <el-option label="上海(SH)" value="SH"/>
          <el-option label="浙江(ZJ)" value="ZJ"/>
        </el-select>
      </el-form-item>
      <el-form-item label="监测时间">
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Upload"
            @click="handleUpload"
            size="mini"
            v-hasPermi="['yjjtgl:sz:upload']"
        >上传数据
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Download"
            @click="handleExport"
            size="mini"
            v-hasPermi="['yjjtgl:sz:export']"
        >导出数据
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column type="index" label="序号" width="60" align="center"/>
      <el-table-column prop="addvcd" label="数据来源" width="80" align="center">
        <template #default="scope">{{ getAddvcdLabel(scope.row.addvcd) }}</template>
      </el-table-column>
      <el-table-column prop="stnm" label="断面名称" width="150" align="center"/>
      <!--      <el-table-column prop="stcd" label="测站编码" width="100" />-->
      <el-table-column prop="rvnm" label="河流名称" width="150" align="center"/>
      <el-table-column prop="spt" label="监测时间" width="180" align="center">
        <template #default="scope">{{ formatDate(scope.row.spt) }}</template>
      </el-table-column>
      <el-table-column prop="wt" label="水温(℃)" width="80" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.wt) }}</template>
      </el-table-column>
      <el-table-column prop="ph" label="pH值" width="80" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.ph) }}</template>
      </el-table-column>
      <el-table-column prop="dox" label="溶解氧(mg/L)" width="120" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.dox) }}</template>
      </el-table-column>
      <el-table-column prop="codcr" label="化学需氧量(mg/L)" width="150" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.codcr) }}</template>
      </el-table-column>
      <el-table-column prop="bod5" label="五日生化需氧量(mg/L)" width="180" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.bod5) }}</template>
      </el-table-column>
      <el-table-column prop="cond" label="电导率(μS/cm)" width="120" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.cond) }}</template>
      </el-table-column>
      <el-table-column prop="codmn" label="高锰酸盐指数" width="120" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.codmn) }}</template>
      </el-table-column>
      <el-table-column prop="nh3n" label="氨氮(mg/L)" width="120" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.nh3n) }}</template>
      </el-table-column>
      <el-table-column prop="tp" label="总磷(mg/L)" width="120" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.tp) }}</template>
      </el-table-column>
      <el-table-column prop="tn" label="总氮(mg/L)" width="120" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.tn) }}</template>
      </el-table-column>
      <el-table-column prop="dtp" label="可溶性总磷(mg/L)" width="120" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.dtp) }}</template>
      </el-table-column>
      <el-table-column prop="watercolor" label="水色" width="120" align="center">
        <template #default="scope">{{ scope.row.watercolor }}</template>
      </el-table-column>
      <el-table-column prop="smell" label="臭和味" width="120" align="center">
        <template #default="scope">{{ scope.row.smell }}</template>
      </el-table-column>
      <el-table-column prop="clarity" label="透明度(㎝)" width="120" align="center">
        <template #default="scope">{{ scope.row.clarity }}</template>
      </el-table-column>
      <el-table-column prop="ss" label="悬浮物" width="120" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.ss) }}</template>
      </el-table-column>
      <el-table-column prop="thrd" label="总硬度" width="120" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.thrd) }}</template>
      </el-table-column>
      <el-table-column prop="no2" label="亚硝酸盐氮" width="120" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.no2) }}</template>
      </el-table-column>
      <el-table-column prop="turb" label="浊度" width="120" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.turb) }}</template>
      </el-table-column>
      <el-table-column prop="chla" label="叶绿素a(mg/L)" width="120" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.chla) }}</template>
      </el-table-column>
      <el-table-column prop="phyd" label="藻密度(个/L)" width="120" align="center">
        <template #default="scope">{{ formatDecimal(scope.row.phyd) }}</template>
      </el-table-column>
      <!--      <el-table-column label="操作" width="100" align="center">-->
      <!--        <template #default="scope">-->
      <!--          <el-button size="mini" type="text" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['yjjtgl:sz:remove']">删除</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 上传弹窗 -->
    <el-dialog title="水质数据上传" v-model="uploadVisible" width="500px" append-to-body>
      <el-form ref="uploadForm" label-width="100px">
        <el-form-item label="上传文件">
          <el-upload
              class="upload-demo"
              drag
              :action="uploadUrl"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :file-list="fileList"
              accept=".xlsx,.xls"
              :auto-upload="false"
              ref="uploadRef"
          >
            <el-icon class="el-icon--upload">
              <upload-filled/>
            </el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">
                <el-icon>
                  <warning/>
                </el-icon>
                <span>仅支持上传Excel文件(.xlsx,.xls)</span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <span class="text-muted">下载模板：</span>
          <el-button type="text" @click="downloadTemplate('sz')">水质数据上传模板</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitUpload">上传</el-button>
        <el-button @click="uploadVisible = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="YjjtSzData">
import {ref, reactive} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {listYjjtSzData, delYjjtSzData, uploadSzData, exportYjjtSzData} from '@/api/yjjt/sz'
import request from '@/utils/request'

const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const showSearch = ref(true)
const uploadVisible = ref(false)
const fileList = ref([])
const uploadRef = ref(null)

// 获取当前日期和当月第一天
const now = new Date()
const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
const formatDateStr = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const queryParams = reactive({
  pageNum: 1,
  pageSize: 15,
  stnm: '',
  stcd: '',
  addvcd: '',
  params: {
    beginTime: formatDateStr(firstDayOfMonth),
    endTime: formatDateStr(now)
  }
})

const dateRange = ref([formatDateStr(firstDayOfMonth), formatDateStr(now)])

const uploadUrl = import.meta.env.VITE_SERVICE_BASE_TITLE + '/yjjt/sz/upload'

const getList = async () => {
  loading.value = true
  try {
    const response = await listYjjtSzData(queryParams)
    tableData.value = response.rows
    total.value = response.total
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  queryParams.stnm = ''
  queryParams.stcd = ''
  queryParams.addvcd = ''
  queryParams.params.beginTime = formatDateStr(firstDayOfMonth)
  queryParams.params.endTime = formatDateStr(now)
  dateRange.value = [formatDateStr(firstDayOfMonth), formatDateStr(now)]
  handleQuery()
}

const handleDateChange = (val) => {
  if (val && val.length === 2) {
    queryParams.params.beginTime = val[0]
    queryParams.params.endTime = val[1]
  } else {
    queryParams.params.beginTime = ''
    queryParams.params.endTime = ''
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定删除该数据吗?', '提示', {type: 'warning'})
    await delYjjtSzData(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleUpload = () => {
  uploadVisible.value = true
}

const submitUpload = () => {
  uploadRef.value.submit()
}

const handleUploadSuccess = async (response) => {
  if (response.code === 200) {
    ElMessage.success(response.msg)
    uploadVisible.value = false
    fileList.value = []
    getList()
  } else {
    ElMessage.error(response.msg)
  }
}

const handleUploadError = () => {
  ElMessage.error('上传失败')
}

const handleExport = async () => {
  try {
    const response = await exportYjjtSzData(queryParams)
    const blob = new Blob([response])
    const filename = '水质数据_' + new Date().getTime() + '.xlsx'
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

const downloadTemplate = async (type) => {
  const templateNames = {
    sl: '引江济太水质数据上传模板.xlsx',
  }
  try {
    const response = await request({
      url: '/yjjt/template/' + type,
      method: 'get',
      responseType: 'blob'
    })
    const blob = new Blob([response])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = templateNames[type]
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('模板下载成功')
  } catch (error) {
    ElMessage.error('模板下载失败')
  }
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const formatDecimal = (value) => {
  if (value === null || value === undefined) return '-'
  return parseFloat(value).toFixed(2)
}

const getAddvcdLabel = (value) => {
  const labels = {
    'WX': '无锡',
    'JS': '江苏',
    'SH': '上海',
    'ZJ': '浙江'
  }
  return labels[value] || value
}

const handleSelectionChange = () => {
}

getList()
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.year-picker {
  width: 150px;
}

.source-select {
  width: 150px;
}

.type-select {
  width: 150px;
}

.mb8 {
  margin-bottom: 8px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  font-size: 14px;
  font-weight: bold;
}

:deep(.el-table td) {
  font-size: 14px;
}

:deep(.el-form-item__label) {
  font-size: 14px;
}

:deep(.el-input__inner) {
  font-size: 14px;
}

:deep(.el-button) {
  font-size: 14px;
}

:deep(.el-pagination) {
  font-size: 14px;
  margin-top: 15px;
}
</style>