<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1200px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-divider content-position="left">车辆信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="汽车品牌" prop="carBrand">
            <el-input v-model="formData.carBrand" placeholder="请输入汽车品牌" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车型" prop="carModel">
            <el-input v-model="formData.carModel" placeholder="请输入车型" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="车牌号" prop="licensePlate">
            <el-input v-model="formData.licensePlate" placeholder="请输入车牌号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="厂牌型号" prop="factoryModel">
            <el-input v-model="formData.factoryModel" placeholder="请输入厂牌型号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="车架号" prop="vin">
            <el-input v-model="formData.vin" placeholder="请输入车架号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发动机号" prop="engineNo">
            <el-input v-model="formData.engineNo" placeholder="请输入发动机号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发票日期" prop="invoiceDate">
            <el-date-picker
              v-model="formData.invoiceDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择发票日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发票金额" prop="invoiceAmount">
            <el-input-number
              v-model="formData.invoiceAmount"
              :min="0"
              :precision="2"
              :step="0.01"
              controls-position="right"
              placeholder="请输入发票金额"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="购买时公里数" prop="purchaseMileage">
            <el-input v-model="formData.purchaseMileage" placeholder="请输入购买时公里数" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="发票图片" prop="invoiceUrl">
            <UploadImg v-model="formData.invoiceUrl" :file-size="10" :file-type="['image/jpeg', 'image/png', 'image/jpg', 'image/gif']" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">购买方信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="服务购买方" prop="serviceBuyer">
            <el-input v-model="formData.serviceBuyer" placeholder="请输入服务购买方" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车辆购买方" prop="carBuyer">
            <el-input v-model="formData.carBuyer" placeholder="请输入车辆购买方" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="证件类型" prop="certType">
            <el-select v-model="formData.certType" placeholder="请选择证件类型" style="width: 100%">
              <el-option label="请选择字典生成" value="" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="证件号码" prop="certNo">
            <el-input v-model="formData.certNo" placeholder="请输入证件号码" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系电话" prop="mobile">
            <el-input v-model="formData.mobile" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会员邮箱" prop="memberEmail">
            <el-input v-model="formData.memberEmail" placeholder="请输入会员邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="联系地址" prop="contactAddress">
            <el-input v-model="formData.contactAddress" placeholder="请输入联系地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="门店" prop="storeId">
            <el-select
              v-model="formData.storeId"
              placeholder="请选择门店"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="store in storeList"
                :key="store.id"
                :label="store.storeName"
                :value="store.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">产品信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="续保产品" prop="productId">
            <el-select
              v-model="formData.productId"
              placeholder="请选择续保产品"
              filterable
              style="width: 100%"
              @change="handleProductChange"
            >
              <el-option
                v-for="product in productList"
                :key="product.id"
                :label="product.productName"
                :value="product.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务产品" prop="serviceProduct">
            <el-input v-model="formData.serviceProduct" placeholder="选择产品后自动填充" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="产品时效" prop="productValidity">
            <el-input v-model="formData.productValidity" placeholder="选择产品后自动填充" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品费用" prop="productFee">
            <el-input-number
              v-model="formData.productFee"
              :min="0"
              :precision="2"
              :step="0.01"
              controls-position="right"
              placeholder="请输入产品费用"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="原厂质保时长" prop="originalWarrantyYears">
            <el-input v-model="formData.originalWarrantyYears" placeholder="请输入原厂质保时长" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="原厂质保里程" prop="originalWarrantyMileage">
            <el-input v-model="formData.originalWarrantyMileage" placeholder="请输入原厂质保里程" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="结算方式" prop="settlementMethod">
            <el-input v-model="formData.settlementMethod" placeholder="请输入结算方式" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="录单人" prop="inputUser">
            <el-input v-model="formData.inputUser" placeholder="请输入录单人" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">其他信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="合同备注" prop="contractRemark">
            <el-input v-model="formData.contractRemark" type="textarea" :rows="3" placeholder="请输入合同备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { RenewalOrderApi, RenewalOrderVO } from '@/api/car/renewalorder'
import { RenewalProductApi, RenewalProductVO } from '@/api/car/renewalproduct'
import { StoreApi, StoreVO } from '@/api/tire/store'
import UploadImg from '@/components/UploadFile/src/UploadImg.vue'

/** 车辆续保订单 表单 */
defineOptions({ name: 'RenewalOrderForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const productList = ref<RenewalProductVO[]>([]) // 续保产品列表
const storeList = ref<StoreVO[]>([]) // 门店列表
const formData = ref({
  id: undefined,
  carBrand: undefined,
  carModel: undefined,
  licensePlate: undefined,
  factoryModel: undefined,
  invoiceAmount: undefined,
  purchaseMileage: undefined,
  engineNo: undefined,
  vin: undefined,
  invoiceDate: undefined,
  invoiceUrl: undefined,
  serviceBuyer: undefined,
  carBuyer: undefined,
  certType: undefined,
  mobile: undefined,
  certNo: undefined,
  contactAddress: undefined,
  memberEmail: undefined,
  storeId: undefined,
  productId: undefined,
  serviceProduct: undefined,
  productValidity: undefined,
  originalWarrantyYears: undefined,
  originalWarrantyMileage: undefined,
  productFee: undefined,
  settlementMethod: undefined,
  remark: undefined,
  inputUser: undefined,
  contractRemark: undefined
})
const formRules = reactive({
  licensePlate: [{ required: true, message: '车牌号不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '续保产品不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 获取门店列表 */
const getStoreList = async () => {
  try {
    const data = await StoreApi.getStorePage({ pageNo: 1, pageSize: -1 })
    storeList.value = data.list || []
  } catch (error) {
    console.error('获取门店列表失败:', error)
  }
}

/** 获取续保产品列表 */
const getProductList = async () => {
  try {
    const data = await RenewalProductApi.getRenewalProductPage({ pageNo: 1, pageSize: -1 })
    productList.value = data.list || []
  } catch (error) {
    console.error('获取续保产品列表失败:', error)
  }
}

/** 处理产品选择变化 */
const handleProductChange = async (productId: number) => {
  if (!productId) {
    formData.value.serviceProduct = undefined
    formData.value.productValidity = undefined
    return
  }
  try {
    const product = await RenewalProductApi.getRenewalProduct(productId)
    // 回显服务产品和产品时效（产品时效 = 产品内容）
    formData.value.serviceProduct = product.productName || ''
    formData.value.productValidity = product.productContent || ''
  } catch (error) {
    console.error('获取产品详情失败:', error)
    message.error('获取产品详情失败')
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 加载门店列表和产品列表
  await Promise.all([getStoreList(), getProductList()])
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await RenewalOrderApi.getRenewalOrder(id)
      // 处理发票日期：如果是Date对象或时间戳，转换为字符串格式 YYYY-MM-DD
      if (data.invoiceDate) {
        if (data.invoiceDate instanceof Date) {
          const year = data.invoiceDate.getFullYear()
          const month = String(data.invoiceDate.getMonth() + 1).padStart(2, '0')
          const day = String(data.invoiceDate.getDate()).padStart(2, '0')
          data.invoiceDate = `${year}-${month}-${day}`
        } else if (typeof data.invoiceDate === 'number' || typeof data.invoiceDate === 'string') {
          // 如果是时间戳或字符串，尝试转换
          const date = new Date(data.invoiceDate)
          if (!isNaN(date.getTime())) {
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            data.invoiceDate = `${year}-${month}-${day}`
          }
        }
      }
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RenewalOrderVO
    if (formType.value === 'create') {
      await RenewalOrderApi.createRenewalOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      await RenewalOrderApi.updateRenewalOrder(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    carBrand: undefined,
    carModel: undefined,
    licensePlate: undefined,
    factoryModel: undefined,
    invoiceAmount: undefined,
    purchaseMileage: undefined,
    engineNo: undefined,
    vin: undefined,
         invoiceDate: undefined,
         invoiceUrl: undefined,
         serviceBuyer: undefined,
    carBuyer: undefined,
    certType: undefined,
    mobile: undefined,
    certNo: undefined,
    contactAddress: undefined,
    memberEmail: undefined,
    storeId: undefined,
    productId: undefined,
    serviceProduct: undefined,
    productValidity: undefined,
    originalWarrantyYears: undefined,
    originalWarrantyMileage: undefined,
    productFee: undefined,
    settlementMethod: undefined,
    remark: undefined,
    inputUser: undefined,
    contractRemark: undefined
  }
  formRef.value?.resetFields()
}
</script>