<template>
  <div ref="containerRef" class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="上报单位" prop="repOrgGuid">
        <el-input v-model="queryParams.repOrgGuid" placeholder="请输入上报单位" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="上报期间" prop="repName">
        <el-input v-model="queryParams.repName" placeholder="请输入上报期间" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="上报状态" prop="repAct">
        <el-select v-model="queryParams.repAct" placeholder="请选择上报状态" clearable style="width: 240px">
          <el-option v-for="dict in rep_stat" :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="['hidd:monrepperi:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['hidd:monrepperi:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['hidd:monrepperi:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['hidd:monrepperi:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Unlock" @click="handleUnlock" v-hasPermi="['hidd:monrepperi:edit']">一键解锁</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Bell" :disabled="multiple" @click="handleUrge" v-hasPermi="['hidd:monrepperi:edit']">督促上报</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns" storageKey="hidd-monrepperi-index"></right-toolbar>
    </el-row>

    <div class="table-wrapper">
    <el-table :height="tableHeight" v-loading="loading" :data="monRepPeriList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="上报单位" align="center" prop="repOrgGuid" v-if="columns.repOrgGuid.visible" :show-overflow-tooltip="true" />
      <el-table-column label="上报期间" align="center" prop="repName" v-if="columns.repName.visible" />
      <el-table-column label="上报状态" align="center" prop="repAct" v-if="columns.repAct.visible">
        <template #default="scope">
          <el-tag v-if="scope.row.repAct === '2'" type="success" effect="plain">已上报</el-tag>
          <el-tag v-else-if="scope.row.repAct === '1'" type="warning" effect="plain">待审批</el-tag>
          <el-tag v-else-if="scope.row.repAct === '3'" type="danger" effect="plain">已退回</el-tag>
          <el-tag v-else type="info" effect="plain">未上报</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上报时间" align="center" prop="repTime" v-if="columns.repTime.visible" width="180" />
      <el-table-column label="退回说明" align="center" prop="returnDesc" v-if="columns.returnDesc.visible" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['hidd:monrepperi:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="详情" placement="top">
            <el-button link type="primary" icon="View" @click="handleDetail(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="下级月报" placement="top">
            <el-button link type="primary" icon="Document" @click="handleSubMonth(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="撤回审批" placement="top" v-if="scope.row.repAct === '2'">
            <el-button link type="warning" icon="Stamp" @click="handleVerify(scope.row)" v-hasPermi="['hidd:monrepperi:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['hidd:monrepperi:remove']"></el-button>
          </el-tooltip>
        </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="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="monRepPeriRef" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上报单位" prop="repOrgGuid">
              <el-input v-model="form.repOrgGuid" placeholder="请输入上报单位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上报期间" prop="repName">
              <el-select v-model="form.repName" placeholder="请选择上报期间" filterable allow-create>
                <el-option v-for="m in 12" :key="m" :label="currentYear + '年' + m + '月'" :value="currentYear + '-' + String(m).padStart(2, '0')" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上报状态" prop="repAct">
              <el-select v-model="form.repAct" placeholder="请选择上报状态">
                <el-option v-for="dict in rep_stat" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker v-model="form.startDate" type="date" placeholder="选择开始日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker v-model="form.endDate" type="date" placeholder="选择结束日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="退回说明" prop="returnDesc">
              <el-input v-model="form.returnDesc" type="textarea" placeholder="请输入退回说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </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>

    <!-- 撤回审批对话框 -->
    <el-dialog title="撤回审批" v-model="verifyOpen" width="600px" append-to-body>
      <el-form :model="verifyForm" :rules="verifyRules" ref="verifyRef" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上报单位">
              <el-input v-model="verifyForm.repOrgGuid" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上报期间">
              <el-input v-model="verifyForm.repName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="审批结果" prop="verifyResult">
              <el-radio-group v-model="verifyForm.verifyResult">
                <el-radio label="1">通过</el-radio>
                <el-radio label="0">驳回</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="审批意见" prop="verifyOpinion">
              <el-input v-model="verifyForm.verifyOpinion" type="textarea" placeholder="请输入审批意见" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitVerify">确 定</el-button>
          <el-button @click="verifyOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 下级月报详情对话框 -->
    <el-dialog title="下级月报详情" v-model="subMonthOpen" width="800px" append-to-body>
      <el-table v-loading="subMonthLoading" :data="subMonthList">
        <el-table-column label="上报单位" align="center" prop="repOrgGuid" :show-overflow-tooltip="true" />
        <el-table-column label="上报期间" align="center" prop="repName" />
        <el-table-column label="上报状态" align="center" prop="repAct">
          <template #default="scope">
            <dict-tag :options="rep_stat" :value="scope.row.repAct" />
          </template>
        </el-table-column>
        <el-table-column label="上报时间" align="center" prop="repTime" width="180" />
        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" icon="View" @click="handleSubMonthDetail(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="BisOrgMonRepPeri">
import { listBisOrgMonRepPeri, getBisOrgMonRepPeri, delBisOrgMonRepPeri, addBisOrgMonRepPeri, updateBisOrgMonRepPeri, batchUnlock, urgeReport } from "@/api/slaj/hidd"
import { useTableHeight } from '@/hooks/useTableHeight'

const { tableHeight, containerRef } = useTableHeight()

const { proxy } = getCurrentInstance()
const { rep_stat } = proxy.useDict("rep_stat")

const currentYear = new Date().getFullYear()

const monRepPeriList = 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 verifyOpen = ref(false)
const verifyForm = ref({})
const verifyRules = {
  verifyResult: [{ required: true, message: "审批结果不能为空", trigger: "change" }]
}

// 下级月报
const subMonthOpen = ref(false)
const subMonthLoading = ref(false)
const subMonthList = ref([])

const columns = ref({
  repOrgGuid: { label: '上报单位', visible: true },
  repName: { label: '上报期间', visible: true },
  repAct: { label: '上报状态', visible: true },
  repTime: { label: '上报时间', visible: true },
  returnDesc: { label: '退回说明', visible: true }
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    repOrgGuid: undefined,
    repName: undefined,
    repAct: undefined
  },
  rules: {
    repOrgGuid: [{ required: true, message: "上报单位不能为空", trigger: "blur" }],
    repName: [{ required: true, message: "上报期间不能为空", trigger: "blur" }]
  }
})

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

/** 查询月报期间列表 */
function getList() {
  loading.value = true
  listBisOrgMonRepPeri(queryParams.value).then(res => {
    loading.value = false
    monRepPeriList.value = res.rows
    total.value = res.total
  })
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  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()
  const guid = row.guid || ids.value
  getBisOrgMonRepPeri(guid).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改月报期间"
  })
}

/** 详情按钮操作 */
function handleDetail(row) {
  const guid = row.guid || ids.value
  proxy.$router.push({ path: '/slaj/hidd/monthDetail', query: { guid: guid } })
}

/** 下级月报按钮 */
function handleSubMonth(row) {
  subMonthLoading.value = true
  subMonthOpen.value = true
  // 查询下级单位的月报
  listBisOrgMonRepPeri({ parentGuid: row.guid }).then(res => {
    subMonthLoading.value = false
    subMonthList.value = res.rows
  })
}

/** 下级月报详情 */
function handleSubMonthDetail(row) {
  proxy.$router.push({ path: '/slaj/hidd/subMonthDetail', query: { guid: row.guid } })
}

/** 撤回审批按钮 */
function handleVerify(row) {
  verifyForm.value = {
    guid: row.guid,
    repOrgGuid: row.repOrgGuid,
    repName: row.repName,
    verifyResult: undefined,
    verifyOpinion: undefined
  }
  verifyOpen.value = true
}

/** 提交撤回审批 */
function submitVerify() {
  proxy.$refs["verifyRef"].validate(valid => {
    if (valid) {
      const data = {
        guid: verifyForm.value.guid,
        repAct: verifyForm.value.verifyResult === '1' ? '1' : '3',
        returnDesc: verifyForm.value.verifyOpinion
      }
      updateBisOrgMonRepPeri(data).then(response => {
        proxy.$modal.msgSuccess("审批成功")
        verifyOpen.value = false
        getList()
      })
    }
  })
}

/** 一键解锁按钮 */
function handleUnlock() {
  if (ids.value.length === 0) {
    proxy.$modal.msgError("请先选择要解锁的月报")
    return
  }
  proxy.$modal.confirm('是否确认对选中的' + ids.value.length + '个月报进行解锁操作？').then(function () {
    return batchUnlock(ids.value)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("解锁成功")
  }).catch(() => {})
}

/** 督促上报按钮 */
function handleUrge() {
  if (ids.value.length === 0) {
    proxy.$modal.msgError("请先选择要督促的月报")
    return
  }
  const selection = monRepPeriList.value.filter(item => ids.value.includes(item.guid))
  const notReported = selection.filter(item => item.repAct === '0')
  if (notReported.length === 0) {
    proxy.$modal.msgError("选中的单位均已上报，无需督促")
    return
  }
  const orgGuids = notReported.map(item => item.repOrgGuid).join(',')
  const repName = notReported[0]?.repName || ''
  proxy.$modal.confirm('是否确认对' + notReported.length + '个未上报单位进行督促？').then(function () {
    return urgeReport(orgGuids, repName)
  }).then(() => {
    proxy.$modal.msgSuccess("督促通知已发送")
  }).catch(() => {})
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["monRepPeriRef"].validate(valid => {
    if (valid) {
      if (form.value.guid != undefined) {
        updateBisOrgMonRepPeri(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addBisOrgMonRepPeri(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const guids = row.guid || ids.value
  proxy.$modal.confirm('是否确认删除月报期间编号为"' + guids + '"的数据项？').then(function () {
    return delBisOrgMonRepPeri(guids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("hidd/monrepperi/export", {
    ...queryParams.value
  }, `monRepPeri_${new Date().getTime()}.xlsx`)
}

/** 重置表单 */
function reset() {
  form.value = {
    guid: undefined,
    repOrgGuid: undefined,
    repName: undefined,
    repAct: undefined,
    repTime: undefined,
    returnDesc: undefined,
    startDate: undefined,
    endDate: undefined
  }
  proxy.resetForm("monRepPeriRef")
}

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