<template>
  <div class="app-container month-detail">
    <div class="tree-panel">
      <div class="tree-header">
        <span>下属单位</span>
        <el-radio-group v-model="lockStatus" size="small" @change="handleLockChange" v-if="userStore.roles?.includes('1')">
          <el-radio-button value="0">解锁</el-radio-button>
          <el-radio-button value="1">加锁</el-radio-button>
        </el-radio-group>
      </div>
      <el-tree
        ref="deptTreeRef"
        :data="deptTreeData"
        :props="{ children: 'children', label: 'label' }"
        node-key="id"
        :highlight-current="true"
        :expand-on-click-node="false"
        @node-click="handleDeptNodeClick"
        default-expand-all
      />
    </div>
    <div class="main-area">
      <el-card shadow="never" class="info-card">
        <div class="info-header">
          <div class="info-left">
            <span class="info-title">{{ selectedYear }}年隐患月报</span>
          </div>
          <div class="info-right">
            <span>上报单位：{{ form.repOrgName || route.query.orgName || '--' }}</span>
            <span class="info-divider">|</span>
            <span>月报开始日期：{{ form.startDate || '--' }}</span>
            <span class="info-divider">|</span>
            <span>月报结束日期：{{ form.endDate || '--' }}</span>
            <span class="info-divider">|</span>
            <span>月报状态：
              <span v-if="form.repAct === '1'" style="color:#579575;">已上报</span>
              <span v-else-if="form.repAct === '2'" style="color:#D8B83F;">未上报</span>
              <span v-else>--</span>
            </span>
          </div>
          <div class="info-buttons">
            <el-button type="success" plain size="small" @click="handleExport">导出</el-button>
          </div>
        </div>
      </el-card>

      <el-card shadow="never" class="table-card">
        <el-table
          v-loading="hiddLoading"
          :data="hiddList"
          @selection-change="handleSelectionChange"
          border
          stripe
          height="calc(100vh - 360px)"
          ref="hiddTableRef"
        >
          <el-table-column v-if="isAddMode" type="selection" width="45" align="center" />
          <el-table-column label="序号" type="index" width="60" align="center" />
          <el-table-column label="所属单位" align="center" prop="orgName" min-width="120" :show-overflow-tooltip="true" />
          <el-table-column label="隐患名称" align="center" prop="hiddName" min-width="160" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-link type="primary" @click="handleHiddNameClick(scope.row)">{{ scope.row.hiddName }}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="隐患类别" align="center" min-width="100">
            <template #default="scope">
              {{ scope.row.hiddGrad === '2' ? '重大隐患' : '一般隐患' }}
            </template>
          </el-table-column>
          <el-table-column label="所属工程" align="center" prop="engName" min-width="120" :show-overflow-tooltip="true" />
          <el-table-column label="排查日期" align="center" width="100">
            <template #default="scope">
              {{ scope.row.inspDate ? scope.row.inspDate.substring(0, 10) : '--' }}
            </template>
          </el-table-column>
          <el-table-column label="要求整改完成日期" align="center" width="130">
            <template #default="scope">
              {{ scope.row.requCompDate ? scope.row.requCompDate.substring(0, 10) : '--' }}
            </template>
          </el-table-column>
          <el-table-column label="实际整改完成日期" align="center" width="130">
            <template #default="scope">
              {{ scope.row.factCompDate ? scope.row.factCompDate.substring(0, 10) : '--' }}
            </template>
          </el-table-column>
          <el-table-column label="整改状态" align="center" width="100">
            <template #default="scope">
              <el-link type="primary" @click="handleRectClick(scope.row)">
                {{ scope.row.hiddStat === '0' ? '未落实整改' : scope.row.hiddStat === '1' ? '正在整改' : scope.row.hiddStat === '2' ? '完成整改' : '--' }}
              </el-link>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="hiddTotal > 0" :total="hiddTotal" v-model:page="hiddQueryParams.pageNum" v-model:limit="hiddQueryParams.pageSize" @pagination="loadHiddList" />
      </el-card>

      <el-card v-if="isAddMode" shadow="never" class="upload-card">
        <template #header>
          <span>上传附件</span>
        </template>
        <el-upload
          ref="uploadRef"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :multiple="true"
          :limit="5"
          :on-success="handleUploadSuccess"
          :on-remove="handleUploadRemove"
          :file-list="uploadFileList"
          accept=".doc,.docx,.xls,.xlsx,.txt,.pdf,.zip,.rar"
          list-type="text"
        >
          <el-button type="primary">选择文件</el-button>
        </el-upload>
      </el-card>

      <el-card v-if="!isAddMode" shadow="never" class="upload-card">
        <template #header>
          <span>相关资料</span>
        </template>
        <el-table v-loading="fileLoading" :data="fileList" size="small">
          <el-table-column label="序号" type="index" width="60" align="center" />
          <el-table-column label="文件名" align="center" prop="medName" :show-overflow-tooltip="true" />
          <el-table-column label="操作" align="center" width="150">
            <template #default="scope">
              <el-button link type="primary" @click="handleDownload(scope.row)">下载</el-button>
              <el-button link type="danger" @click="handleDeleteFile(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <div v-if="isAddMode" class="bottom-bar">
        <el-button type="success" size="small" @click="handleExport">导出</el-button>
        <el-button type="primary" size="small" @click="handleReport">上报</el-button>
        <el-button size="small" @click="goBack">取消</el-button>
      </div>
    </div>

    <el-dialog title="隐患信息" v-model="hiddDetailOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border v-if="hiddDetailRow">
        <el-descriptions-item label="隐患名称" :span="2">{{ hiddDetailRow.hiddName }}</el-descriptions-item>
        <el-descriptions-item label="隐患等级">
          {{ hiddDetailRow.hiddGrad === '2' ? '重大隐患' : '一般隐患' }}
        </el-descriptions-item>
        <el-descriptions-item label="隐患类别">{{ hiddDetailRow.hiddType }}</el-descriptions-item>
        <el-descriptions-item label="所属工程">{{ hiddDetailRow.engName }}</el-descriptions-item>
        <el-descriptions-item label="排查人">{{ hiddDetailRow.invePers }}</el-descriptions-item>
        <el-descriptions-item label="排查日期">{{ hiddDetailRow.findDate }}</el-descriptions-item>
        <el-descriptions-item label="隐患部位">{{ hiddDetailRow.proPart }}</el-descriptions-item>
        <el-descriptions-item label="隐患描述" :span="2">{{ hiddDetailRow.hiddDesc }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="hiddDetailOpen = false">关 闭</el-button>
      </template>
    </el-dialog>

    <el-dialog title="隐患核实" v-model="hiddVerifyOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border v-if="hiddVerifyRow">
        <el-descriptions-item label="隐患名称" :span="2">{{ hiddVerifyRow.hiddName }}</el-descriptions-item>
        <el-descriptions-item label="核实日期">{{ hiddVerifyRow.verifyDate }}</el-descriptions-item>
        <el-descriptions-item label="核实人">{{ hiddVerifyRow.verifyPers }}</el-descriptions-item>
        <el-descriptions-item label="核实结果">{{ hiddVerifyRow.verifyResult }}</el-descriptions-item>
        <el-descriptions-item label="核实说明" :span="2">{{ hiddVerifyRow.verifyDesc }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="hiddVerifyOpen = false">关 闭</el-button>
      </template>
    </el-dialog>

    <el-dialog title="隐患整改落实信息" v-model="rectImplOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border v-if="rectImplRow">
        <el-descriptions-item label="隐患名称" :span="2">{{ rectImplRow.hiddName }}</el-descriptions-item>
        <el-descriptions-item label="整改状态">
          {{ rectImplRow.hiddStat === '0' ? '未落实整改' : rectImplRow.hiddStat === '1' ? '正在整改' : rectImplRow.hiddStat === '2' ? '完成整改' : '--' }}
        </el-descriptions-item>
        <el-descriptions-item label="整改负责人">{{ rectImplRow.rectPers }}</el-descriptions-item>
        <el-descriptions-item label="要求整改完成日期">{{ rectImplRow.requCompDate }}</el-descriptions-item>
        <el-descriptions-item label="实际整改完成日期">{{ rectImplRow.factCompDate }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="rectImplOpen = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MonthDetail">
import { getBisOrgMonRepPeri, listBisHiddRecRepWithHidd, listAttMedBase, delAttMedBase, batchUnlock, submitMonth, listObjHidd, addAttMedBase, addBisOrgMonRepPeri, getMonthListStats } from "@/api/slaj/hidd"
import { listAttOrgBase } from "@/api/slaj/hidd"
import { getToken } from "@/utils/auth"
import useUserStore from '@/store/modules/user'

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

const isAddMode = computed(() => !route.query.guid)

const form = ref({})
const hiddList = ref([])
const fileList = ref([])
const hiddLoading = ref(false)
const fileLoading = ref(false)
const hiddTotal = ref(0)
const hiddQueryParams = ref({ pageNum: 1, pageSize: 20 })
const selectedHiddGuids = ref([])
const hiddTableRef = ref(null)
const uploadFileList = ref([])

const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/common/upload'
const uploadHeaders = { Authorization: 'Bearer ' + getToken() }
const uploadRef = ref(null)

const selectedYear = ref(new Date().getFullYear())
const selectedMonth = ref('')

const deptTreeRef = ref(null)
const deptTreeData = ref([])
const lockStatus = ref('0')

const selectedDeptId = ref(null)

const hiddDetailOpen = ref(false)
const hiddDetailRow = ref(null)
const hiddVerifyOpen = ref(false)
const hiddVerifyRow = ref(null)
const rectImplOpen = ref(false)
const rectImplRow = ref(null)

function loadDeptTree() {
  listAttOrgBase({}).then(res => {
    const data = res.data || []
    deptTreeData.value = buildTreeData(data, null)
  })
}

function buildTreeData(list, parentId) {
  const tree = []
  list.forEach(item => {
    if (item.pguid === parentId) {
      const node = {
        id: item.guid,
        label: item.orgName,
        children: buildTreeData(list, item.guid)
      }
      if (node.children.length === 0) delete node.children
      tree.push(node)
    }
  })
  return tree
}

function handleDeptNodeClick(data) {
  selectedDeptId.value = data.id
  loadHiddListByDept(data.id)
}

function loadHiddListByDept(deptId) {
  hiddLoading.value = true
  hiddList.value = []
  
  if (form.value.guid) {
    listBisHiddRecRepWithHidd(form.value.guid).then(repRes => {
      const allData = repRes.data || []
      // 如果选择了部门，过滤该部门的数据
      let filteredData = allData
      if (deptId) {
        filteredData = allData.filter(item => item.orgGuid === deptId || item.orgId === deptId)
      }
      
      hiddTotal.value = filteredData.length
      
      // 分页处理
      const start = (hiddQueryParams.value.pageNum - 1) * hiddQueryParams.value.pageSize
      const end = start + hiddQueryParams.value.pageSize
      hiddList.value = filteredData.slice(start, end)
      
      hiddLoading.value = false
    }).catch(() => {
      hiddLoading.value = false
    })
  } else {
    hiddLoading.value = false
  }
}

function handleLockChange(val) {
  const selectedNodes = deptTreeRef.value?.getCheckedKeys() || []
  if (selectedNodes.length === 0) {
    proxy.$modal.msgWarning('请先选择需要操作的单位')
    lockStatus.value = val === '0' ? '1' : '0'
    return
  }
  
  const msg = val === '0' ? '解锁' : '加锁'
  proxy.$modal.confirm(`是否确认对选中的${selectedNodes.length}个单位进行${msg}操作？`).then(() => {
    batchUnlock(selectedNodes).then(() => {
      proxy.$modal.msgSuccess(`${msg}成功`)
      loadDeptTree()
    }).catch(() => {
      lockStatus.value = val === '0' ? '1' : '0'
    })
  }).catch(() => {
    lockStatus.value = val === '0' ? '1' : '0'
  })
}

function getInfo() {
  const guid = route.query.guid
  if (guid) {
    getBisOrgMonRepPeri(guid).then(response => {
      form.value = response.data
      loadHiddList()
      loadFileList()
    })
  } else {
    // 新增模式：自动创建月报期间
    const month = route.query.month
    const year = route.query.year
    if (month) {
      initNewPeriod(month, year)
    }
    loadHiddList()
  }
}

function initNewPeriod(month, year) {
  const repTime = month
  const parts = month.split('-')
  const startDate = year + '-' + parts[1] + '-07'
  let endYear = parseInt(parts[0])
  let endMonth = parseInt(parts[1])
  if (endMonth === 12) {
    endYear = endYear + 1
    endMonth = 1
  } else {
    endMonth = endMonth + 1
  }
  const endDate = endYear + '-' + String(endMonth).padStart(2, '0') + '-06'
  
  // 检查是否已存在
  getMonthListStats({ repTime: repTime, unitType: '0' }).then(res => {
    const data = res.data || res.rows || []
    const existing = data.find(d => d.repTime === repTime)
    if (existing) {
      if (existing.repAct === '1') {
        proxy.$modal.msgWarning('本月数据已上报，不允许重复上报')
      } else {
        form.value = { guid: existing.guid, repTime: repTime, startDate: startDate, endDate: endDate, repAct: existing.repAct }
      }
    } else {
      // 创建新的月报期间
      addBisOrgMonRepPeri({
        repName: repTime + '隐患期间表',
        repAct: '2',
        repType: '0',
        repTime: repTime,
        startDate: startDate,
        endDate: endDate,
        lockStatus: '1'
      }).then(addRes => {
        if (addRes.data && addRes.data.guid) {
          form.value = { guid: addRes.data.guid, repTime: repTime, startDate: startDate, endDate: endDate, repAct: '2' }
        }
      }).catch(() => {})
    }
  }).catch(() => {})
}

function loadHiddList() {
  hiddLoading.value = true
  hiddList.value = []

  if (isAddMode.value) {
    // 新增模式：加载所有隐患
    listObjHidd({}).then(res => {
      const allData = res.rows || res.data || []
      hiddTotal.value = allData.length
      const start = (hiddQueryParams.value.pageNum - 1) * hiddQueryParams.value.pageSize
      const end = start + hiddQueryParams.value.pageSize
      hiddList.value = allData.slice(start, end)
      hiddLoading.value = false
    }).catch(() => {
      hiddLoading.value = false
    })
  } else if (form.value.guid) {
    listBisHiddRecRepWithHidd(form.value.guid).then(repRes => {
      const allData = repRes.data || []
      hiddTotal.value = allData.length
      const start = (hiddQueryParams.value.pageNum - 1) * hiddQueryParams.value.pageSize
      const end = start + hiddQueryParams.value.pageSize
      hiddList.value = allData.slice(start, end)
      hiddLoading.value = false
    }).catch(() => {
      hiddLoading.value = false
    })
  } else {
    hiddLoading.value = false
  }
}

function handleSelectionChange(selection) {
  selectedHiddGuids.value = selection.map(r => r.guid)
}

function handleReport() {
  if (selectedHiddGuids.value.length === 0) {
    // 零报告：无隐患时也能上报
    proxy.$modal.confirm('当前没有选择隐患记录，确定进行零报告上报吗？').then(() => {
      doSubmitMonth([])
    }).catch(() => {})
    return
  }
  doSubmitMonth(selectedHiddGuids.value)
}

function doSubmitMonth(guids) {
  if (!form.value.guid) {
    proxy.$modal.msgWarning('请稍候，月报期间正在创建中...')
    return
  }
  submitMonth(form.value.guid, guids).then(() => {
    proxy.$modal.msgSuccess('上报成功')
    goBack()
  }).catch(() => {})
}

function handleUploadSuccess(response, file) {
  if (response.code === 200) {
    addAttMedBase({ medName: file.name, medPath: response.fileName, bizGuid: form.value.guid }).then(() => {
      proxy.$modal.msgSuccess('上传成功')
    })
  }
}

function handleUploadRemove(file) {
  if (file.guid) {
    delAttMedBase(file.guid)
  }
}

function loadFileList() {
  fileLoading.value = true
  listAttMedBase({ bizGuid: form.value.guid }).then(res => {
    fileList.value = res.rows || []
    fileLoading.value = false
  }).catch(() => {
    fileLoading.value = false
  })
}

function handleHiddNameClick(row) {
  hiddDetailRow.value = row
  hiddDetailOpen.value = true
}

function handleRectClick(row) {
  rectImplRow.value = row
  rectImplOpen.value = true
}

function handleVerifyClick(row) {
  hiddVerifyRow.value = row
  hiddVerifyOpen.value = true
}

function handleExport() {
  const repYear = selectedYear.value
  const repMonth = form.value.repName || route.query.month || ''
  const id = form.value.guid || route.query.guid || ''
  window.location.href = `/hidd/hiddStat/export?repYear=${repYear}&repMonth=${encodeURIComponent(repMonth)}&id=${id}&requestType=1`
}

function handleDownload(row) {
  proxy.download('common/download', { fileName: row.medPath }, row.medName)
}

function handleDeleteFile(row) {
  proxy.$modal.confirm('是否确认删除附件"' + row.medName + '"？').then(() => {
    return delAttMedBase(row.guid)
  }).then(() => {
    loadFileList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => {})
}

function goBack() {
  proxy.$router.push({ path: '/slaj/hidd/month' })
}

onMounted(() => {
  loadDeptTree()
  getInfo()
})
</script>

<style scoped>
.month-detail {
  display: flex;
  gap: 10px;
}
.tree-panel {
  width: 200px;
  min-width: 200px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fff;
}
.tree-header {
  padding: 8px 12px;
  font-size: 13px;
  font-weight: bold;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.main-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.info-card {
  flex-shrink: 0;
}
.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
}
.info-left {
  font-weight: bold;
  font-size: 18px;
}
.info-buttons {
  flex-shrink: 0;
}
.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.upload-card {
  flex-shrink: 0;
}
</style>
