<template>
  <view class="yd-page-container">
    <!-- 顶部导航栏 -->
    <wd-navbar
      :title="getTitle"
      left-arrow placeholder safe-area-inset-top fixed
      @click-left="handleBack"
    />

    <!-- 加载状态 -->
    <wd-loading v-if="formLoading" />

    <!-- 表单内容 -->
    <wd-form
      v-else
      ref="formRef"
      :model="formData"
      :rules="rules"
    >
      <wd-cell-group border>
        <wd-input
          v-model="formData.productName"
          label="产品名称"
          label-width="180rpx"
          prop="productName"
          clearable
          placeholder="请输入产品名称"
        />
        <wd-picker
          v-model="formData.productType"
          :columns="productTypeOptions"
          label="产品类别"
          label-width="180rpx"
          prop="productType"
          placeholder="请选择产品类别"
          label-key="label"
          value-key="value"
        />
        <wd-textarea
          v-model="formData.productContent"
          label="产品内容"
          label-width="180rpx"
          prop="productContent"
          placeholder="请输入产品内容"
          :maxlength="500"
          show-word-limit
          clearable
        />
        <wd-textarea
          v-model="formData.remark"
          label="备注"
          label-width="180rpx"
          prop="remark"
          placeholder="请输入备注"
          :maxlength="200"
          show-word-limit
          clearable
        />
      </wd-cell-group>
    </wd-form>

    <!-- 底部保存按钮 -->
    <view class="yd-detail-footer">
      <wd-button
        type="primary"
        block
        :loading="submitting"
        @click="handleSubmit"
      >
        保存
      </wd-button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'wot-design-uni/components/wd-form/types'
import type { RenewalProductVO } from '@/api/car/renewalproduct'
import { onLoad } from '@dcloudio/uni-app'
import { computed, onMounted, ref } from 'vue'
import { useToast } from 'wot-design-uni'
import { createRenewalProduct, getRenewalProduct, updateRenewalProduct } from '@/api/car/renewalproduct'
import { getStrDictOptions } from '@/hooks/useDict'
import { navigateBackPlus } from '@/utils'
import { DICT_TYPE } from '@/utils/constants'

definePage({
  style: {
    navigationBarTitleText: '',
    navigationStyle: 'custom',
  },
})

const toast = useToast()
const formRef = ref<FormInstance>()
const productId = ref<number>()
const formLoading = ref(false)
const submitting = ref(false)

const getTitle = computed(() => (productId.value ? '编辑产品' : '新增产品'))

// 产品类别选项
const productTypeOptions = computed(() => {
  return getStrDictOptions(DICT_TYPE.CAR_RENEWAL_PRODUCT_TYPE).map(item => ({
    label: item.label,
    value: item.value,
  }))
})

const formData = ref<RenewalProductVO>({
  productName: undefined,
  productContent: undefined,
  productType: undefined,
  remark: undefined,
})

const rules = {
  productName: [
    { required: true, message: '请输入产品名称' },
  ],
  productType: [
    { required: true, message: '请选择产品类别' },
  ],
}

/** 返回上一页 */
function handleBack() {
  navigateBackPlus()
}

/** 加载产品详情 */
async function getDetail() {
  if (!productId.value) {
    return
  }
  formLoading.value = true
  try {
    const data = await getRenewalProduct(productId.value)
    formData.value = { ...data }
  } catch (error) {
    console.error('获取产品详情失败:', error)
    toast.error('获取产品详情失败')
  } finally {
    formLoading.value = false
  }
}

/** 提交表单 */
async function handleSubmit() {
  const { valid } = await formRef.value?.validate()
  if (!valid) {
    return
  }

  submitting.value = true
  try {
    if (productId.value) {
      await updateRenewalProduct({ ...formData.value, id: productId.value })
      toast.success('修改成功')
    } else {
      await createRenewalProduct(formData.value)
      toast.success('新增成功')
    }
    setTimeout(() => {
      navigateBackPlus()
    }, 500)
  } catch (error) {
    console.error('提交失败:', error)
    toast.error(productId.value ? '修改失败' : '新增失败')
  } finally {
    submitting.value = false
  }
}

/** 页面加载时获取路由参数 */
onLoad((options) => {
  if (options?.id) {
    productId.value = Number(options.id)
  }
})

/** 初始化 */
onMounted(() => {
  getDetail()
})
</script>

<style lang="scss" scoped>
</style>
