<template>
  <div class="task-form-page frame-body adaption-frame-body">
    <div class="task-form-card">
      <div class="task-form-header">
        <div>
          <div class="task-form-title">新建任务</div>
          <div class="task-form-subtitle">补齐执行人、参与人、时间、优先级、附件和任务说明。</div>
        </div>
        <div class="task-form-actions">
          <el-button @click="goBack">返回</el-button>
          <el-button type="primary" :loading="submitting" @click="submit">保存任务</el-button>
        </div>
      </div>

      <div class="task-form-content">
        <div class="task-form-main">
          <div class="panel">
            <div class="panel-title">任务内容</div>
            <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
              <el-form-item label="任务标题" prop="title">
                <el-input v-model="form.title" maxlength="120" show-word-limit placeholder="请输入任务标题" />
              </el-form-item>
              <el-form-item label="任务说明" prop="content">
                <Editor v-model="form.content" :min-height="260" />
              </el-form-item>
              <el-form-item label="上传附件">
                <Upload v-model="resourceIdList" :resource-list="resourceList" :is-tips="false" />
              </el-form-item>
            </el-form>
          </div>
        </div>

        <div class="task-form-side">
          <div class="panel">
            <div class="panel-title">任务属性</div>
            <el-form ref="metaFormRef" :model="form" :rules="rules" label-position="top">
              <el-form-item label="执行人" prop="executeId">
                <SelectUser v-model="form.executeId" placeholder="请选择执行人" />
              </el-form-item>
              <el-form-item label="参与人">
                <SelectUser v-model="participantIds" multiple placeholder="请选择参与人" />
              </el-form-item>
              <el-form-item label="日期范围" prop="dateRange">
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 100%"
                  @change="syncDateFields"
                />
              </el-form-item>
              <el-form-item label="时间范围" prop="timeRange">
                <el-time-picker
                  v-model="timeRange"
                  is-range
                  value-format="HH:mm"
                  range-separator="-"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  style="width: 100%"
                  @change="syncTimeFields"
                />
              </el-form-item>
              <el-form-item label="优先级" prop="priorityType">
                <el-select v-model="form.priorityType" style="width: 100%">
                  <el-option label="重要紧急" :value="1" />
                  <el-option label="重要不紧急" :value="2" />
                  <el-option label="不重要紧急" :value="3" />
                  <el-option label="不重要不紧急" :value="4" />
                </el-select>
              </el-form-item>
              <el-form-item label="提醒时间">
                <el-select v-model="form.remindType" clearable style="width: 100%">
                  <el-option label="不提醒" :value="-1" />
                  <el-option label="开始前5分钟" :value="5" />
                  <el-option label="开始前30分钟" :value="30" />
                  <el-option label="开始前1小时" :value="60" />
                  <el-option label="开始前1天" :value="1440" />
                </el-select>
              </el-form-item>
              <el-form-item label="父任务ID">
                <el-input v-model="form.parentId" placeholder="如为子任务可自动带入" disabled />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { computed, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Editor from '@/components/Editor/index.vue'
import SelectUser from '@/components/SelectUser/SelectUser.vue'
import Upload from '@/components/FileUpload/upload.vue'
import { taskAdd } from '@/api/otr/task/core'

const router = useRouter()
const route = useRoute()
const submitting = ref(false)
const formRef = ref<ElFormInstance>()
const metaFormRef = ref<ElFormInstance>()
const resourceIdList = ref<Array<string | number>>([])
const resourceList = ref<any[]>([])
const participantIds = ref<Array<string | number>>([])
const dateRange = ref<string[]>([])
const timeRange = ref<string[]>([])
const currentUser = readUserInfo()

const form = reactive({
  title: '',
  content: '',
  executeId: currentUser.id || currentUser.userId || undefined,
  participantId: '',
  startDate: '',
  endDate: '',
  startTime: '09:00',
  endTime: '18:00',
  dateName: '',
  dateType: '7',
  recycleContent: '',
  recycleType: null as string | number | null,
  recycleInterval: null as string | number | null,
  priorityType: 4,
  remindType: -1,
  parentId: String(route.query.ptaskId || ''),
  resourceIdList: [] as Array<string | number>,
})

const rules = reactive({
  title: [{ required: true, message: '请填写任务标题', trigger: 'blur' }],
  content: [{ required: true, message: '请填写任务说明', trigger: 'blur' }],
  executeId: [{ required: true, message: '请选择执行人', trigger: 'change' }],
  dateRange: [{ validator: validateDateRange, trigger: 'change' }],
  timeRange: [{ validator: validateTimeRange, trigger: 'change' }],
})

function readUserInfo() {
  try {
    return JSON.parse(localStorage.getItem('userInfo') || '{}')
  } catch {
    return {}
  }
}

function validateDateRange(_: any, __: any, callback: (error?: Error) => void) {
  if (!dateRange.value?.length || !dateRange.value[0] || !dateRange.value[1]) {
    callback(new Error('请选择日期范围'))
    return
  }
  callback()
}

function validateTimeRange(_: any, __: any, callback: (error?: Error) => void) {
  if (!timeRange.value?.length || !timeRange.value[0] || !timeRange.value[1]) {
    callback(new Error('请选择时间范围'))
    return
  }
  callback()
}

function syncDateFields() {
  form.startDate = dateRange.value?.[0] || ''
  form.endDate = dateRange.value?.[1] || ''
  form.dateName = form.startDate && form.endDate ? `${form.startDate}~${form.endDate}` : ''
  form.recycleContent = form.dateName
}

function syncTimeFields() {
  form.startTime = timeRange.value?.[0] || ''
  form.endTime = timeRange.value?.[1] || ''
}

const submitPayload = computed(() => ({
  title: form.title,
  content: form.content,
  executeId: form.executeId,
  participantId: participantIds.value.join(','),
  startDate: form.startDate,
  endDate: form.endDate,
  startTime: form.startTime,
  endTime: form.endTime,
  dateName: form.dateName,
  dateType: form.dateType,
  recycleContent: form.recycleContent,
  recycleType: form.recycleType,
  recycleInterval: form.recycleInterval,
  priorityType: form.priorityType,
  remindType: form.remindType,
  parentId: form.parentId || null,
  resourceIdList: resourceIdList.value,
  leaderId: form.executeId,
}))

async function submit() {
  const validMain = await formRef.value?.validate().catch(() => false)
  const validMeta = await metaFormRef.value?.validate().catch(() => false)
  if (!validMain || !validMeta) return

  submitting.value = true
  try {
    await taskAdd(submitPayload.value)
    ElMessage.success('任务已保存')
    router.push('/otr/task/list')
  } finally {
    submitting.value = false
  }
}

function goBack() {
  router.back()
}

dateRange.value = []
timeRange.value = ['09:00', '18:00']
syncDateFields()
syncTimeFields()
</script>

<style scoped lang="scss">
.task-form-page {
  .task-form-card {
    background: #fff;
    border-radius: 10px;
    padding: 24px;
  }

  .task-form-header {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 16px;
    margin-bottom: 24px;
    padding-bottom: 20px;
    border-bottom: 1px solid #eef2f6;
  }

  .task-form-title {
    font-size: 22px;
    font-weight: 600;
    color: #1f2937;
  }

  .task-form-subtitle {
    margin-top: 6px;
    color: #6b7280;
    font-size: 13px;
  }

  .task-form-actions {
    display: flex;
    gap: 12px;
  }

  .task-form-content {
    display: grid;
    grid-template-columns: minmax(0, 2fr) minmax(320px, 1fr);
    gap: 20px;
  }

  .panel {
    padding: 20px;
    border: 1px solid #e5e7eb;
    border-radius: 10px;
    background: linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
  }

  .panel-title {
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: 600;
    color: #111827;
  }

  :deep(.el-form-item__label) {
    color: #374151;
    font-weight: 500;
  }

  @media (max-width: 1100px) {
    .task-form-content {
      grid-template-columns: 1fr;
    }

    .task-form-header {
      flex-direction: column;
    }
  }
}
</style>

