<template>
  <div ref="containerRef" 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 type="primary" plain @click="handleAdd" v-hasPermi="['business:orgwsub:add']"><el-icon><Plus /></el-icon> 新增</el-button>
                <el-button type="danger" plain :disabled="multiple" @click="handleDelete" v-hasPermi="['business:orgwsub:remove']"><el-icon><Delete /></el-icon> 删除</el-button>
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
              </div>
            </div>
          </template>

          <div class="search-bar" v-show="showSearch">
            <el-form :model="queryParams" ref="queryRef" :inline="true">
              <el-form-item label="分包单位名称" prop="wiunWsubName">
                <el-input v-model="queryParams.wiunWsubName" placeholder="请输入分包单位名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <OrgTreeSelect v-model="queryParams.parentId" label="上级机构" scope="uwatAll" placeholder="请选择上级机构" />

              <el-form-item>
                <el-button type="primary" @click="handleQuery"><el-icon><Search /></el-icon> 搜索</el-button>
                <el-button @click="resetQuery"><el-icon><Refresh /></el-icon> 重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table :height="tableHeight" v-loading="loading" :data="attOrgWsubList" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="分包单位名称" align="center" prop="wiunWsubName" :show-overflow-tooltip="true" />
        <el-table-column label="社会信用代码" align="center" prop="socCreCode" :show-overflow-tooltip="true" />
        <el-table-column label="施工总承包资质" align="center" prop="contrQualGrad" :show-overflow-tooltip="true">
          <template #default="scope">
            <dict-tag :options="slaj_contr_qual_grad" :value="scope.row.contrQualGrad" />
          </template>
        </el-table-column>
        <el-table-column label="项目负责人" align="center" prop="legPers" :show-overflow-tooltip="true" />
        <el-table-column label="项目负责人电话" align="center" prop="legPersTel" :show-overflow-tooltip="true" />
        <el-table-column label="安全员" align="center" prop="safePers" :show-overflow-tooltip="true" />
        <el-table-column label="安全生产许可证编号" width="150" align="center" prop="safeProdLiceCode" :show-overflow-tooltip="true" />

         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['business:orgwsub:edit']">修改</el-button>
               <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['business:orgwsub:remove']">删除</el-button>
            </template>
         </el-table-column>
      </el-table>

          <div class="pagination">
            <el-pagination
              v-show="total > 0"
              v-model:current-page="queryParams.pageNum"
              v-model:page-size="queryParams.pageSize"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="getList"
              @current-change="getList"
            />
          </div>
        </el-card>

        <el-dialog :title="title" v-model="open" width="850px" append-to-body>
         <el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
            <el-row>
              <el-col :span="24">
                <OrgSelect v-model="form.parentId" label="上级机构" placeholder="请输入机构名称搜索（不填即为顶级机构）" scope="uwat" />
              </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="orgCode">
                     <el-input v-model="form.orgCode" 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="状态" prop="status">
                     <el-select v-model="form.status" placeholder="请选择状态" style="width:100%">
                        <el-option label="正常" value="1" />
                        <el-option label="停用" value="9" />
                     </el-select>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="社会信用代码" prop="socCreCode">
                     <el-input v-model="form.socCreCode" placeholder="请输入社会信用代码" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="施工总承包资质" prop="contrQualGrad">
                     <el-select v-model="form.contrQualGrad" placeholder="请选择施工总承包资质" style="width:100%">
                        <el-option v-for="dict in slaj_contr_qual_grad" :key="dict.value" :label="dict.label" :value="dict.value" />
                     </el-select>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="项目负责人" prop="legPers">
                     <el-input v-model="form.legPers" placeholder="请输入项目负责人" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="项目负责人电话" prop="legPersTel">
                     <el-input v-model="form.legPersTel" placeholder="请输入项目负责人电话" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="安全员" prop="safePers">
                     <el-input v-model="form.safePers" placeholder="请输入安全员" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="安全生产许可证编号" prop="safeProdLiceCode">
                     <el-input v-model="form.safeProdLiceCode" placeholder="请输入安全生产许可证编号" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="单位类型" prop="orgType">
                     <el-select v-model="form.orgType" placeholder="请选择单位类型" style="width:100%">
                        <el-option v-for="dict in UNIT_TYPE_OPTIONS" :key="dict.value" :label="dict.label" :value="dict.value" />
                     </el-select>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="单位规格" prop="orgLevel">
                     <el-select v-model="form.orgLevel" placeholder="请选择单位规格" style="width:100%">
                        <el-option v-for="dict in slaj_org_level" :key="dict.value" :label="dict.label" :value="dict.value" />
                     </el-select>
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer>
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
         </template>
      </el-dialog>
  </div>
</template>

<script setup name="AttOrgWsub">
import { listAttOrgWsub, getAttOrgWsub, delOrgWsubWithDept, addOrgWsubWithDept, updateOrgWsubWithDept } from "@/api/system/attOrgWsub"
import OrgSelect from "@/components/OrgSelect"
import OrgTreeSelect from "@/components/OrgTreeSelect"
import { useTableHeight } from '@/hooks/useTableHeight'
import { Plus, Delete, Search, Refresh, OfficeBuilding } from '@element-plus/icons-vue'
import { UNIT_TYPE_OPTIONS } from '@/utils/orgUnitType'

const { tableHeight, containerRef } = useTableHeight()
const { proxy } = getCurrentInstance()

const { slaj_contr_qual_grad, slaj_org_level } = proxy.useDict("slaj_contr_qual_grad", "slaj_org_level")

const attOrgWsubList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {
    // sys_dept 字段
    deptId: undefined,
    parentId: undefined,
    parentName: undefined,
    deptName: undefined,
    leader: undefined,
    phone: undefined,
    email: undefined,
    status: "1",
    orderNum: 1,
    // att_org_uwat_base 字段
    orgCode: undefined,
    orgType: undefined,
    orgLevel: undefined,
    // att_org_wsub 字段
    wiunWsubName: undefined,
    orgGuid: undefined,
    socCreCode: undefined,
    contrQualGrad: undefined,
    legPers: undefined,
    legPersTel: undefined,
    safePers: undefined,
    safeProdLiceCode: undefined,
  },
  queryParams: {
    wiunWsubName: undefined,
    orgGuid: undefined,
    parentId: undefined,
    pageNum: 1,
    pageSize: 20
  },
  rules: {
    deptName: [{ required: true, message: "分包单位名称不能为空", trigger: "blur" }],
    orgCode: [{ required: true, message: "机构代码不能为空", trigger: "blur" }],
    orgType: [{ required: true, message: "单位类型不能为空", trigger: "blur" }]
  }
})

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

function getList() {
  loading.value = true
  listAttOrgWsub(queryParams.value).then(response => {
    attOrgWsubList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

function cancel() {
  open.value = false
  reset()
}

function reset() {
  form.value = {
    deptId: undefined,
    parentId: undefined,
    parentName: undefined,
    deptName: undefined,
    orgCode: undefined,
    leader: undefined,
    phone: undefined,
    email: undefined,
    status: "1",
    orderNum: 1,
    wiunWsubName: undefined,
    orgGuid: undefined,
    socCreCode: undefined,
    contrQualGrad: undefined,
    legPers: undefined,
    legPersTel: undefined,
    safePers: undefined,
    safeProdLiceCode: undefined,
    orgType: undefined,
    orgLevel: undefined,
  }
  proxy.resetForm("formRef")
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.orgGuid = undefined
  queryParams.value.parentId = undefined
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.guid)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

function handleAdd() {
  reset()
  open.value = true
  title.value = '添加分包单位'
}

function handleUpdate(row) {
  reset()
  // 按共享 UUID（orgGuid = deptId = base.guid）查询，不以扩展表独立 PK 查
  const orgGuid = row.orgGuid || ids.value
  getAttOrgWsub(orgGuid).then(response => {
    form.value = response.data
    open.value = true
    title.value = '修改分包单位'
  })
}

/** 从统一 form 中提取后端需要的 dept / wsub / base 三部分数据 */
function buildSubmitPayload() {
  form.value.wiunWsubName = form.value.deptName
  return {
    dept: {
      deptId: form.value.deptId,
      parentId: form.value.parentId,
      parentName: form.value.parentName,
      deptName: form.value.deptName,
      leader: form.value.leader,
      phone: form.value.phone,
      email: form.value.email,
      status: form.value.status,
      orderNum: form.value.orderNum
    },
    wsub: {
      guid: form.value.guid,
      wiunWsubName: form.value.deptName,
      orgGuid: form.value.orgGuid,
      socCreCode: form.value.socCreCode,
      contrQualGrad: form.value.contrQualGrad,
      legPers: form.value.legPers,
      legPersTel: form.value.legPersTel,
      safePers: form.value.safePers,
      safeProdLiceCode: form.value.safeProdLiceCode,
    },
    orgCode: form.value.orgCode,
    orgType: form.value.orgType,
    orgLevel: form.value.orgLevel,
  }
}

function submitForm() {
  proxy.$refs.formRef.validate(valid => {
    if (!valid) return
    // 未选上级机构即为顶级机构
    if (!form.value.parentId) {
      form.value.parentId = null
    }
    const payload = buildSubmitPayload()
    if (form.value.deptId != undefined) {
      updateOrgWsubWithDept(payload).then(() => {
        proxy.$modal.msgSuccess('修改成功')
        open.value = false
        getList()
      })
    } else {
      addOrgWsubWithDept(payload).then(res => {
        form.value.orgGuid = res.data
        proxy.$modal.msgSuccess('新增成功')
        open.value = false
        getList()
      })
    }
  })
}

function handleDelete(row) {
  const guids = row.guid || ids.value
  proxy.$modal.confirm('是否确认删除该分包单位? 将同时删除关联的机构基础信息和机构表数据。').then(function() {
    // 三表全删（同一事务），支持批量
    const ids = Array.isArray(guids) ? guids : [guids]
    return Promise.all(ids.map(g => delOrgWsubWithDept(g)))
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

getList()
</script>

