<template>
  <div class="water-page facility-page">
    <div v-if="errorMessage" class="facility-error">
      <el-alert :title="errorMessage" type="error" show-icon :closable="false" />
      <el-button type="primary" link size="small" @click="retryRequest">重试</el-button>
    </div>
    <!-- 页头 -->
    <div class="page-heading">
      <div class="page-title">
        <span class="page-title-icon"><el-icon><Odometer /></el-icon></span>
        <div><h2>泵站信息查询</h2><span class="muted">泵站档案、能力与运行状态维护</span></div>
      </div>
      <el-button class="heading-refresh" :icon="Refresh" :loading="loading" @click="getList">刷新</el-button>
    </div>
    <!-- 筛选卡 -->
    <el-card shadow="never" class="filter-card">
      <template #header>
        <div class="filter-card-header">
          <div class="card-title"><el-icon><Search /></el-icon><span>筛选</span></div>
          <div class="card-actions">
            <el-button type="primary" plain icon="Plus" size="small" @click="handleAdd" v-hasPermi="['waterSupply:pumpStation:add']">新增</el-button>
            <el-button type="danger" plain icon="Delete" size="small" :disabled="multiple" @click="handleDelete" v-hasPermi="['waterSupply:pumpStation:remove']">删除</el-button>
            <el-button type="success" plain icon="Download" size="small" @click="handleExport" v-hasPermi="['waterSupply:waterPumpStation:export']">导出</el-button>
            <el-button type="info" plain icon="Upload" size="small" @click="importVisible = true" v-hasPermi="['waterSupply:waterPumpStation:import']">导入</el-button>
          </div>
        </div>
      </template>
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px">
        <el-form-item label="泵站编号" prop="stationCode">
          <el-input v-model="queryParams.stationCode" placeholder="请输入泵站编号" clearable size="small" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="泵站名称" prop="stationName">
          <el-input v-model="queryParams.stationName" placeholder="请输入泵站名称" clearable size="small" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="运行状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small" style="width: 120px">
            <el-option label="正常" value="0" />
            <el-option label="故障停运" value="1" />
            <el-option label="检修中" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="principal">
          <el-input v-model="queryParams.principal" placeholder="请输入负责人" clearable size="small" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            size="small"
            style="width: 240px"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" size="small" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格卡 -->
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="card-title"><el-icon><List /></el-icon><span>泵站清单</span></div>
      </template>
      <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="泵站编号" align="center" prop="stationCode" :show-overflow-tooltip="true" min-width="120" />
        <el-table-column label="泵站名称" align="center" prop="stationName" :show-overflow-tooltip="true" min-width="140" />
        <el-table-column label="泵站地址" align="center" prop="location" :show-overflow-tooltip="true" min-width="160" />
        <el-table-column label="经度" align="center" prop="longitude" width="120" />
        <el-table-column label="纬度" align="center" prop="latitude" width="120" />
        <el-table-column label="水泵数量" align="center" prop="pumpCount" width="90" />
        <el-table-column label="设计流量(m³/h)" align="center" prop="designFlow" width="130" />
        <el-table-column label="设计扬程(m)" align="center" prop="designHead" width="110" />
        <el-table-column label="装机容量(kW)" align="center" prop="powerCapacity" width="120" />
        <el-table-column label="投运日期" align="center" prop="commissionDate" width="110" />
        <el-table-column label="运行状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)" size="small">{{ statusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="负责人" align="center" prop="principal" width="100" />
        <el-table-column label="联系电话" align="center" prop="contactPhone" width="120" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="操作" align="center" width="168" fixed="right">
          <template #default="{ row }">
            <div class="facility-row-actions">
              <el-tooltip content="查看详情" placement="top"><el-button class="facility-row-action is-detail" aria-label="查看详情" size="small" type="primary" plain circle icon="View" @click="handleDetail(row)" /></el-tooltip>
              <el-tooltip content="修改信息" placement="top"><el-button class="facility-row-action is-edit" aria-label="修改信息" size="small" type="warning" plain circle icon="Edit" @click="handleUpdate(row)" v-hasPermi="['waterSupply:pumpStation:edit']" /></el-tooltip>
              <el-tooltip content="删除记录" placement="top"><el-button class="facility-row-action is-delete" aria-label="删除记录" size="small" type="danger" plain circle icon="Delete" @click="handleDelete(row)" v-hasPermi="['waterSupply:pumpStation:remove']" /></el-tooltip>
            </div>
          </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-drawer :title="dialogTitle" v-model="dialogVisible" class="facility-form-drawer" direction="rtl" size="760px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="泵站编号" prop="stationCode">
              <el-input v-model="form.stationCode" placeholder="请输入泵站编号" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="泵站名称" prop="stationName">
              <el-input v-model="form.stationName" placeholder="请输入泵站名称" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="泵站地址" prop="location">
              <el-input v-model="form.location" placeholder="请输入泵站地址" maxlength="200" />
            </el-form-item>
          </el-col>
          <el-col :span="12"><el-form-item label="经度" prop="longitude"><el-input-number v-model="form.longitude" :precision="8" :step="0.00000001" controls-position="right" style="width: 100%" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="纬度" prop="latitude"><el-input-number v-model="form.latitude" :precision="8" :step="0.00000001" controls-position="right" style="width: 100%" /></el-form-item></el-col>
          <el-col :span="12">
            <el-form-item label="水泵数量" prop="pumpCount">
              <el-input-number v-model="form.pumpCount" :min="0" :precision="0" style="width: 100%" placeholder="请输入水泵数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设计流量(m³/h)" prop="designFlow">
              <el-input-number v-model="form.designFlow" :min="0" :precision="2" style="width: 100%" placeholder="请输入设计流量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设计扬程(m)" prop="designHead">
              <el-input-number v-model="form.designHead" :min="0" :precision="2" style="width: 100%" placeholder="请输入设计扬程" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="装机容量(kW)" prop="powerCapacity">
              <el-input-number v-model="form.powerCapacity" :min="0" :precision="2" style="width: 100%" placeholder="请输入装机容量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="投运日期" prop="commissionDate">
              <el-date-picker v-model="form.commissionDate" type="date" placeholder="请选择投运日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运行状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">故障停运</el-radio>
                <el-radio label="2">检修中</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="principal">
              <el-input v-model="form.principal" placeholder="请输入负责人" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" maxlength="500" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </template>
    </el-drawer>

    <!-- 详情抽屉 -->
    <el-drawer title="泵站详情" v-model="detailVisible" class="detail-drawer" direction="rtl" size="650px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="泵站编号">{{ detailData.stationCode }}</el-descriptions-item>
        <el-descriptions-item label="泵站名称">{{ detailData.stationName }}</el-descriptions-item>
        <el-descriptions-item label="泵站地址" :span="2">{{ detailData.location }}</el-descriptions-item>
        <el-descriptions-item label="经度">{{ detailData.longitude }}</el-descriptions-item>
        <el-descriptions-item label="纬度">{{ detailData.latitude }}</el-descriptions-item>
        <el-descriptions-item label="水泵数量">{{ detailData.pumpCount }}</el-descriptions-item>
        <el-descriptions-item label="设计流量(m³/h)">{{ detailData.designFlow }}</el-descriptions-item>
        <el-descriptions-item label="设计扬程(m)">{{ detailData.designHead }}</el-descriptions-item>
        <el-descriptions-item label="装机容量(kW)">{{ detailData.powerCapacity }}</el-descriptions-item>
        <el-descriptions-item label="投运日期">{{ detailData.commissionDate }}</el-descriptions-item>
        <el-descriptions-item label="运行状态">
          <el-tag :type="statusTagType(detailData.status)" size="small">{{ statusLabel(detailData.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="负责人">{{ detailData.principal }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detailData.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailData.remark }}</el-descriptions-item>
        <el-descriptions-item label="创建者">{{ detailData.createBy }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新者">{{ detailData.updateBy }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.updateTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible = false">关 闭</el-button>
      </template>
    </el-drawer>

    <WaterFacilityImportDialog v-model="importVisible" title="泵站信息" upload-url="/api/water/pumpStation/importData" template-url="/api/water/pumpStation/importTemplate" @imported="getList" />

    <!-- 回收站对话框 -->
    <el-dialog title="回收站" v-model="recycleVisible" width="900px" append-to-body>
      <el-form :model="recycleQuery" ref="recycleForm" :inline="true" size="small">
        <el-form-item label="泵站编号" prop="stationCode">
          <el-input v-model="recycleQuery.stationCode" placeholder="请输入编号" clearable />
        </el-form-item>
        <el-form-item label="泵站名称" prop="stationName">
          <el-input v-model="recycleQuery.stationName" placeholder="请输入名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getRecycleList">搜索</el-button>
          <el-button icon="Refresh" @click="resetRecycleQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="recycleLoading" :data="recycleData" @selection-change="handleRecycleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="泵站编号" align="center" prop="stationCode" />
        <el-table-column label="泵站名称" align="center" prop="stationName" />
        <el-table-column label="泵站地址" align="center" prop="location" :show-overflow-tooltip="true" />
        <el-table-column label="负责人" align="center" prop="principal" width="100" />
        <el-table-column label="运行状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)" size="small">{{ statusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="删除时间" align="center" prop="updateTime" width="160" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="{ row }">
            <el-button size="small" type="text" icon="RefreshLeft" @click="handleRestore(row)">恢复</el-button>
            <el-button size="small" type="text" icon="Delete" @click="handleDeletePhysically(row)">
              <span style="color: #F56C6C">彻底删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="recycleTotal > 0" :total="recycleTotal" v-model:page="recycleQuery.pageNum" v-model:limit="recycleQuery.pageSize" @pagination="getRecycleList" />
    </el-dialog>
  </div>
</template>

<script>
import { listPumpStation, getPumpStation, addPumpStation, updatePumpStation, delPumpStation, listRecyclePumpStation, restorePumpStation, deletePhysicallyPumpStation } from '@/api/pipeNetwork/waterPumpStation'
import { saveAs } from 'file-saver'
import { exportWaterPumpStation } from '@/api/pipeNetwork/waterSupply'
import { buildWaterFacilityQuery, getRequestErrorMessage } from '@/utils/waterFacilityQuery'
import WaterFacilityImportDialog from '@/views/subSystem/waterSupply/components/WaterFacilityImportDialog.vue'

export default {
  name: 'WaterPumpStation',
  components: { WaterFacilityImportDialog },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      tableData: [],
      dateRange: [],
      dialogTitle: '',
      dialogVisible: false,
      detailVisible: false,
      importVisible: false,
      detailData: {},
      recycleVisible: false,
      recycleLoading: false,
      recycleData: [],
      recycleTotal: 0,
      recycleIds: [],
      errorMessage: '',
      retryAction: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationCode: undefined,
        stationName: undefined,
        status: undefined,
        principal: undefined
      },
      recycleQuery: {
        pageNum: 1,
        pageSize: 10,
        stationCode: undefined,
        stationName: undefined
      },
      form: {},
      rules: {
        stationCode: [
          { required: true, message: '泵站编号不能为空', trigger: 'blur' }
        ],
        stationName: [
          { required: true, message: '泵站名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      this.errorMessage = ''
      this.retryAction = this.getList
      listPumpStation(buildWaterFacilityQuery(this.queryParams, this.dateRange)).then(response => {
        this.tableData = response.data.records
        this.total = response.data.total
        this.loading = false
      }).catch(error => {
        this.loading = false
        this.errorMessage = getRequestErrorMessage(error, '泵站信息查询失败，请稍后重试')
      })
    },
    retryRequest() {
      if (this.retryAction) this.retryAction()
    },
    statusTagType(status) {
      const map = { '0': 'success', '1': 'danger', '2': 'warning' }
      return map[status] || 'info'
    },
    statusLabel(status) {
      const map = { '0': '正常', '1': '故障停运', '2': '检修中' }
      return map[status] || '未知'
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleExport() {
      this.errorMessage = ''
      this.retryAction = this.handleExport
      exportWaterPumpStation(buildWaterFacilityQuery(this.queryParams, this.dateRange)).then(blob => {
        saveAs(new Blob([blob]), `泵站信息_${new Date().toISOString().slice(0, 10)}.xlsx`)
      }).catch(error => {
        this.errorMessage = getRequestErrorMessage(error, '泵站信息导出失败，请稍后重试')
      })
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleRecycleSelectionChange(selection) {
      this.recycleIds = selection.map(item => item.id)
    },
    handleAdd() {
      this.reset()
      this.dialogTitle = '新增泵站信息'
      this.dialogVisible = true
    },
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPumpStation(id).then(response => {
        this.form = response.data
        this.dialogTitle = '修改泵站信息'
        this.dialogVisible = true
      })
    },
    handleDetail(row) {
      this.errorMessage = ''
      this.retryAction = () => this.handleDetail(row)
      getPumpStation(row.id).then(response => {
        this.detailData = response.data
        this.detailVisible = true
      }).catch(error => {
        this.errorMessage = getRequestErrorMessage(error, '泵站详情查询失败，请稍后重试')
      })
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updatePumpStation(this.form).then(() => {
              this.$modal.msgSuccess('修改成功')
              this.dialogVisible = false
              this.getList()
            })
          } else {
            addPumpStation(this.form).then(() => {
              this.$modal.msgSuccess('新增成功')
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    },
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids
      this.$modal.confirm('是否确认删除泵站编号为"' + ids.join(',') + '"的数据项？').then(() => {
        return delPumpStation(ids.join(','))
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    handleRecycle() {
      this.recycleVisible = true
      this.getRecycleList()
    },
    getRecycleList() {
      this.recycleLoading = true
      listRecyclePumpStation(this.recycleQuery).then(response => {
        this.recycleData = response.data.records
        this.recycleTotal = response.data.total
        this.recycleLoading = false
      }).catch(() => {
        this.recycleLoading = false
      })
    },
    resetRecycleQuery() {
      this.resetForm('recycleForm')
      this.getRecycleList()
    },
    handleRestore(row) {
      const ids = row.id || this.recycleIds
      this.$modal.confirm('是否确认恢复该数据？').then(() => {
        return restorePumpStation(Array.isArray(ids) ? ids.join(',') : ids)
      }).then(() => {
        this.getRecycleList()
        this.getList()
        this.$modal.msgSuccess('恢复成功')
      }).catch(() => {})
    },
    handleDeletePhysically(row) {
      const ids = row.id || this.recycleIds
      this.$modal.confirm('彻底删除后数据不可恢复，是否继续？').then(() => {
        return deletePhysicallyPumpStation(Array.isArray(ids) ? ids.join(',') : ids)
      }).then(() => {
        this.getRecycleList()
        this.$modal.msgSuccess('彻底删除成功')
      }).catch(() => {})
    },
    reset() {
      this.form = {
        status: '0'
      }
      this.resetForm('form')
    }
  }
}
</script>

<style scoped lang="scss">
@use '../../waterSupply/components/waterFacilityPageTheme.scss';
</style>
