<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>水库工程管理</span>
          <el-button type="primary" size="small" style="float:right" @click="handleAdd">新增水库</el-button>
        </div>
      </template>

      <el-form :model="queryParams" :inline="true" size="small">
        <el-form-item label="水库名称">
          <el-input v-model="queryParams.resName" placeholder="请输入水库名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="管理单位">
          <el-input v-model="queryParams.admDep" placeholder="请输入管理单位" clearable @keyup.enter="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-button type="info" icon="DataAnalysis" @click="handleStats">统计</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="list" stripe>
        <el-table-column prop="resCode" label="编码" width="100" />
        <el-table-column prop="resName" label="水库名称" min-width="140" />
        <el-table-column prop="resLoc" label="位置" width="140" />
        <el-table-column prop="engScal" label="规模" width="90" />
        <el-table-column prop="totCap" label="总库容(万m³)" width="120" />
        <el-table-column prop="watShedArea" label="集水面积(km²)" width="120" />
        <el-table-column prop="engStat" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.engStat === '1' ? 'success' : 'warning'" size="small">
              {{ scope.row.engStat === '1' ? '正常' : scope.row.engStat === '0' ? '停用' : scope.row.engStat }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="admDep" label="管理单位" width="140" />
        <el-table-column prop="updDate" label="更新日期" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="View" @click="handleDetail(scope.row)">查看</el-button>
            <el-button type="primary" link icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <el-dialog :title="title" v-model="open" width="720px" append-to-body>
      <el-form :model="form" label-width="130px">
        <el-row>
          <el-col :span="12"><el-form-item label="水库编码"><el-input v-model="form.resCode" :disabled="title === '编辑水库'" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="水库名称"><el-input v-model="form.resName" /></el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"><el-form-item label="位置"><el-input v-model="form.resLoc" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="类型"><el-input v-model="form.resType" /></el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"><el-form-item label="总库容(万m³)"><el-input-number v-model="form.totCap" :min="0" :step="0.01" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="正常库容(万m³)"><el-input-number v-model="form.normPoolStagCap" :min="0" :step="0.01" /></el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"><el-form-item label="防洪库容(万m³)"><el-input-number v-model="form.flcoCap" :min="0" :step="0.01" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="调洪库容(万m³)"><el-input-number v-model="form.storFlCap" :min="0" :step="0.01" /></el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"><el-form-item label="集水面积(km²)"><el-input-number v-model="form.watShedArea" :min="0" :step="0.1" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="工程状态">
            <el-select v-model="form.engStat"><el-option label="正常" value="1" /><el-option label="停用" value="0" /></el-select>
          </el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"><el-form-item label="管理单位"><el-input v-model="form.admDep" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="开工日期"><el-input v-model="form.startDate" type="date" /></el-form-item></el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button v-if="title === '水库详情'" icon="User" @click="handlePerson(form)">责任人信息</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="personVisible" title="水库责任人信息" width="700px" append-to-body>
      <el-tabs v-model="personTab">
        <el-tab-pane label="行政责任人" name="admin">
          <el-descriptions :column="2" border v-if="personData.adminName">
            <el-descriptions-item label="姓名">{{ personData.adminName }}</el-descriptions-item>
            <el-descriptions-item label="职务">{{ personData.adminDuty }}</el-descriptions-item>
            <el-descriptions-item label="联系方式" :span="2">{{ personData.adminPhone }}</el-descriptions-item>
          </el-descriptions>
          <el-empty v-else description="暂无数据" />
        </el-tab-pane>
        <el-tab-pane label="技术责任人" name="tech">
          <el-descriptions :column="2" border v-if="personData.techName">
            <el-descriptions-item label="姓名">{{ personData.techName }}</el-descriptions-item>
            <el-descriptions-item label="职务">{{ personData.techDuty }}</el-descriptions-item>
            <el-descriptions-item label="联系方式" :span="2">{{ personData.techPhone }}</el-descriptions-item>
          </el-descriptions>
          <el-empty v-else description="暂无数据" />
        </el-tab-pane>
        <el-tab-pane label="巡查责任人" name="patrol">
          <el-descriptions :column="2" border v-if="personData.patrolName">
            <el-descriptions-item label="姓名">{{ personData.patrolName }}</el-descriptions-item>
            <el-descriptions-item label="职务">{{ personData.patrolDuty }}</el-descriptions-item>
            <el-descriptions-item label="联系方式" :span="2">{{ personData.patrolPhone }}</el-descriptions-item>
          </el-descriptions>
          <el-empty v-else description="暂无数据" />
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <el-button @click="personVisible = false">关 闭</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="statsVisible" title="水库类型分布统计" width="600px" append-to-body>
      <el-table :data="statsData" stripe v-loading="statsLoading">
        <el-table-column prop="name" label="类型" min-width="120" />
        <el-table-column prop="value" label="数量" width="100" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Reservoir">
import { getReservoirList } from '@/api/slgc/gc/index'
import { getReservoir, addReservoir, updateReservoir, delReservoir, getReservoirCountType } from '@/api/slgc/reservoir/index'

const { proxy } = getCurrentInstance()
const loading = ref(true)
const total = ref(0)
const open = ref(false)
const title = ref('')
const list = ref([])
const queryParams = reactive({ pageNum: 1, pageSize: 10, resName: undefined, admDep: undefined })
const form = ref({})
const statsVisible = ref(false)
const statsLoading = ref(false)
const statsData = ref([])
const personVisible = ref(false)
const personTab = ref('admin')
const personData = ref({})
const personLoading = ref(false)

function getList() {
  loading.value = true
  getReservoirList(queryParams).then(res => {
    list.value = res.rows; total.value = res.total; loading.value = false
  })
}
function handleQuery() { queryParams.pageNum = 1; getList() }
function resetQuery() { queryParams.resName = undefined; queryParams.admDep = undefined; handleQuery() }
function handleDetail(row) {
  getReservoir(row.resCode).then(res => { form.value = res.data; title.value = '水库详情'; open.value = true })
}
function handleEdit(row) {
  getReservoir(row.resCode).then(res => { form.value = res.data; title.value = '编辑水库'; open.value = true })
}
function submitForm() {
  const method = form.value.resCode && title.value === '编辑水库' ? updateReservoir : addReservoir
  method(form.value).then(() => { proxy.$modal.msgSuccess('操作成功'); open.value = false; getList() })
}
function cancel() { open.value = false }

function handleAdd() {
  form.value = { engStat: '1' }
  title.value = '新增水库'
  open.value = true
}

function handleDelete(row) {
  proxy.$modal.confirm('确认删除水库"' + row.resName + '"？').then(() => {
    delReservoir(row.resCode).then(() => {
      proxy.$modal.msgSuccess('删除成功')
      getList()
    })
  })
}

function handleStats() {
  statsVisible.value = true
  statsLoading.value = true
  getReservoirCountType().then(res => {
    statsData.value = res.data || []
    statsLoading.value = false
  }).catch(() => { statsLoading.value = false })
}

function handlePerson(row) {
  personVisible.value = true
  personTab.value = 'admin'
  personData.value = {}
  personLoading.value = true
  const names = [row.resName, row.resName.replace(/水库$/, ''), row.resName + '水库']
  const outFields = '行政责任人姓名,行政责任人职务,行政责任人联系方式,技术责任人姓名,技术责任人职务,技术责任人联系方式,巡查责任人姓名,巡查责任人职务,巡查责任人联系方式'
  const layers = [5, 6, 7]
  let found = false
  layers.reduce((seq, layerId) => {
    return seq.catch(() => {
      const where = names.map(n => `水库名称 like '%25${encodeURIComponent(n)}%25'`).join(' or ')
      const url = `http://10.8.4.128/server/rest/services/OneMap/TH_SLGC/MapServer/${layerId}/query?f=json&where=${where}&returnGeometry=false&outFields=${outFields}&outSR=4490`
      return fetch(url).then(r => r.json()).then(data => {
        if (data.features && data.features.length > 0) {
          found = true
          const attrs = data.features[0].attributes
          const d = personData.value
          d.adminName = attrs['行政责任人姓名'] || '-'
          d.adminDuty = attrs['行政责任人职务'] || '-'
          d.adminPhone = attrs['行政责任人联系方式'] || '-'
          d.techName = attrs['技术责任人姓名'] || '-'
          d.techDuty = attrs['技术责任人职务'] || '-'
          d.techPhone = attrs['技术责任人联系方式'] || '-'
          d.patrolName = attrs['巡查责任人姓名'] || '-'
          d.patrolDuty = attrs['巡查责任人职务'] || '-'
          d.patrolPhone = attrs['巡查责任人联系方式'] || '-'
          return Promise.resolve()
        }
        return Promise.reject()
      })
    })
  }, Promise.reject()).catch(() => {
    if (!found) proxy.$modal.msgWarning('未查询到责任人信息')
  }).finally(() => { personLoading.value = false })
}

onMounted(() => { getList() })
</script>

<style scoped>
.card-header { font-weight: 600; font-size: 16px; }
</style>
