<template>
  <!-- 移动端使用抽屉 -->
  <el-drawer
    v-if="isMobile"
    v-model="dialogVisible"
    :title="dialogTitle"
    direction="rtl"
    size="100%"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-position="top"
      v-loading="formLoading"
    >
      <div class="mobile-form-section">
        <div class="mobile-form-section__title">基本信息</div>
        <el-form-item label="司机姓名" prop="driverName">
          <el-input v-model="formData.driverName" placeholder="请输入司机姓名" />
        </el-form-item>
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="formData.licensePlate" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
      </div>

      <div class="mobile-form-section">
        <div class="mobile-form-section__title">车辆参数</div>
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="长（米）" prop="carLength">
              <el-input-number v-model="formData.carLength" :min="0" :precision="2" :step="0.1" controls-position="right" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="宽（米）" prop="carWidth">
              <el-input-number v-model="formData.carWidth" :min="0" :precision="2" :step="0.1" controls-position="right" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="核定吨位（吨）" prop="ratedTonnage">
          <el-input-number v-model="formData.ratedTonnage" :min="0" :precision="2" :step="0.1" controls-position="right" style="width:100%" />
        </el-form-item>
      </div>

      <div class="mobile-form-section">
        <div class="mobile-form-section__title">其他信息</div>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio
              v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <div class="mobile-drawer-footer">
        <el-button @click="dialogVisible = false" style="flex:1">取消</el-button>
        <el-button type="primary" @click="submitForm" :disabled="formLoading" style="flex:1">确定</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- PC端使用对话框 -->
  <Dialog v-else :title="dialogTitle" v-model="dialogVisible" width="500">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="司机姓名" prop="driverName">
        <el-input v-model="formData.driverName" placeholder="请输入司机姓名" />
      </el-form-item>
      <el-form-item label="车牌号" prop="licensePlate">
        <el-input v-model="formData.licensePlate" placeholder="请输入车牌号" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="长（米）" prop="carLength">
        <el-input-number v-model="formData.carLength" :min="0" :precision="2" :step="0.1" :controls="false" class="!w-240px" />
      </el-form-item>
      <el-form-item label="宽（米）" prop="carWidth">
        <el-input-number v-model="formData.carWidth" :min="0" :precision="2" :step="0.1" :controls="false" class="!w-240px" />
      </el-form-item>
      <el-form-item label="核定吨位（吨）" prop="ratedTonnage">
        <el-input-number v-model="formData.ratedTonnage" :min="0" :precision="2" :step="0.1" :controls="false" class="!w-240px" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm" :disabled="formLoading">确定</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as CarApi from '@/api/erp/purchase/car'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

import { computed } from 'vue'
import { useWindowSize } from '@vueuse/core'

defineOptions({ name: 'CarForm' })

const { width } = useWindowSize()
const isMobile = computed(() => width.value < 768)

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  driverName: '',
  licensePlate: '',
  contactPhone: '',
  carLength: undefined,
  carWidth: undefined,
  ratedTonnage: undefined,
  remark: '',
  status: 0
})
const formRules = reactive({
  driverName: [{ required: true, message: '司机姓名不能为空', trigger: 'blur' }],
  licensePlate: [{ required: true, message: '车牌号不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CarApi.getCar(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    driverName: '',
    licensePlate: '',
    contactPhone: '',
    carLength: undefined,
    carWidth: undefined,
    ratedTonnage: undefined,
    remark: '',
    status: 0
  }
  formRef.value?.resetFields()
}
</script>

<style lang="scss" scoped>
.mobile-form-section {
  margin-bottom: 20px;
  
  &__title {
    font-size: 15px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
  }
}

.mobile-drawer-footer {
  display: flex;
  gap: 12px;
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
}
</style>