<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-picker
          v-if="showEffectiveYear"
          v-model="formData.effectiveYear"
          :columns="effectiveYearOptions"
          label="生效年限"
          label-width="180rpx"
          prop="effectiveYear"
          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, watch } from 'vue'
import { useToast } from 'wot-design-uni'
import { createRenewalProduct, getRenewalProduct, updateRenewalProduct } from '@/api/car/renewalproduct'
import { getDictLabel, 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 effectiveYearOptions = computed(() => {
  return getStrDictOptions(DICT_TYPE.CAR_RENEWAL_YEAR).map(item => ({
    label: item.label,
    value: item.value,
  }))
})

/** 仅当产品类别为「无忧」或「无忧延保」时显示生效年限 */
const showEffectiveYear = computed(() => {
  const label = getDictLabel(DICT_TYPE.CAR_RENEWAL_PRODUCT_TYPE, formData.value.productType) || ''
  return label === '无忧' || label === '无忧延保'
})

// 产品类别切换为「无忧」或「无忧延保」时设置生效年限默认值，切换为其他时清空
watch(
  () => formData.value.productType,
  (type) => {
    const label = getDictLabel(DICT_TYPE.CAR_RENEWAL_PRODUCT_TYPE, type) || ''
    if (label === '无忧' || label === '无忧延保') {
      const opts = getStrDictOptions(DICT_TYPE.CAR_RENEWAL_YEAR)
      if (opts.length > 0 && !formData.value.effectiveYear) {
        formData.value.effectiveYear = opts[0].value
      }
    } else {
      formData.value.effectiveYear = undefined
    }
  },
)

const formData = ref<RenewalProductVO>({
  productName: undefined,
  productContent: undefined,
  productType: undefined,
  effectiveYear: 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('新增成功')
    }
    // 标记列表页需要刷新，返回后列表会重新拉取数据
    uni.setStorageSync('renewalproduct_list_need_refresh', true)
    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>
