<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="450">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="用户名称" prop="userId">
        <el-select
          v-model="formData.userId"
          placeholder="请选择工卡用户"
          clearable
          class="!w-240px"
          @change="handleSelectUser"
        >
          <el-option
            v-for="item in userList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-row>-->
<!--        <el-col :span="15">-->
<!--          <el-form-item label="工卡编码" prop="cardCode">-->
<!--            <el-input-->
<!--              v-model="formData.cardCode"-->
<!--              placeholder="请输入工卡编码"-->
<!--              class="!w-240px"-->
<!--            />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="8">-->
<!--          <el-form-item label-width="80">-->
<!--            <el-switch-->
<!--              v-model="autoGenFlag"-->
<!--              active-color="#13ce66"-->
<!--              active-text="自动生成"-->
<!--              @change="handleAutoGenChange"-->
<!--            />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--      </el-row>-->
      <el-form-item label="工卡NFC" prop="cardNfc">
        <el-input
          v-model="formData.cardNfc"
          placeholder="请输入工卡NFC"
          maxlength="16"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="工卡类型" prop="cardType">
        <el-select
          v-model="formData.cardType"
          placeholder="请选择工卡类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CARD_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="exStatus">
        <el-radio-group v-model="formData.exStatus">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.JOB_CARD_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="exRemark">
        <el-input
          v-model="formData.exRemark"
          placeholder="请输入备注"
          class="!w-240px"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as WorkCardApi from '@/api/hw/hardware/workCard/index'
// import * as AutocodeApi from '@/api/system/autocode/rule'

defineOptions({ name: 'WorkCardForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const autoGenFlag = ref(false) // 是否自动生成编码
const userList = ref([]) // 用户列表

const formData = ref({
  userId: undefined,
  id: undefined,
  cardCode: '',
  cardNfc: '',
  cardType: undefined,
  exStatus: '1',
  exRemark: '',
  userName: undefined,
})

const formRules = reactive({
  // cardCode: [{ required: true, message: '工卡编码不能为空', trigger: 'blur' }],
  id: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
  cardNfc: [{ required: true, message: '工卡NFC不能为空', trigger: 'blur' }],
  cardType: [{ required: true, message: '工卡类型不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
console.log(id,'id')
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await WorkCardApi.workCardInfo(id)
      formData.value = data
      formData.value.userId=data.userId
      formData.value.userName = data.userName
      formData.value.exStatus=Number(data.exStatus)
      // 转换工卡类型
      if (data.cardType === '1') {
        formData.value.cardType = '员工卡'
      } else if (data.cardType === '2') {
        formData.value.cardType = '临时卡'
      }
    } 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 }
    // 转换工卡类型
    if (data.cardType === '员工卡') {
      data.cardType = '1'
    } else if (data.cardType === '临时卡') {
      data.cardType = '2'
    }
    if (formType.value === 'create') {
      await WorkCardApi.addWorkCard(data)
      message.success(t('common.createSuccess'))
    } else {
      await WorkCardApi.updateWorkCard(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    userId: undefined,
    id: undefined,
    cardCode: '',
    cardNfc: '',
    cardType: undefined,
    exStatus: '1',
    exRemark: ''
  }
  autoGenFlag.value = false
  formRef.value?.resetFields()
}

/** 自动生成编码 */
// const handleAutoGenChange = async (value: boolean) => {
//   if (value) {
//     formData.value.cardCode = await AutocodeApi.genCode('CARD_CODE')
//   } else {
//     formData.value.cardCode = ''
//   }
// }

/** 选择用户 */
const handleSelectUser = (value: string) => {
  const user = userList.value.find(item => item.value === value)
  if (user) {
    formData.value.userName = user.label
  }
}

/** 获取用户列表 */
const getUserList = async () => {
  const data = await WorkCardApi.getUserList({ pageNo: 1,  selectAll:1 })
  userList.value = data.list.map(item => ({
    value: item.id,
    label: item.nickname
  }))
}

/** 初始化 */
onMounted(async () => {
  await getUserList()
})
</script>
