<template>
  <div class="app-container">
    <el-form ref="queryRef" :model="queryParams" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="申请人" prop="applicantName">
        <el-input v-model="queryParams.applicantName" placeholder="请输入申请人" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="报销状态" prop="reimburseStatus">
        <el-select v-model="queryParams.reimburseStatus" placeholder="请选择状态" clearable style="width: 180px">
          <el-option label="未报销" value="0" />
          <el-option label="已报销" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button size="small" icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button size="small" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button size="small" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button size="small" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button size="small" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="reimbursementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请人" align="center" prop="applicantName" width="120" />
      <el-table-column label="附件" align="left" min-width="260">
        <template #default="scope">
          <div v-if="scope.row._attachmentFiles?.length" class="attachment-list">
            <el-link
              v-for="file in scope.row._attachmentFiles"
              :key="file.ossId"
              :href="file.url"
              target="_blank"
              type="primary"
              :underline="false"
              class="attachment-link"
            >
              {{ file.originalName || file.fileName || `附件-${file.ossId}` }}
            </el-link>
          </div>
          <span v-else class="text-muted">无附件</span>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
        <template #default="scope">
          <span>{{ proxy.parseTime(scope.row.uploadTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center" prop="amount" width="120" />
      <el-table-column label="状态" align="center" width="180">
        <template #default="scope">
          <el-switch
            :model-value="scope.row.reimburseStatus === '1'"
            active-text="已报销"
            inactive-text="未报销"
            inline-prompt
            @change="(val) => handleQuickStatusChange(scope.row, val)"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <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="680px" append-to-body>
      <el-form ref="reimbursementRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="附件" prop="attachmentUrl">
          <div class="upload-wrap">
            <file-upload v-model="form.attachmentUrl" :limit="3" />
          </div>
        </el-form-item>
        <el-form-item label="上传时间" prop="uploadTime">
          <el-date-picker
            clearable
            v-model="form.uploadTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择上传时间"
          />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Reimbursement">
import { listReimbursement, getReimbursement, delReimbursement, addReimbursement, updateReimbursement } from '@/api/oa/reimbursement'
import { listByIds } from '@/api/system/oss'

const { proxy } = getCurrentInstance()

const reimbursementList = ref([])
const open = ref(false)
const buttonLoading = 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: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    applicantName: undefined,
    reimburseStatus: undefined
  },
  rules: {
    uploadTime: [{ required: true, message: '上传时间不能为空', trigger: 'change' }],
    amount: [{ required: true, message: '金额不能为空', trigger: 'blur' }]
  }
})

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

async function hydrateAttachmentFiles(list) {
  const idSet = new Set()
  list.forEach(row => {
    const ids = (row.attachmentUrl || '').split(',').map(i => i.trim()).filter(Boolean)
    ids.forEach(id => idSet.add(id))
  })
  if (!idSet.size) {
    reimbursementList.value = list.map(row => ({ ...row, _attachmentFiles: [] }))
    return
  }
  const idStr = Array.from(idSet).join(',')
  const res = await listByIds(idStr)
  const files = res?.data || []
  const fileMap = new Map(files.map(f => [String(f.ossId), f]))
  reimbursementList.value = list.map(row => {
    const ids = (row.attachmentUrl || '').split(',').map(i => i.trim()).filter(Boolean)
    const attachmentFiles = ids.map(id => fileMap.get(id)).filter(Boolean)
    return { ...row, _attachmentFiles: attachmentFiles }
  })
}

function getList() {
  loading.value = true
  listReimbursement(queryParams.value).then(async response => {
    total.value = response.total
    await hydrateAttachmentFiles(response.rows || [])
  }).finally(() => {
    loading.value = false
  })
}

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

function reset() {
  form.value = {
    reimbursementId: null,
    attachmentUrl: null,
    uploadTime: proxy.parseTime(new Date(), '{y}-{m}-{d}'),
    amount: null,
    remark: null
  }
  proxy.resetForm('reimbursementRef')
}

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

function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

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

function handleAdd() {
  reset()
  open.value = true
  title.value = '添加报销'
}

function handleUpdate(row) {
  loading.value = true
  reset()
  const _reimbursementId = row.reimbursementId || ids.value
  getReimbursement(_reimbursementId).then(response => {
    form.value = response.data
    open.value = true
    title.value = '修改报销'
  }).finally(() => {
    loading.value = false
  })
}

function submitForm() {
  proxy.$refs.reimbursementRef.validate(valid => {
    if (!valid) {
      return
    }
    buttonLoading.value = true
    const req = form.value.reimbursementId != null ? updateReimbursement(form.value) : addReimbursement(form.value)
    req.then(() => {
      proxy.$modal.msgSuccess(form.value.reimbursementId != null ? '修改成功' : '新增成功')
      open.value = false
      getList()
    }).finally(() => {
      buttonLoading.value = false
    })
  })
}

function handleQuickStatusChange(row, val) {
  const oldStatus = row.reimburseStatus
  const targetStatus = val ? '1' : '0'
  const statusText = targetStatus === '1' ? '已报销' : '未报销'

  proxy.$modal.confirm(`确认将状态改为${statusText}吗？`).then(() => {
    const payload = {
      ...row,
      reimburseStatus: targetStatus
    }
    return updateReimbursement(payload)
  }).then(() => {
    row.reimburseStatus = targetStatus
    proxy.$modal.msgSuccess('状态更新成功')
  }).catch(() => {
    row.reimburseStatus = oldStatus
  })
}

function handleDelete(row) {
  const _reimbursementIds = row.reimbursementId || ids.value
  proxy.$modal.confirm('是否确认删除报销编号为"' + _reimbursementIds + '"的数据项？').then(function () {
    loading.value = true
    return delReimbursement(_reimbursementIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).finally(() => {
    loading.value = false
  })
}

function handleExport() {
  proxy.download('oa/reimbursement/export', {
    ...queryParams.value
  }, `reimbursement_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
.upload-wrap {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.upload-tip {
  margin-top: 2px;
}

.attachment-list {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
}

.attachment-link {
  max-width: 240px;
}

.text-muted {
  color: #909399;
}
</style>
