<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" type="border-card" @tab-change="handleTabChange">
      <el-tab-pane label="工程基础信息" name="base">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
          <el-form-item label="工程名称" prop="engName">
            <el-input v-model="queryParams.engName" placeholder="请输入工程名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="工程编码" prop="engCode">
            <el-input v-model="queryParams.engCode" placeholder="请输入工程编码" clearable style="width: 200px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="工程类型" prop="engType">
            <el-select v-model="queryParams.engType" placeholder="工程类型" clearable style="width: 200px">
              <el-option v-for="dict in slaj_eng_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </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="Plus" @click="handleAddBase">新增</el-button></el-col>
          <el-col :span="1.5"><el-button type="success" plain icon="Edit" :disabled="!currentBase" @click="handleEditBase">修改</el-button></el-col>
          <el-col :span="1.5"><el-button type="danger" plain icon="Delete" :disabled="!currentBase" @click="handleDelBase">删除</el-button></el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
        </el-row>

        <el-table v-loading="loading" :data="baseList" @row-click="handleBaseRowClick" highlight-current-row>
          <el-table-column label="工程编码" prop="engCode" align="center" width="140" />
          <el-table-column label="工程名称" prop="engName" align="center" :show-overflow-tooltip="true" />
          <el-table-column label="工程类型" prop="engType" align="center" width="120">
            <template #default="scope"><dict-tag :options="slaj_eng_type" :value="scope.row.engType" /></template>
          </el-table-column>
          <el-table-column label="工程规模" prop="engScal" align="center" width="100" />
          <el-table-column label="工程等别" prop="engGrad" align="center" width="100" />
          <el-table-column label="重要程度" prop="impoGrad" align="center" width="100" />
          <el-table-column label="工程状态" prop="engStat" align="center" width="100" />
          <el-table-column label="采集时间" prop="collTime" align="center" width="160">
            <template #default="scope"><span>{{ parseTime(scope.row.collTime) }}</span></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-tab-pane>

      <el-tab-pane label="工程类型属性" name="attr" v-if="currentBase">
        <template v-if="currentAttrType">
          <el-alert :title="`当前工程: ${currentBase.engName} (${getTypeLabel(currentAttrType)})`" type="info" :closable="false" style="margin-bottom:12px" />
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5"><el-button type="primary" plain icon="Plus" size="small" @click="handleAddAttr">新增属性</el-button></el-col>
            <el-col :span="1.5"><el-button type="success" plain icon="Edit" size="small" :disabled="!currentAttr" @click="handleEditAttr">修改</el-button></el-col>
            <el-col :span="1.5"><el-button type="danger" plain icon="Delete" size="small" :disabled="!currentAttr" @click="handleDelAttr">删除</el-button></el-col>
          </el-row>
          <el-table :data="attrList" v-loading="attrLoading" @row-click="handleAttrRowClick" highlight-current-row>
            <el-table-column v-for="col in attrColumns" :key="col.prop" :label="col.label" :prop="col.prop" align="center" :show-overflow-tooltip="true" :width="col.width" />
            <el-table-column label="采集时间" prop="collTime" align="center" width="160">
              <template #default="scope"><span>{{ parseTime(scope.row.collTime) }}</span></template>
            </el-table-column>
          </el-table>
        </template>
        <el-empty v-else description='请先在"工程基础信息"中选中一条记录' />
      </el-tab-pane>

      <el-tab-pane label="工程信息 OBJ_ENG" name="objeng">
        <el-form :model="objQuery" ref="objQueryRef" :inline="true" label-width="80px">
          <el-form-item label="工程名称" prop="engName">
            <el-input v-model="objQuery.engName" placeholder="请输入" clearable style="width: 200px" @keyup.enter="getObjEngList" />
          </el-form-item>
          <el-form-item><el-button type="primary" icon="Search" @click="getObjEngList">搜索</el-button></el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5"><el-button type="primary" plain icon="Plus" @click="handleAddObjEng">新增</el-button></el-col>
          <el-col :span="1.5"><el-button type="danger" plain icon="Delete" :disabled="!currentObjEng" @click="handleDelObjEng">删除</el-button></el-col>
        </el-row>
        <el-table :data="objEngList" v-loading="objEngLoading" @row-click="(row) => currentObjEng = row" highlight-current-row>
          <el-table-column label="工程编码" prop="engCode" align="center" width="140" />
          <el-table-column label="工程名称" prop="engName" align="center" :show-overflow-tooltip="true" />
          <el-table-column label="工程类型" prop="engType" align="center" width="120" />
          <el-table-column label="管理模式" prop="manageMode" align="center" width="120" />
        </el-table>
        <pagination v-show="objEngTotal > 0" :total="objEngTotal" v-model:page="objQuery.pageNum" v-model:limit="objQuery.pageSize" @pagination="getObjEngList" />
      </el-tab-pane>
    </el-tabs>

    <!-- 工程基础信息对话框 -->
    <el-dialog :title="baseDialogTitle" v-model="baseOpen" width="700px" append-to-body>
      <el-form :model="baseForm" ref="baseRef" label-width="100px">
        <el-row><el-col :span="12"><el-form-item label="工程编码" prop="engCode"><el-input v-model="baseForm.engCode" /></el-form-item></el-col>
        <el-col :span="12"><el-form-item label="工程名称" prop="engName"><el-input v-model="baseForm.engName" /></el-form-item></el-col></el-row>
        <el-row><el-col :span="12"><el-form-item label="工程类型" prop="engType"><el-select v-model="baseForm.engType" style="width:100%"><el-option v-for="d in slaj_eng_type" :key="d.value" :label="d.label" :value="d.value" /></el-select></el-form-item></el-col>
        <el-col :span="12"><el-form-item label="工程规模" prop="engScal"><el-input v-model="baseForm.engScal" /></el-form-item></el-col></el-row>
        <el-row><el-col :span="12"><el-form-item label="工程等别" prop="engGrad"><el-input v-model="baseForm.engGrad" /></el-form-item></el-col>
        <el-col :span="12"><el-form-item label="重要程度" prop="impoGrad"><el-input v-model="baseForm.impoGrad" /></el-form-item></el-col></el-row>
        <el-form-item label="开工日期" prop="startDate"><el-date-picker v-model="baseForm.startDate" type="date" value-format="YYYY-MM-DD" style="width:100%" /></el-form-item>
        <el-form-item label="完工日期" prop="compDate"><el-date-picker v-model="baseForm.compDate" type="date" value-format="YYYY-MM-DD" style="width:100%" /></el-form-item>
        <el-form-item label="备注" prop="note"><el-input v-model="baseForm.note" type="textarea" :rows="2" /></el-form-item>
      </el-form>
      <template #footer><el-button type="primary" @click="submitBase">确 定</el-button><el-button @click="baseOpen=false">取 消</el-button></template>
    </el-dialog>

    <!-- 类型属性对话框 -->
    <el-dialog :title="attrDialogTitle" v-model="attrOpen" width="600px" append-to-body>
      <el-form :model="attrForm" ref="attrRef" label-width="110px">
        <el-form-item v-for="f in attrFields" :key="f.prop" :label="f.label" :prop="f.prop">
          <el-input v-model="attrForm[f.prop]" :placeholder="'请输入' + f.label" />
        </el-form-item>
        <el-form-item label="备注" prop="note"><el-input v-model="attrForm.note" type="textarea" :rows="2" /></el-form-item>
      </el-form>
      <template #footer><el-button type="primary" @click="submitAttr">确 定</el-button><el-button @click="attrOpen=false">取 消</el-button></template>
    </el-dialog>

    <!-- OBJ_ENG 对话框 -->
    <el-dialog title="工程信息" v-model="objEngOpen" width="500px" append-to-body>
      <el-form :model="objEngForm" ref="objEngRef" label-width="100px">
        <el-form-item label="工程编码" prop="engCode"><el-input v-model="objEngForm.engCode" /></el-form-item>
        <el-form-item label="工程名称" prop="engName"><el-input v-model="objEngForm.engName" /></el-form-item>
        <el-form-item label="工程类型" prop="engType"><el-select v-model="objEngForm.engType" style="width:100%"><el-option v-for="d in slaj_eng_type" :key="d.value" :label="d.label" :value="d.value" /></el-select></el-form-item>
        <el-form-item label="管理模式" prop="manageMode"><el-input v-model="objEngForm.manageMode" /></el-form-item>
      </el-form>
      <template #footer><el-button type="primary" @click="submitObjEng">确 定</el-button><el-button @click="objEngOpen=false">取 消</el-button></template>
    </el-dialog>
  </div>
</template>

<script setup name="EngManage">
import { listEngBase, getEngBase, addEngBase, updateEngBase, delEngBase, listObjEng, getObjEng, addObjEng, updateObjEng, delObjEng, listEngAttr, getEngAttr, addEngAttr, updateEngAttr, delEngAttr } from "@/api/slaj/eng"

const { proxy } = getCurrentInstance()

// 工程类型字典
const slaj_eng_type = [
  { label: '水库工程', value: 'res' }, { label: '农村供水', value: 'cws' }, { label: '堤防工程', value: 'dike' },
  { label: '水电站', value: 'hyst' }, { label: '灌区工程', value: 'irr' }, { label: '泵站工程', value: 'pust' },
  { label: '淤地坝', value: 'sd' }, { label: '引调水', value: 'wadi' }, { label: '水闸工程', value: 'waga' },
  { label: '其他工程', value: 'othe' }
]

// 各类型对应的字段定义
const TYPE_FIELDS = {
  cws: [{ prop:'waterSource',label:'水源类型'},{ prop:'supplyMode',label:'供水方式'},{ prop:'dailySupply',label:'日供水量'},{ prop:'popuServed',label:'服务人口'},{ prop:'treatCapacity',label:'处理能力'},{ prop:'pipeLength',label:'管网长度'},{ prop:'pumpCount',label:'水泵数量'}],
  dike: [{ prop:'dikeLength',label:'堤防长度'},{ prop:'dikeHeight',label:'堤防高度'},{ prop:'topWidth',label:'堤顶宽度'},{ prop:'protArea',label:'保护面积'},{ prop:'protPopu',label:'保护人口'},{ prop:'desFlStand',label:'设计防洪标准'},{ prop:'dikeType',label:'堤防类型'},{ prop:'slopeRatio',label:'边坡比'}],
  hyst: [{ prop:'instCapacity',label:'装机容量'},{ prop:'annualOutput',label:'年发电量'},{ prop:'turbineType',label:'水轮机类型'},{ prop:'turbineCount',label:'机组数量'},{ prop:'headHeight',label:'水头高度'},{ prop:'flowRate',label:'设计流量'},{ prop:'damType',label:'坝型'},{ prop:'damHeight',label:'坝高'},{ prop:'reservoirCap',label:'库容'}],
  irr: [{ prop:'irrArea',label:'灌溉面积'},{ prop:'desFlow',label:'设计流量'},{ prop:'mainChanLen',label:'干渠长度'},{ prop:'branChanLen',label:'支渠长度'},{ prop:'waterSource',label:'水源'},{ prop:'irrMode',label:'灌溉方式'},{ prop:'benefitPopu',label:'受益人口'}],
  othe: [{ prop:'engTypeName',label:'工程类型名称'},{ prop:'engScale',label:'工程规模'},{ prop:'mainFunc',label:'主要功能'},{ prop:'investAmount',label:'投资额'},{ prop:'startDate',label:'开工日期'},{ prop:'compDate',label:'完工日期'}],
  pust: [{ prop:'pumpType',label:'水泵类型'},{ prop:'pumpCount',label:'水泵数量'},{ prop:'totalFlow',label:'总流量'},{ prop:'liftHeight',label:'扬程'},{ prop:'motorPower',label:'电机功率'},{ prop:'inletLevel',label:'进水水位'},{ prop:'outletLevel',label:'出水水位'},{ prop:'pipeDiam',label:'管径'}],
  sd: [{ prop:'damHeight',label:'坝高'},{ prop:'damLength',label:'坝长'},{ prop:'damVolume',label:'坝体方量'},{ prop:'siltCapacity',label:'淤积库容'},{ prop:'controlArea',label:'控制面积'},{ prop:'floodCap',label:'防洪库容'},{ prop:'damType',label:'坝型'},{ prop:'spillwayType',label:'溢洪道类型'}],
  wadi: [{ prop:'divFlow',label:'引水流量'},{ prop:'chanLength',label:'渠道长度'},{ prop:'divSource',label:'引水水源'},{ prop:'divTarget',label:'供水目标'},{ prop:'tunnelLength',label:'隧洞长度'},{ prop:'aqueductLen',label:'渡槽长度'},{ prop:'pipeDiam',label:'管径'},{ prop:'benefitArea',label:'受益面积'}],
  waga: [{ prop:'gateType',label:'闸门类型'},{ prop:'gateCount',label:'闸门数量'},{ prop:'gateWidth',label:'闸门宽度'},{ prop:'gateHeight',label:'闸门高度'},{ prop:'dischCap',label:'过闸流量'},{ prop:'desFlStand',label:'设计防洪标准'},{ prop:'operMode',label:'运行方式'},{ prop:'maxWaterLevel',label:'最高水位'},{ prop:'minWaterLevel',label:'最低水位'}]
}

const activeTab = ref("base")
const loading = ref(false), attrLoading = ref(false), objEngLoading = ref(false)
const showSearch = ref(true)
const total = ref(0), objEngTotal = ref(0)
const baseList = ref([]), attrList = ref([]), objEngList = ref([])
const currentBase = ref(null), currentAttr = ref(null), currentObjEng = ref(null)
const baseOpen = ref(false), attrOpen = ref(false), objEngOpen = ref(false)
const baseDialogTitle = ref(""), attrDialogTitle = ref("")
const currentAttrType = computed(() => currentBase.value?.engType || '')

// 工程基础信息查询参数
const data = reactive({
  queryParams: { pageNum:1, pageSize:10, engName:undefined, engCode:undefined, engType:undefined },
  baseForm: { guid:undefined, engCode:undefined, engName:undefined, engType:undefined, engScal:undefined, engGrad:undefined, impoGrad:undefined, startDate:undefined, compDate:undefined, note:undefined, orgGuid:undefined }
})
const { queryParams, baseForm } = toRefs(data)

const attrForm = reactive({})
const attrFields = computed(() => TYPE_FIELDS[currentAttrType.value] || [])

// OBJ_ENG
const objQuery = reactive({ pageNum:1, pageSize:10, engName:undefined })
const objEngForm = reactive({ guid:undefined, engCode:'', engName:'', engType:undefined, manageMode:'' })

function getTypeLabel(type) {
  const item = slaj_eng_type.find(d => d.value === type)
  return item ? item.label : type
}

// ===== 工程基础信息 CRUD =====
function getList() {
  loading.value = true
  listEngBase(queryParams.value).then(res => { baseList.value = res.rows; total.value = res.total; loading.value = false })
}
function handleQuery() { queryParams.value.pageNum = 1; getList() }
function resetQuery() { proxy.resetForm("queryRef"); handleQuery() }
function handleBaseRowClick(row) { currentBase.value = row; currentAttr.value = null }

function resetBaseForm() {
  Object.keys(baseForm.value).forEach(k => baseForm.value[k] = undefined)
}
function handleAddBase() { resetBaseForm(); baseDialogTitle.value = "新增工程"; baseOpen.value = true }
function handleEditBase() {
  if (!currentBase.value) return
  getEngBase(currentBase.value.guid).then(res => { Object.assign(baseForm.value, res.data); baseDialogTitle.value = "修改工程"; baseOpen.value = true })
}
function handleDelBase() {
  if (!currentBase.value) return
  proxy.$modal.confirm('是否确认删除该工程？').then(() => delEngBase(currentBase.value.guid)).then(() => { getList(); proxy.$modal.msgSuccess("删除成功"); currentBase.value = null })
}
function submitBase() {
  if (baseForm.value.guid) {
    updateEngBase(baseForm.value).then(() => { proxy.$modal.msgSuccess("修改成功"); baseOpen.value = false; getList() })
  } else {
    addEngBase(baseForm.value).then(() => { proxy.$modal.msgSuccess("新增成功"); baseOpen.value = false; getList() })
  }
}

// ===== 类型属性 CRUD =====
function getAttrList() {
  if (!currentAttrType.value) return
  attrLoading.value = true
  listEngAttr(currentAttrType.value, { engGuid: currentBase.value.engGuid || currentBase.value.guid }).then(res => { attrList.value = res.rows; attrLoading.value = false })
}
function handleAttrRowClick(row) { currentAttr.value = row }

function resetAttrForm() {
  Object.keys(attrForm).forEach(k => delete attrForm[k])
  attrForm.guid = undefined; attrForm.engGuid = currentBase.value.engGuid || currentBase.value.guid
  attrForm.engName = currentBase.value.engName
}
function handleAddAttr() { resetAttrForm(); attrDialogTitle.value = "新增属性"; attrOpen.value = true }
function handleEditAttr() {
  if (!currentAttr.value) return
  getEngAttr(currentAttrType.value, currentAttr.value.guid).then(res => {
    Object.keys(attrForm).forEach(k => delete attrForm[k])
    Object.assign(attrForm, res.data)
    attrDialogTitle.value = "修改属性"; attrOpen.value = true
  })
}
function handleDelAttr() {
  if (!currentAttr.value) return
  proxy.$modal.confirm('是否确认删除？').then(() => delEngAttr(currentAttrType.value, currentAttr.value.guid)).then(() => { getAttrList(); proxy.$modal.msgSuccess("删除成功"); currentAttr.value = null })
}
function submitAttr() {
  if (attrForm.guid) {
    updateEngAttr(currentAttrType.value, attrForm).then(() => { proxy.$modal.msgSuccess("修改成功"); attrOpen.value = false; getAttrList() })
  } else {
    addEngAttr(currentAttrType.value, attrForm).then(() => { proxy.$modal.msgSuccess("新增成功"); attrOpen.value = false; getAttrList() })
  }
}

// ===== OBJ_ENG CRUD =====
function getObjEngList() {
  objEngLoading.value = true
  listObjEng(objQuery).then(res => { objEngList.value = res.rows; objEngTotal.value = res.total; objEngLoading.value = false })
}
function handleAddObjEng() { Object.keys(objEngForm).forEach(k => objEngForm[k] = undefined); objEngOpen.value = true }
function handleDelObjEng() {
  if (!currentObjEng.value) return
  proxy.$modal.confirm('是否确认删除？').then(() => delObjEng(currentObjEng.value.guid)).then(() => { getObjEngList(); proxy.$modal.msgSuccess("删除成功"); currentObjEng.value = null })
}
function submitObjEng() {
  if (objEngForm.guid) {
    updateObjEng(objEngForm).then(() => { proxy.$modal.msgSuccess("修改成功"); objEngOpen.value = false; getObjEngList() })
  } else {
    addObjEng(objEngForm).then(() => { proxy.$modal.msgSuccess("新增成功"); objEngOpen.value = false; getObjEngList() })
  }
}

function handleTabChange(tab) {
  if (tab === 'attr') getAttrList()
  if (tab === 'objeng') getObjEngList()
}

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