<template>
  <div class="system-page config-page">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon :size="20" color="#409EFF">
              <OfficeBuilding/>
            </el-icon>
            <span class="page-title">本单位信息</span>
          </div>
          <div class="search-right">
            <el-button v-if="!editing" type="primary" @click="startEdit">
              <el-icon>
                <Edit/>
              </el-icon>
              编辑
            </el-button>
            <el-button v-if="editing" type="primary" @click="submitForm" :loading="saving">
              <el-icon>
                <Check/>
              </el-icon>
              保存
            </el-button>
            <el-button v-if="editing" @click="cancelEdit">取消</el-button>
            <el-button @click="refresh">
              <el-icon>
                <Refresh/>
              </el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="190px" v-loading="loading"
               style="padding: 20px;">

        <!-- 水利机构 (orgType=1) 单位信息填报 -->
        <template v-if="form.type === '1'">
          <el-divider content-position="left">单位信息填报</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="单位名称" prop="deptName">
                <el-input v-model="form.deptName" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="社会信用代码" prop="socCreCode">
                <el-input v-model="form.socCreCode" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <AdSelect label="所属行政区" v-model="form.adGuid" :disabled="!editing"></AdSelect>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位地址" prop="addr">
                <el-input v-model="form.addr" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="行政管辖范围" prop="jurd">
                <el-input v-model="form.jurd" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="标准化等级" prop="stanGrad">
                <el-select v-model="form.stanGrad" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in slaj_stan_grad" :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="fundSour">
                <el-select v-model="form.fundSour" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in slaj_fund_sour" :key="d.value" :label="d.label" :value="d.value"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">人员信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="主要负责人" prop="leader">
                <el-input v-model="form.leader" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="主要负责人电话" prop="phone">
                <el-input v-model="form.phone" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分管安全负责人" prop="safetyLegPers">
                <el-input v-model="form.safetyLegPers" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分管安全负责人电话" prop="safetyLegPersTel">
                <el-input v-model="form.safetyLegPersTel" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="安全生产联系人" prop="safeProdConta">
                <el-input v-model="form.safeProdConta" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="安全生产联系人电话" prop="safeProdContaTel">
                <el-input v-model="form.safeProdContaTel" :disabled="!editing"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">其他信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="从业人员人数" prop="workPopNum">
                <el-input v-model="form.workPopNum" :disabled="!editing" type="number" :min="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="事故隐患内部举报奖励机制" prop="accReportMech">
                <el-select v-model="form.accReportMech" :disabled="!editing" style="width:100%">
                  <el-option label="已建立" value="1"/>
                  <el-option label="未建立" value="0"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">附件上传</el-divider>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="标准化证书附件">
                <FileUpload v-model="form.stanCertFiles" :disabled="!editing" :limit="3" bizMedia
                            bisTablename="ORG_MESSAGE" :bisGuid="form.deptId" bisRelColumns="标准化证书">
                </FileUpload>
                <div class="upload-notice">
                  本平台为互联网非涉密平台，严禁处理、传输国家秘密。请确认扫描、传输的文件资料不涉及国家秘密。
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="营业执照附件">
                <FileUpload v-model="form.bizLicenseFiles" :disabled="!editing" :limit="3" bizMedia
                            bisTablename="ORG_MESSAGE" :bisGuid="form.deptId" bisRelColumns="营业执照"/>
                <div class="upload-notice">
                  本平台为互联网非涉密平台，严禁处理、传输国家秘密。请确认扫描、传输的文件资料不涉及国家秘密。
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="承诺书附件">
                <FileUpload v-model="form.pledgeFiles" :disabled="!editing" :limit="3" bizMedia
                            bisTablename="ORG_MESSAGE" :bisGuid="form.deptId" bisRelColumns="承诺书"/>
                <div class="upload-notice">
                  本平台为互联网非涉密平台，严禁处理、传输国家秘密。请确认扫描、传输的文件资料不涉及国家秘密。
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <!-- 参建单位 (orgType=2) -->
        <template v-if="form.type === '2'">
          <el-divider content-position="left">基础信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="机构代码" prop="orgCode">
                <el-input v-model="form.orgCode" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="机构名称" prop="deptName">
                <el-input v-model="form.deptName" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="级别" prop="orgLevel">
                <el-select v-model="form.orgLevel" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in slaj_org_level" :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="orgType">
                <el-select v-model="form.orgType" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in UNIT_TYPE_OPTIONS" :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="ordernum">
                <el-input v-model="form.ordernum" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in slaj_org_status" :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="adCode">
                <el-input v-model="form.adCode" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="管辖范围" prop="jurd">
                <el-input v-model="form.jurd" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="区域类型" prop="areaType">
                <el-select v-model="form.areaType" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in slaj_area_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="nodeCode">
                <el-input v-model="form.nodeCode" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职责" prop="orgGrad">
                <el-input v-model="form.orgGrad" :disabled="!editing"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">扩展信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="社会信用代码" prop="socCreCode">
                <el-input v-model="form.socCreCode" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位类型(客户端)" prop="orgClienType">
                <el-select v-model="form.orgClienType" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in slaj_org_clien_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="wiunCode">
                <el-input v-model="form.wiunCode" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="注册名称" prop="regName">
                <el-input v-model="form.regName" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="法定代表人" prop="legRep">
                <el-input v-model="form.legRep" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位性质" prop="wiunProp">
                <el-select v-model="form.wiunProp" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in slaj_wiun_prop" :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="ifWateEnte">
                <el-select v-model="form.ifWateEnte" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in slaj_if_wate_ente" :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="isLegEnti">
                <el-select v-model="form.isLegEnti" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in slaj_is_leg_enti" :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="ifMiniDire">
                <el-select v-model="form.ifMiniDire" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in slaj_if_mini_dire" :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="contrQualGrad">
                <el-select v-model="form.contrQualGrad" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in slaj_contr_qual_grad" :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="contrCertNum">
                <el-input v-model="form.contrCertNum" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="监理资质等级" prop="supQualGrad">
                <el-select v-model="form.supQualGrad" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in DPC_SUP_QUAL_GRAD" :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="stanGrad">
                <el-select v-model="form.stanGrad" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in slaj_stan_grad" :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="stanCertCode">
                <el-input v-model="form.stanCertCode" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="安全生产许可证编号" prop="safeProdLiceCode">
                <el-input v-model="form.safeProdLiceCode" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经费来源" prop="fundSour">
                <el-select v-model="form.fundSour" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in slaj_fund_sour" :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="estDate">
                <el-date-picker v-model="form.estDate" type="date" value-format="YYYY-MM-DD" :disabled="!editing"
                                style="width:100%"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="注册资本(万元)" prop="regiCapi">
                <el-input v-model="form.regiCapi" :disabled="!editing" type="number" :min="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位地址" prop="addr">
                <el-input v-model="form.addr" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="注册地址" prop="regLoc">
                <el-input v-model="form.regLoc" :disabled="!editing"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">备注</el-divider>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="note">
                <el-input v-model="form.note" :disabled="!editing" type="textarea" :rows="3"/>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <!-- 分包单位 (orgType=3) -->
        <template v-if="form.type === '3'">
          <el-divider content-position="left">基本信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="分包单位名称" prop="deptName">
                <el-input v-model="form.deptName" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="机构代码" prop="orgCode">
                <el-input v-model="form.orgCode" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="社会信用代码" prop="socCreCode">
                <el-input v-model="form.socCreCode" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="施工总承包资质" prop="contrQualGrad">
                <el-select v-model="form.contrQualGrad" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in slaj_contr_qual_grad" :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="orgType">
                <el-select v-model="form.orgType" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in UNIT_TYPE_OPTIONS" :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="orgLevel">
                <el-select v-model="form.orgLevel" :disabled="!editing" style="width:100%">
                  <el-option v-for="d in slaj_org_level" :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="status">
                <el-select v-model="form.status" :disabled="!editing" style="width:100%">
                  <el-option label="正常" value="0"/>
                  <el-option label="停用" value="1"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">人员信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目负责人" prop="legPers">
                <el-input v-model="form.legPers" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目负责人电话" prop="legPersTel">
                <el-input v-model="form.legPersTel" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="安全员" prop="safePers">
                <el-input v-model="form.safePers" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="安全生产许可证编号" prop="safeProdLiceCode">
                <el-input v-model="form.safeProdLiceCode" :disabled="!editing"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">联系方式</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="负责人" prop="leader">
                <el-input v-model="form.leader" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="form.phone" :disabled="!editing"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" :disabled="!editing"/>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>
    </el-card>
  </div>
</template>

<script setup name="OrgInfo">
import AdSelect from '@/components/AdSelect/index'
import {getDept, updateDept} from '@/api/system/dept'
import {getAttOrgExt, updateOrgWithDept} from '@/api/system/attOrgExt'
import {getAttOrgUwatBase, updateAttOrgUwatBase} from '@/api/system/attOrgUwatBase'
import {listAttOrgUwatExt, updateAttOrgUwatExt} from '@/api/system/attOrgUwatExt'
import {getAttOrgWsub, updateOrgWsubWithDept} from '@/api/system/attOrgWsub'
import useUserStore from '@/store/modules/user'
import FileUpload from '@/components/FileUpload/index.vue'
import {listMedia} from '@/api/slaj/eme'
import {Check, Edit, OfficeBuilding, Refresh} from '@element-plus/icons-vue'
import {UNIT_TYPE_OPTIONS, unitTypeToUwatExtType} from '@/utils/orgUnitType'

const {proxy} = getCurrentInstance()
const userStore = useUserStore()

// 字典
const {
  slaj_org_level, slaj_org_status, slaj_area_type,
  slaj_org_clien_type, slaj_wiun_prop, slaj_if_wate_ente,
  slaj_is_leg_enti, slaj_if_mini_dire, slaj_contr_qual_grad, DPC_SUP_QUAL_GRAD,
  slaj_stan_grad, slaj_fund_sour
} = proxy.useDict(
    'slaj_org_level', 'slaj_org_status', 'slaj_area_type',
    'slaj_org_clien_type', 'slaj_wiun_prop', 'slaj_if_wate_ente',
    'slaj_is_leg_enti', 'slaj_if_mini_dire', 'slaj_contr_qual_grad', 'DPC_SUP_QUAL_GRAD',
    'slaj_stan_grad', 'slaj_fund_sour')

const formRef = ref(null)
const editing = ref(false)
const saving = ref(false)
const loading = ref(true)
const originalForm = ref({})

// 初始表单数据
const EMPTY_FORM = {
  type: '', deptId: '', deptName: '', orgType: '', orgCode: '', leader: '', phone: '', email: '', status: '0', note: '',
  // 水利机构 — 填报字段
  socCreCode: '', adGuid: '', addr: '', jurd: '', stanGrad: '', fundSour: '',
  safetyLegPers: '', safetyLegPersTel: '', safeProdConta: '', safeProdContaTel: '',
  workPopNum: '', accReportMech: '',
  // 附件
  stanCertFiles: [], bizLicenseFiles: [], pledgeFiles: [],
  // 参建单位字段
  orgLevel: '', orgClienType: '', wiunCode: '', regName: '', legRep: '', wiunProp: '',
  estDate: '', regiCapi: '', regLoc: '', proOrgGuid: '',
  ifWateEnte: '', isLegEnti: '', ifMiniDire: '', adminWiunGuid: '',
  contrQualGrad: '', contrCertNum: '', supQualGrad: '', stanCertCode: '',
  safeProdLiceCode: '',
  ordernum: '', adCode: '', areaType: '', nodeCode: '', orgGrad: '',
  // 分包单位
  legPers: '', legPersTel: '', safePers: ''
}

const form = reactive({...EMPTY_FORM})
const rules = {
  deptName: [{required: true, message: '单位名称不能为空', trigger: 'blur'}],
  socCreCode: [{required: true, message: '社会信用代码不能为空', trigger: 'blur'}],
  adGuid: [{required: true, message: '所属行政区不能为空', trigger: 'blur'}],
  stanGrad: [{required: true, message: '标准化等级不能为空', trigger: 'change'}],
  fundSour: [{required: true, message: '经费来源不能为空', trigger: 'change'}],
  leader: [{required: true, message: '主要负责人不能为空', trigger: 'blur'}],
  phone: [{
    required: true,
    message: '主要负责人电话不能为空',
    trigger: 'blur'
  }, {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur'}],
  safetyLegPers: [{required: true, message: '分管安全负责人不能为空', trigger: 'blur'}],
  safetyLegPersTel: [{required: true, message: '分管安全负责人电话不能为空', trigger: 'blur'}],
  safeProdConta: [{required: true, message: '安全生产联系人不能为空', trigger: 'blur'}],
  safeProdContaTel: [{required: true, message: '安全生产联系人电话不能为空', trigger: 'blur'}],
  accReportMech: [{required: true, message: '事故隐患内部举报奖励机制不能为空', trigger: 'change'}]
}

/** 加载数据 */
function loadData() {
  loading.value = true
  const orgGuid = userStore.orgGuid
  if (!orgGuid) {
    loading.value = false
    proxy.$modal.msgWarning('当前用户未关联任何单位，无法显示本单位信息')
    return
  }

  // 第一步：获取 orgType（sys_dept）
  getDept(orgGuid).then(res => {
    const dept = res.data
    if (!dept) {
      loading.value = false;
      proxy.$modal.msgWarning('未找到单位信息');
      return
    }
    // 页面分区：1 水利机构 / 2 参建单位 / 3 分包单位
    // 由 sys_dept.org_type 映射（1水利机构 2分包单位 3参建单位）；旧数据 org_type 为空时按 org_check_type/type 兜底
    const orgTypeMap = {'1': '1', '3': '2', '2': '3'}
    form.type = orgTypeMap[dept.orgType]
    if (!form.type) {
      form.type = dept.orgCheckType === '1' ? '1'
          : (dept.type === '3' || dept.type === '4') ? '2'
              : dept.type || ''
    }
    if (form.type === '1') {
      // 水利机构：一个接口返回三表全部数据（后台 JOIN），前端只展示
      getAttOrgExt(orgGuid).then(r2 => {
        const data = r2.data
        if (data) {
          Object.assign(form, {...EMPTY_FORM})
          form.type = '1'
          form.deptId = data.deptId || ''
          form.deptName = data.deptName || ''
          form.orgType = data.orgType || ''
          form.leader = data.leader || ''
          form.phone = data.phone || ''
          form.email = data.email || ''
          form.status = data.status || '0'
          form.orgCode = data.orgCode || ''
          form.socCreCode = data.socCreCode || ''
          form.adGuid = data.adGuid || ''
          form.addr = data.addr || ''
          form.stanGrad = data.stanGrad || ''
          form.fundSour = data.fundSour || ''
          form.safetyLegPers = data.safetyLegPers || ''
          form.safetyLegPersTel = data.safetyLegPersTel || ''
          form.safeProdConta = data.safeProdConta || ''
          form.safeProdContaTel = data.safeProdContaTel || ''
          form.workPopNum = data.workPopNum || ''
          form.note = data.note || ''
        }
        loadAttachments(orgGuid, () => finishLoad())
      }).catch(() => {
        loadAttachments(orgGuid, () => finishLoad())
      })
    } else if (form.type === '2') {
      Promise.all([
        getAttOrgUwatBase(orgGuid),
        listAttOrgUwatExt({orgGuid, pageSize: 1})
      ]).then(([rBase, rExt]) => {
        const base = rBase.data
        form.deptId = orgGuid
        if (base) {
          form.orgCode = base.orgCode;
          form.orgLevel = base.orgLevel;
          form.orgType = base.orgType
          form.ordernum = base.ordernum;
          form.adCode = base.adCode
          form.jurd = base.jurd;
          form.areaType = base.areaType
          form.nodeCode = base.nodeCode;
          form.orgGrad = base.orgGrad
          form.status = base.status;
          form.note = base.note
        }
        const extRows = rExt.rows || []
        if (extRows.length) {
          const ext = extRows[0]
          form.socCreCode = ext.socCreCode;
          form.orgClienType = ext.orgClienType
          form.wiunCode = ext.wiunCode;
          form.regName = ext.regName
          form.legRep = ext.legRep;
          form.wiunProp = ext.wiunProp
          form.ifWateEnte = ext.ifWateEnte;
          form.isLegEnti = ext.isLegEnti
          form.ifMiniDire = ext.ifMiniDire;
          form.contrQualGrad = ext.contrQualGrad
          form.contrCertNum = ext.contrCertNum;
          form.supQualGrad = ext.supQualGrad
          form.stanGrad = ext.stanGrad;
          form.stanCertCode = ext.stanCertCode
          form.safeProdLiceCode = ext.safeProdLiceCode;
          form.fundSour = ext.fundSour
          form.estDate = ext.estDate;
          form.regiCapi = ext.regiCapi
          form.addr = ext.addr;
          form.regLoc = ext.regLoc;
          form.note = ext.note || form.note
        }
        finishLoad()
      }).catch(() => finishLoad())
    } else if (form.type === '3') {
      getAttOrgWsub(orgGuid).then(r2 => {
        const wsub = r2.data
        if (wsub) {
          form.deptId = orgGuid
          form.orgCode = wsub.orgCode || ''
          form.socCreCode = wsub.socCreCode;
          form.contrQualGrad = wsub.contrQualGrad
          form.legPers = wsub.legPers;
          form.legPersTel = wsub.legPersTel
          form.safePers = wsub.safePers;
          form.safeProdLiceCode = wsub.safeProdLiceCode
          form.orgType = wsub.orgType;
          form.orgLevel = wsub.orgLevel
          form.leader = wsub.leader || form.leader
          form.phone = wsub.phone || form.phone
          form.email = wsub.email || form.email
        }
        finishLoad()
      }).catch(() => finishLoad())
    } else {
      finishLoad()
    }
  }).catch(() => {
    loading.value = false
    proxy.$modal.msgError('加载单位信息失败，请稍后重试')
  })
}

function finishLoad() {
  originalForm.value = {...form}
  loading.value = false
}

/** 加载已上传的附件，每种附件使用独立的业务表名区分 */
function loadAttachments(orgGuid, cb) {
  const tasks = [
    {field: 'stanCertFiles', tablename: 'ATT_ORG_EXT_STAN_CERT'},
    {field: 'bizLicenseFiles', tablename: 'ATT_ORG_EXT_BIZ_LICENSE'},
    {field: 'pledgeFiles', tablename: 'ATT_ORG_EXT_PLEDGE'}
  ]
  let loaded = 0
  tasks.forEach(({field, tablename}) => {
    listMedia(tablename, orgGuid).then(res => {
      const raw = res.data || res.rows || res
      form[field] = (Array.isArray(raw) ? raw : []).map(formatMedia)
    }).catch(() => {
    }).finally(() => {
      loaded++
      if (loaded === tasks.length && cb) cb()
    })
  })
}

/** 将服务端媒体记录转为 FileUpload 组件需要的格式 */
function formatMedia(m) {
  const name = m.medName || m.medTitl || m.fileName || m.name || ''
  return {
    uid: m.guid || m.medGuid,
    name,
    guid: m.guid || m.medGuid,
    medGuid: m.guid || m.medGuid,
    medName: name,
    medTitl: name,
    medPath: m.medPath || '',
    url: m.medPath || ''
  }
}

function refresh() {
  editing.value = false;
  loadData()
}

function startEdit() {
  editing.value = true
}

function cancelEdit() {
  Object.assign(form, originalForm.value);
  editing.value = false;
  formRef.value?.resetFields()
}

function submitForm() {
  formRef.value?.validate(valid => {
    if (!valid) return
    saving.value = true

    let promise
    if (form.type === '1') {
      promise = updateOrgWithDept({
        dept: {
          deptId: form.deptId,
          deptName: form.deptName,
          leader: form.leader,
          phone: form.phone,
          email: form.email,
          status: form.status
        },
        ext: {
          guid: form.deptId,
          wiunName: form.deptName,
          orgGuid: form.deptId,
          socCreCode: form.socCreCode,
          adGuid: form.adGuid,
          addr: form.addr,
          stanGrad: form.stanGrad,
          fundSour: form.fundSour,
          safetyLegPers: form.safetyLegPers,
          safetyLegPersTel: form.safetyLegPersTel,
          safeProdConta: form.safeProdConta,
          safeProdContaTel: form.safeProdContaTel,
          workPopNum: form.workPopNum,
          note: form.note
        },
        orgCode: form.orgCode
      })
    } else if (form.type === '2') {
      promise = updateAttOrgUwatBase({
        guid: form.deptId, orgCode: form.orgCode, orgName: form.deptName, orgLevel: form.orgLevel,
        orgType: form.orgType, ordernum: form.ordernum, adCode: form.adCode, jurd: form.jurd,
        areaType: form.areaType, nodeCode: form.nodeCode, orgGrad: form.orgGrad, status: form.status, note: form.note
      }).then(() => {
        const extData = {
          guid: form.deptId,
          orgGuid: form.deptId,
          wiunName: form.deptName,
          socCreCode: form.socCreCode,
          orgClienType: form.orgClienType,
          orgType: unitTypeToUwatExtType(form.orgType),
          orgLevel: form.orgLevel,
          wiunCode: form.wiunCode,
          regName: form.regName,
          legRep: form.legRep,
          wiunProp: form.wiunProp,
          ifWateEnte: form.ifWateEnte,
          isLegEnti: form.isLegEnti,
          ifMiniDire: form.ifMiniDire,
          contrQualGrad: form.contrQualGrad,
          contrCertNum: form.contrCertNum,
          supQualGrad: form.supQualGrad,
          stanGrad: form.stanGrad,
          stanCertCode: form.stanCertCode,
          safeProdLiceCode: form.safeProdLiceCode,
          fundSour: form.fundSour,
          estDate: form.estDate,
          regiCapi: form.regiCapi,
          addr: form.addr,
          regLoc: form.regLoc,
          note: form.note
        }
        return Promise.all([
          extData.guid ? updateAttOrgUwatExt(extData) : Promise.resolve(),
          // 同步 sys_dept.type（单位类型：1水行政 2企事业单位 3施工 4监理）
          updateDept({deptId: form.deptId, type: form.orgType})
        ])
      })
    } else if (form.type === '3') {
      promise = updateOrgWsubWithDept({
        dept: {
          deptId: form.deptId,
          deptName: form.deptName,
          leader: form.leader,
          phone: form.phone,
          email: form.email,
          status: form.status
        },
        wsub: {
          guid: form.deptId,
          wiunWsubName: form.deptName,
          orgGuid: form.deptId,
          socCreCode: form.socCreCode,
          contrQualGrad: form.contrQualGrad,
          legPers: form.legPers,
          legPersTel: form.legPersTel,
          safePers: form.safePers,
          safeProdLiceCode: form.safeProdLiceCode
        },
        orgCode: form.orgCode, orgType: form.orgType, orgLevel: form.orgLevel
      })
    } else {
      promise = updateDept({
        deptId: form.deptId,
        deptName: form.deptName,
        leader: form.leader,
        phone: form.phone,
        email: form.email,
        status: form.status
      })
    }

    promise.then(() => {
      proxy.$modal.msgSuccess('保存成功')
      editing.value = false;
      saving.value = false
      loadData()
    }).catch(() => {
      saving.value = false
    })
  })
}

loadData()
</script>

<style scoped>
.upload-notice {
  color: #e6a23c;
  font-size: 13px;
  margin-top: 4px;
  line-height: 1.6;
}
</style>
