<template>
  <view class="form-container">
    <u-form :model="formData" ref="formRef" :rules="rules" label-width="180rpx">
      <u-form-item label="合同编号" prop="code">
        <u-input v-model="formData.code" placeholder="请输入合同编号" />
      </u-form-item>
      <u-form-item label="合同名称" prop="name">
        <u-input v-model="formData.name" placeholder="请输入合同名称" />
      </u-form-item>
      <u-form-item label="合同状态" prop="status">
        <u-picker 
          v-model="formData.status" 
          :range="statusOptions"
          range-key="text"
          @change="onStatusChange"
        >
          <u-input 
            v-model="statusText" 
            disabled 
            placeholder="请选择合同状态" 
            suffix-icon="arrow-down"
          />
        </u-picker>
      </u-form-item>
      <u-form-item label="签订日期" prop="signDate">
        <uni-datetime-picker v-model="formData.signDate" type="date" />
      </u-form-item>
      <u-form-item label="合同开始日期" prop="startDate">
        <uni-datetime-picker v-model="formData.startDate" type="date" />
      </u-form-item>
      <u-form-item label="合同结束日期" prop="endDate">
        <uni-datetime-picker v-model="formData.endDate" type="date" />
      </u-form-item>
      <u-form-item label="合同金额" prop="amount">
        <u-input v-model="formData.amount" placeholder="请输入合同金额" type="number" />
      </u-form-item>
      <u-form-item label="备注" prop="remark">
        <u-textarea v-model="formData.remark" placeholder="请输入备注" />
      </u-form-item>
      <u-form-item label="岗位ID" prop="postId">
        <u-input v-model="formData.postId" placeholder="请输入岗位ID" />
      </u-form-item>
      <!-- TODO: 附件上传 -->
    </u-form>
    <u-button
      type="primary"
      @click="submit"
      class="submit-btn"
      :loading="submitting"
      :disabled="submitting"
    >提交</u-button>
  </view>
</template>

<script setup>
import { ref, reactive, computed, toRaw } from 'vue'
import DemoContractApi from '@/sheep/api/infra/democontract'
import { onLoad } from '@dcloudio/uni-app'

const formType = ref('create')
const formData = reactive({
  id: undefined,
  code: '',
  name: '',
  status: 0,
  signDate: '',
  startDate: '',
  endDate: '',
  amount: undefined,
  remark: '',
  postId: ''
})

const statusOptions = [
  { value: 0, text: '草稿' },
  { value: 1, text: '审核中' },
  { value: 2, text: '已通过' },
  { value: 3, text: '已拒绝' }
]

const statusText = computed(() => {
  const option = statusOptions.find(item => item.value === formData.status)
  return option ? option.text : '请选择合同状态'
})

const rules = {
  code: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  amount: [{ required: true, message: '合同金额不能为空', trigger: 'blur' }],
  postId: [{ required: true, message: '岗位ID不能为空', trigger: 'blur' }]
}

const formRef = ref(null)
const submitting = ref(false)

const formTitle = computed(() => {
  return formType.value === 'create' ? '新增合同' : '修改合同'
})

onLoad((options) => {
  if (options.type) {
    formType.value = options.type
  }
  if (options.id) {
    getDemo(options.id)
  }
})

const getDemo = async (id) => {
  const res = await DemoContractApi.getDemoContract(id)
  if (!res || res.code !== 0) {
    return
  }
  const data = res.data || {}
  formData.id = data.id
  formData.code = data.code || ''
  formData.name = data.name || ''
  formData.status = Number.isNaN(Number(data.status)) ? 0 : Number(data.status)
  formData.signDate = data.signDate || ''
  formData.startDate = data.startDate || ''
  formData.endDate = data.endDate || ''
  formData.amount = data.amount !== undefined && data.amount !== null ? String(data.amount) : ''
  formData.remark = data.remark || ''
  formData.postId = data.postId !== undefined && data.postId !== null ? String(data.postId) : ''
}

const onStatusChange = (e) => {
  formData.status = statusOptions[e.detail.value].value
}

const validateForm = async () => {
  if (!formRef.value || typeof formRef.value.validate !== 'function') {
    throw new Error('表单未准备就绪')
  }
  try {
    await formRef.value.validate()
    return true
  } catch (error) {
    throw error
  }
}

const buildPayload = () => {
  const raw = toRaw(formData)
  const payload = {
    ...raw,
    status: Number(raw.status)
  }
  if (Number.isNaN(payload.status)) {
    payload.status = 0
  }
  if (payload.amount !== undefined && payload.amount !== null && payload.amount !== '') {
    const amountNumber = Number(payload.amount)
    payload.amount = Number.isNaN(amountNumber) ? payload.amount : amountNumber
  }
  if (formType.value === 'create') {
    delete payload.id
  }
  return payload
}

const submit = async () => {
  if (submitting.value) {
    return
  }
  try {
    await validateForm()
  } catch (error) {
    return
  }

  const payload = buildPayload()
  const apiFn = formType.value === 'create' ? DemoContractApi.createDemoContract : DemoContractApi.updateDemoContract

  submitting.value = true
  try {
    const result = await apiFn(payload)
    if (!result || result.code !== 0) {
      return
    }
    uni.showToast({
      title: formType.value === 'create' ? '新增成功' : '修改成功',
      icon: 'success'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 600)
  } finally {
    submitting.value = false
  }
}
</script>

<style lang="scss" scoped>
.form-container {
  padding: 30rpx;
  background: #fff;
}
.submit-btn {
  margin-top: 30rpx;
}
</style>
