<template>
   <div ref="containerRef" class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
         <el-form-item label="机构名称" prop="deptName">
            <el-input
               v-model="queryParams.deptName"
               placeholder="请输入机构名称"
               clearable
               style="width: 200px"
               @keyup.enter="handleQuery"
            />
         </el-form-item>
         <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="机构状态" clearable style="width: 200px">
               <el-option
                  v-for="dict in sys_normal_disable"
                  :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="handleAdd"
               v-hasPermi="['system:dept:add']"
            >新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="warning"
               plain
               icon="Check"
               @click="handleSaveSort"
               v-hasPermi="['system:dept:edit']"
            >保存排序</el-button>
         </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <div class="table-wrapper">
      <el-table :height="tableHeight"
         v-if="refreshTable"
         v-loading="loading"
         ref="deptTableRef"
         :data="deptList"
         row-key="deptId"
         lazy
         :load="loadChildren"
         :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
         <el-table-column prop="deptName" label="机构名称" width="300"></el-table-column>
         <el-table-column prop="orderNum" label="排序" width="200">
            <template #default="scope">
               <el-input-number v-model="scope.row.orderNum" controls-position="right" :min="0" style="width: 88px" />
            </template>
         </el-table-column>
         <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
               <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
            </template>
         </el-table-column>
         <el-table-column label="创建时间" align="center" prop="createTime" width="200">
            <template #default="scope">
               <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:dept:edit']">修改</el-button>
               <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:dept:add']">新增</el-button>
               <el-button v-if="scope.row.parentId != 0 && scope.row.parentId != null" link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:dept:remove']">删除</el-button>
            </template>
         </el-table-column>
      </el-table>
      </div>

      <pagination
         v-show="total > 0"
         :total="total"
         v-model:page="queryParams.pageNum"
         v-model:limit="queryParams.pageSize"
         @pagination="getList"
      />

      <!-- 添加或修改机构对话框 -->
      <el-dialog :title="title" v-model="open" width="760px" append-to-body :close-on-click-modal="false">
         <el-form ref="deptRef" :model="form" :rules="rules" label-width="100px">
            <!-- 机构类型选择（新增时可选，修改时锁定） -->
            <el-row>
               <el-col :span="24">
                  <el-form-item label="机构类型" prop="orgType">
                     <el-select v-model="form.orgType" placeholder="请选择机构类型" :disabled="!!form.deptId" @change="onOrgTypeChange" style="width:100%">
                        <el-option label="水利机构" value="1"/>
                        <el-option label="参建单位" value="2"/>
                        <el-option label="分包单位" value="3"/>
                     </el-select>
                  </el-form-item>
               </el-col>
            </el-row>
            <!-- 公共字段 -->
            <el-row>
               <el-col :span="24" v-if="form.parentId !== 0">
                  <el-form-item label="上级机构" prop="parentId">
                     <el-tree-select v-model="form.parentId" :data="deptOptions" :props="{ value: 'deptId', label: 'deptName', children: 'children' }" value-key="deptId" placeholder="选择上级机构" check-strictly/>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="机构名称" prop="deptName"><el-input v-model="form.deptName" placeholder="请输入"/></el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="负责人" prop="leader"><el-input v-model="form.leader" placeholder="请输入"/></el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="联系电话" prop="phone"><el-input v-model="form.phone" placeholder="请输入"/></el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="邮箱" prop="email"><el-input v-model="form.email" placeholder="请输入"/></el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="状态">
                     <el-radio-group v-model="form.status">
                        <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
                     </el-radio-group>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="排序" prop="orderNum"><el-input-number v-model="form.orderNum" controls-position="right" :min="0"/></el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="机构代码" prop="orgCode"><el-input v-model="form.orgCode" placeholder="请输入"/></el-form-item>
               </el-col>
            </el-row>

            <!-- 水利机构专属字段 -->
            <template v-if="form.orgType === '1'">
               <el-row>
                  <el-col :span="12">
                     <el-form-item label="单位类型"><el-select v-model="form.extOrgType" placeholder="请选择" style="width:100%"><el-option v-for="d in slaj_ext_org_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="单位规格"><el-select v-model="form.extOrgLevel" placeholder="请选择" 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="单位编码"><el-input v-model="form.extWiunCode" placeholder="请输入"/></el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="注册名称"><el-input v-model="form.extRegName" placeholder="请输入"/></el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="法定代表人"><el-input v-model="form.extLegRep" placeholder="请输入"/></el-form-item>
                  </el-col>
               </el-row>
            </template>

            <!-- 参建单位专属字段 -->
            <template v-if="form.orgType === '2'">
               <el-row>
                  <el-col :span="12">
                     <el-form-item label="单位类型"><el-select v-model="form.baseOrgType" placeholder="请选择" style="width:100%"><el-option v-for="d in slaj_org_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="单位规格"><el-select v-model="form.baseOrgLevel" placeholder="请选择" 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="顺序号"><el-input v-model="form.baseOrdernum" placeholder="请输入"/></el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="行政区划"><el-input v-model="form.baseAdCode" placeholder="请输入"/></el-form-item>
                  </el-col>
               </el-row>
            </template>

            <!-- 分包单位专属字段 -->
            <template v-if="form.orgType === '3'">
               <el-row>
                  <el-col :span="12">
                     <el-form-item label="社会信用代码"><el-input v-model="form.wsubSocCreCode" placeholder="请输入"/></el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="施工总承包资质"><el-select v-model="form.wsubContrQualGrad" placeholder="请选择" 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="项目负责人"><el-input v-model="form.wsubLegPers" placeholder="请输入"/></el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="项目负责人电话"><el-input v-model="form.wsubLegPersTel" placeholder="请输入"/></el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="安全员"><el-input v-model="form.wsubSafePers" placeholder="请输入"/></el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="安全生产许可证编号"><el-input v-model="form.wsubSafeProdLiceCode" placeholder="请输入"/></el-form-item>
                  </el-col>
               </el-row>
            </template>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Dept">
import { listDept, getDept, delDept, addDept, updateDept, updateDeptSort, listDeptExcludeChild, listDeptChildren } from "@/api/system/dept"
import { addOrgWithDept } from "@/api/system/attOrgExt"
import { addOrgUwatWithExt } from "@/api/system/attOrgUwatBase"
import { addOrgWsubWithDept } from "@/api/system/attOrgWsub"
import { useTableHeight } from '@/hooks/useTableHeight'

const { tableHeight, containerRef } = useTableHeight()

const { proxy } = getCurrentInstance()
const { sys_normal_disable } = proxy.useDict("sys_normal_disable")
const { slaj_ext_org_type, slaj_org_level, slaj_contr_qual_grad, slaj_org_type } = proxy.useDict("slaj_ext_org_type","slaj_org_level","slaj_contr_qual_grad","slaj_org_type")

const deptList = ref([])
const deptTableRef = ref(null)
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref("")
const deptOptions = ref([])
const refreshTable = ref(true)
const originalOrders = ref({})
const total = ref(0)

const data = reactive({
  form: {
    // 公共字段
    deptId: undefined, parentId: undefined, deptName: undefined,
    orgType: undefined, orgCode: undefined,
    leader: undefined, phone: undefined, email: undefined,
    status: "0", orderNum: 0,
    // 水利机构扩展
    extOrgType: undefined, extOrgLevel: undefined, extWiunCode: undefined,
    extRegName: undefined, extLegRep: undefined,
    // 参建单位扩展
    baseOrgType: undefined, baseOrgLevel: undefined, baseOrdernum: undefined,
    baseAdCode: undefined,
    // 分包单位扩展
    wsubSocCreCode: undefined, wsubContrQualGrad: undefined,
    wsubLegPers: undefined, wsubLegPersTel: undefined,
    wsubSafePers: undefined, wsubSafeProdLiceCode: undefined,
  },
  queryParams: {
    deptName: undefined,
    status: undefined,
    pageNum: 1,
    pageSize: 10
  },
  rules: {
    parentId: [{ required: true, message: "上级机构不能为空", trigger: "blur" }],
    deptName: [{ required: true, message: "机构名称不能为空", trigger: "blur" }],
    orgType: [{ required: true, message: "机构类型不能为空", trigger: "change" }],
    orgCode: [{ required: true, message: "机构代码不能为空", trigger: "blur" }],
    orderNum: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
    email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
    phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
  },
})

const { queryParams, form, rules } = toRefs(data)

/** 查询机构列表（懒加载模式，支持搜索过滤，顶级分页） */
function getList() {
  loading.value = true
  listDeptChildren({ ...queryParams.value }).then(response => {
    deptList.value = response.data.rows
    recordOriginalOrders(deptList.value)
    total.value = response.data.total
    loading.value = false
  })
}

/** 懒加载子节点（不分页，加载全部直接子节点，支持搜索过滤） */
function loadChildren(row, treeNode, resolve) {
  listDeptChildren({ parentId: row.deptId, deptName: queryParams.value.deptName, status: queryParams.value.status }).then(response => {
    resolve(response.data)
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    deptId: undefined, parentId: undefined, deptName: undefined,
    orgType: undefined, orgCode: undefined,
    leader: undefined, phone: undefined, email: undefined,
    status: "0", orderNum: 0,
    extOrgType: undefined, extOrgLevel: undefined, extWiunCode: undefined,
    extRegName: undefined, extLegRep: undefined,
    baseOrgType: undefined, baseOrgLevel: undefined, baseOrdernum: undefined,
    baseAdCode: undefined,
    wsubSocCreCode: undefined, wsubContrQualGrad: undefined,
    wsubLegPers: undefined, wsubLegPersTel: undefined,
    wsubSafePers: undefined, wsubSafeProdLiceCode: undefined,
  }
  proxy.resetForm("deptRef")
}

function onOrgTypeChange() {}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.pageNum = 1
  getList()
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset()
  // 新增时加载全量机构树供选择上级
  listDept().then(response => {
    deptOptions.value = proxy.handleTree(response.data, "deptId")
  })
  if (row != undefined) {
    form.value.parentId = row.deptId
  }
  open.value = true
  title.value = "添加机构"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  listDeptExcludeChild(row.deptId).then(response => {
    deptOptions.value = proxy.handleTree(response.data, "deptId")
  })
  getDept(row.deptId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改机构"
  })
}

/** 提交按钮：按机构类型路由到不同复合 API */
function submitForm() {
  proxy.$refs["deptRef"].validate(valid => {
    if (!valid) return
    if (form.value.deptId != undefined) {
      // 修改走原有 updateDept
      updateDept(form.value).then(() => {
        proxy.$modal.msgSuccess("修改成功")
        open.value = false
        getList()
      })
      return
    }
    // 新增：按机构类型调用不同复合接口
    const dept = { parentId: form.value.parentId, deptName: form.value.deptName, leader: form.value.leader, phone: form.value.phone, email: form.value.email, status: form.value.status, orderNum: form.value.orderNum }
    const orgCode = form.value.orgCode
    const orgType = form.value.orgType
    let promise
    if (orgType === '1') {
      // 水利机构
      const ext = { wiunName: form.value.deptName, orgType: form.value.extOrgType, orgLevel: form.value.extOrgLevel, wiunCode: form.value.extWiunCode, regName: form.value.extRegName, legRep: form.value.extLegRep, proOrgGuid: form.value.parentId }
      promise = addOrgWithDept({ dept, ext, orgCode })
    } else if (orgType === '2') {
      // 参建单位
      const base = { orgName: form.value.deptName, orgCode, orgType: form.value.baseOrgType, orgLevel: form.value.baseOrgLevel, ordernum: form.value.baseOrdernum, adCode: form.value.baseAdCode, pguid: form.value.parentId, status: form.value.status }
      const ext = { wiunName: form.value.deptName, proOrgGuid: form.value.parentId }
      promise = addOrgUwatWithExt({ base, ext })
    } else if (orgType === '3') {
      // 分包单位
      const wsub = { wiunWsubName: form.value.deptName, socCreCode: form.value.wsubSocCreCode, contrQualGrad: form.value.wsubContrQualGrad, legPers: form.value.wsubLegPers, legPersTel: form.value.wsubLegPersTel, safePers: form.value.wsubSafePers, safeProdLiceCode: form.value.wsubSafeProdLiceCode }
      promise = addOrgWsubWithDept({ dept, wsub, orgCode, orgType: form.value.extOrgType, orgLevel: form.value.extOrgLevel })
    } else {
      proxy.$modal.msgWarning("请选择机构类型")
      return
    }
    promise.then(() => {
      proxy.$modal.msgSuccess("新增成功")
      open.value = false
      getList()
    })
  })
}

/** 递归记录原始排序 */
function recordOriginalOrders(list) {
  list.forEach(item => {
    originalOrders.value[item.deptId] = item.orderNum
    if (item.children && item.children.length) {
      recordOriginalOrders(item.children)
    }
  })
}

/** 保存排序 */
function handleSaveSort() {
  const changedDeptIds = []
  const changedOrderNums = []
  const collectChanged = (list) => {
    list.forEach(item => {
      if (String(originalOrders.value[item.deptId]) !== String(item.orderNum)) {
        changedDeptIds.push(item.deptId)
        changedOrderNums.push(item.orderNum)
      }
      if (item.children && item.children.length) {
        collectChanged(item.children)
      }
    })
  }
  collectChanged(deptList.value)
  if (changedDeptIds.length === 0) {
   proxy.$modal.msgWarning("未检测到排序修改")
    return
  }
  updateDeptSort({ deptIds: changedDeptIds.join(","), orderNums: changedOrderNums.join(",") }).then(() => {
   proxy.$modal.msgSuccess("排序保存成功")
    recordOriginalOrders(deptList.value)
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项?').then(function() {
    return delDept(row.deptId)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

getList()
</script>
