<template>
  <el-card shadow="never">
    <template #header>
      <div class="header">{{ title }}</div>
    </template>

    <el-form label-width="100px" style="max-width: 760px">
      <el-form-item label="标题" required>
        <el-input v-model="form.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="form.summaryType" style="width: 160px">
          <el-option label="日报" value="1" />
          <el-option label="周报" value="2" />
          <el-option label="月报" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间区间">
        <el-date-picker
          v-model="range"
          type="daterange"
          value-format="YYYY-MM-DD"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 260px"
        />
      </el-form-item>
      <el-form-item label="内容">
        <el-input v-model="form.content" type="textarea" :rows="6" placeholder="请输入简报内容" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="submitting" @click="submit">保存</el-button>
        <el-button @click="load">重载</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import { summaryAdd, summaryEdit, summaryGet } from '@/api/otr/summary/core'

const props = defineProps<{ title: string; isShare?: boolean }>()
const route = useRoute()
const submitting = ref(false)
const range = ref<string[]>([])
const form = reactive<Record<string, any>>({
  id: '',
  title: '',
  summaryType: '2',
  content: '',
})

async function load() {
  const id = String(route.query.id || '')
  if (!id) return
  const res: any = await summaryGet(id)
  const rt = res?.result || {}
  form.id = rt.id || id
  form.title = rt.title || ''
  form.summaryType = String(rt.summaryType || '2')
  form.content = rt.content || ''
  range.value = [rt.beginDate || '', rt.endDate || ''].filter(Boolean)
}

async function submit() {
  if (!form.title) {
    ElMessage.warning('请填写标题')
    return
  }
  submitting.value = true
  try {
    const payload = {
      ...form,
      beginDate: range.value?.[0] || '',
      endDate: range.value?.[1] || '',
      shareMode: props.isShare ? 1 : 0,
    }
    if (form.id) await summaryEdit(payload)
    else await summaryAdd(payload)
    ElMessage.success('保存成功')
  } finally {
    submitting.value = false
  }
}

onMounted(load)
</script>

<style scoped>
.header {
  font-weight: 600;
}
</style>
