<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <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="stnm">
        <el-input v-model="queryParams.stnm" placeholder="请输入测站名称" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="站点类型" prop="sttp">
        <el-select v-model="queryParams.sttp" placeholder="请选择站点类型" clearable>
          <el-option label="水位站" value="SW"/>
          <el-option label="流量站" value="LL"/>
          <el-option label="水质站" value="SZ"/>
        </el-select>
      </el-form-item>
      <el-form-item label="数据来源" prop="addvcd">
        <el-select v-model="queryParams.addvcd" placeholder="请选择数据来源" clearable>
          <el-option label="江苏" value="JS"/>
          <el-option label="无锡" value="WX"/>
          <el-option label="上海" value="SH"/>
          <el-option label="浙江" value="ZJ"/>
        </el-select>
      </el-form-item>
      <el-form-item label="年份" prop="year">
        <el-date-picker
            v-model="queryParams.year"
            type="year"
            placeholder="请选择年份"
            format="YYYY"
            value-format="YYYY"
            clearable
            @change="handleQuery"
        />
      </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">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList">
        <template #right>
          <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['yjjtgl:station:add']">新增站点
          </el-button>
          <el-button type="success" icon="Download" @click="handleExport" v-hasPermi="['yjjtgl:station:export']">导出
          </el-button>
          <el-button type="warning" icon="Upload" @click="handleImport" v-hasPermi="['yjjtgl:station:import']">导入
          </el-button>
          <el-button type="danger" icon="Delete" @click="handleBatchDelete" v-hasPermi="['yjjtgl:station:remove']"
                     :disabled="selectedIds.length === 0">批量删除
          </el-button>
        </template>
      </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="stcd" label="测站编码" width="120"/>
      <el-table-column prop="stnm" label="测站名称" width="150"/>
      <el-table-column prop="year" label="年份" width="80"/>
      <el-table-column prop="sttp" label="站点类型" width="100">
        <template #default="scope">{{ getSttpLabel(scope.row.sttp) }}</template>
      </el-table-column>
      <el-table-column prop="rvnm" label="河流名称" width="120"/>
      <el-table-column prop="hnnm" label="湖泊名称" width="120"/>
      <el-table-column prop="bsnm" label="水系名称" width="120"/>
      <el-table-column prop="stlc" label="站点位置" width="200"/>
      <!--      <el-table-column prop="lgtd" label="经度" width="130" align="right">-->
      <!--        <template #default="scope">{{ scope.row.lgtd ? scope.row.lgtd.toFixed(6) : '' }}</template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column prop="lttd" label="纬度" width="130" align="right">-->
      <!--        <template #default="scope">{{ scope.row.lttd ? scope.row.lttd.toFixed(6) : '' }}</template>-->
      <!--      </el-table-column>-->
      <el-table-column prop="addvcd" label="数据来源" width="100">
        <template #default="scope">{{ getAddvcdLabel(scope.row.addvcd) }}</template>
      </el-table-column>
      <el-table-column prop="jcdw" label="监测单位" width="220"/>
      <el-table-column prop="jcpc" label="监测频次" width="120"/>
      <el-table-column prop="jcxm" label="监测项目" width="150"/>
      <el-table-column prop="flag" label="标志" width="80">
        <template #default="scope">{{ getFlagLabel(scope.row.flag) }}</template>
      </el-table-column>
      <el-table-column prop="dbcd" label="数据库编码" width="120"/>
      <el-table-column prop="prov" label="所属省份" width="100"/>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button size="mini" type="primary" icon="Edit" @click="handleEdit(scope.row)"
                     v-hasPermi="['yjjtgl:station:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['yjjtgl:station: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="formVisible" width="700px" append-to-body>
      <el-form :model="form" ref="formRef" label-width="100px">
        <el-form-item label="测站编码" prop="stcd" required>
          <el-input v-model="form.stcd" :disabled="isEdit" placeholder="请输入测站编码"/>
        </el-form-item>
        <el-form-item label="年份" prop="year" required>
          <el-input v-model="form.year" :disabled="isEdit" placeholder="请输入年份"/>
        </el-form-item>
        <el-form-item label="测站名称" prop="stnm" required>
          <el-input v-model="form.stnm" placeholder="请输入测站名称"/>
        </el-form-item>
        <el-form-item label="站点类型" prop="sttp">
          <el-select v-model="form.sttp" placeholder="请选择站点类型">
            <el-option label="水位站" value="SW"/>
            <el-option label="流量站" value="LL"/>
            <el-option label="水质站" value="SZ"/>
          </el-select>
        </el-form-item>
        <el-form-item label="河流名称" prop="rvnm">
          <el-input v-model="form.rvnm" placeholder="请输入河流名称"/>
        </el-form-item>
        <el-form-item label="湖泊名称" prop="hnnm">
          <el-input v-model="form.hnnm" placeholder="请输入湖泊名称"/>
        </el-form-item>
        <el-form-item label="水系名称" prop="bsnm">
          <el-input v-model="form.bsnm" placeholder="请输入水系名称"/>
        </el-form-item>
        <el-form-item label="站点位置" prop="stlc">
          <el-input v-model="form.stlc" placeholder="请输入站点位置"/>
        </el-form-item>
        <el-form-item label="经度" prop="lgtd">
          <el-input v-model="form.lgtd" placeholder="请输入经度" type="number"/>
        </el-form-item>
        <el-form-item label="纬度" prop="lttd">
          <el-input v-model="form.lttd" placeholder="请输入纬度" type="number"/>
        </el-form-item>
        <el-form-item label="数据来源" prop="addvcd">
          <el-select v-model="form.addvcd" placeholder="请选择数据来源">
            <el-option label="江苏" value="JS"/>
            <el-option label="上海" value="SH"/>
            <el-option label="浙江" value="ZJ"/>
          </el-select>
        </el-form-item>
        <el-form-item label="监测单位" prop="jcdw">
          <el-input v-model="form.jcdw" placeholder="请输入监测单位"/>
        </el-form-item>
        <el-form-item label="监测频次" prop="jcpc">
          <el-input v-model="form.jcpc" placeholder="请输入监测频次"/>
        </el-form-item>
        <el-form-item label="监测项目" prop="jcxm">
          <el-input v-model="form.jcxm" placeholder="请输入监测项目"/>
        </el-form-item>
        <el-form-item label="标志" prop="flag">
          <el-select v-model="form.flag" placeholder="请选择标志">
            <el-option label="启用" value="1"/>
            <el-option label="停用" value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item label="数据库编码" prop="dbcd">
          <el-input v-model="form.dbcd" placeholder="请输入数据库编码"/>
        </el-form-item>
        <el-form-item label="所属省份" prop="prov">
          <el-input v-model="form.prov" placeholder="请输入所属省份"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="formVisible = false">取消</el-button>
      </template>
    </el-dialog>

    <!-- 导入弹窗 -->
    <el-dialog title="站点数据导入" v-model="importVisible" width="500px" append-to-body>
      <el-form :model="importForm" ref="importForm" label-width="100px">
        <el-form-item label="上传文件">
          <el-upload
              class="upload-demo"
              drag
              :action="uploadUrl"
              :data="{ bizType: importForm.bizType }"
              :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">站点模板</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitUpload">上传</el-button>
        <el-button @click="importVisible = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="YjjtStation">
import {ref, reactive} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
  listStation,
  getStation,
  addStation,
  updateStation,
  delStation,
  delStationBatch,
  exportStation,
  importStation,
  importStationTemplate
} from '@/api/yjjt/station'

const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const showSearch = ref(true)
const formVisible = ref(false)
const importVisible = ref(false)
const isEdit = ref(false)
const selectedIds = ref([])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 15,
  stcd: '',
  stnm: '',
  sttp: '',
  addvcd: '',
  year: ''
})

const form = reactive({
  stcd: '',
  year: '',
  stnm: '',
  sttp: '',
  rvnm: '',
  hnnm: '',
  bsnm: '',
  stlc: '',
  lgtd: null,
  lttd: null,
  addvcd: '',
  jcdw: '',
  jcpc: '',
  jcxm: '',
  flag: '1',
  dbcd: '',
  prov: '',
  remark: ''
})

const importForm = reactive({
  bizType: ''
})

const fileList = ref([])
const uploadRef = ref(null)
const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/yjjt/station/import'

const getList = async () => {
  loading.value = true
  try {
    const response = await listStation(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.stcd = ''
  queryParams.stnm = ''
  queryParams.sttp = ''
  queryParams.addvcd = ''
  queryParams.year = ''
  handleQuery()
}

const handleAdd = () => {
  isEdit.value = false
  form.stcd = ''
  form.year = ''
  form.stnm = ''
  form.sttp = ''
  form.rvnm = ''
  form.hnnm = ''
  form.bsnm = ''
  form.stlc = ''
  form.lgtd = null
  form.lttd = null
  form.addvcd = ''
  form.jcdw = ''
  form.jcpc = ''
  form.jcxm = ''
  form.flag = '1'
  form.dbcd = ''
  form.prov = ''
  form.remark = ''
  formVisible.value = true
}

const handleEdit = async (row) => {
  isEdit.value = true
  try {
    const response = await getStation(row.stcd, row.year)
    Object.assign(form, response.data)
    formVisible.value = true
  } catch (error) {
    ElMessage.error('获取站点信息失败')
  }
}

const submitForm = async () => {
  try {
    if (isEdit.value) {
      await updateStation(form)
      ElMessage.success('修改成功')
    } else {
      await addStation(form)
      ElMessage.success('新增成功')
    }
    formVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

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

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm('确定删除选中的站点吗?', '提示', {type: 'warning'})
    await delStationBatch(selectedIds.value)
    ElMessage.success('批量删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

const handleSelectionChange = (val) => {
  selectedIds.value = val
}

const handleExport = async () => {
  try {
    const response = await exportStation(queryParams)
    const blob = new Blob([response])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '引江济太站点数据.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

const handleImport = () => {
  fileList.value = []
  importVisible.value = true
}

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

const handleUploadSuccess = () => {
  ElMessage.success('导入成功')
  importVisible.value = false
  getList()
}

const handleUploadError = () => {
  ElMessage.error('导入失败')
}

const downloadTemplate = async () => {
  try {
    const response = await importStationTemplate()
    const blob = new Blob([response])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '引江济太站点导入模板.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('模板下载成功')
  } catch (error) {
    ElMessage.error('模板下载失败')
  }
}

const getSttpLabel = (value) => {
  const labels = {
    'SW': '水位站',
    'LL': '流量站',
    'SZ': '水质站'
  }
  return labels[value] || value
}

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

const getFlagLabel = (value) => {
  const labels = {
    '1': '启用',
    '0': '停用'
  }
  return labels[value] || value
}

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>
