<template>
  <el-dialog v-model="showDialog" :title="formData.id ? t('updateCoupons') : t('addCoupons')" width="50%"
             class="diy-dialog-wrap"
             :destroy-on-close="true">
    <el-form :model="formData" label-width="120px" ref="formRef" :rules="formRules" class="page-form"
             v-loading="loading">
      <el-form-item :label="t('name')" prop="name">
        <el-input v-model="formData.name" clearable :placeholder="t('namePlaceholder')" class="input-width"/>
      </el-form-item>

      <el-form-item :label="t('nominalValue')" prop="nominal_value">
        <el-input-number v-model="formData.nominal_value" clearable :placeholder="t('nominalValuePlaceholder')"
                         class="input-width"/>
      </el-form-item>

      <el-form-item :label="t('stock')" prop="stock">
        <el-input-number v-model="formData.stock" clearable :placeholder="t('stockPlaceholder')" class="input-width"/>
      </el-form-item>


      <el-form-item :label="t('isShow')" prop="is_show">
        <el-radio-group v-model="formData.is_show" :placeholder="t('isShowPlaceholder')">
          <el-radio
              v-for="(item, index) in is_showList"
              :key="index"
              :label="item.value">
            {{ item.name }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="t('isObsolete')" prop="is_obsolete">
        <el-radio-group v-model="formData.is_obsolete" :placeholder="t('isObsoletePlaceholder')">
          <el-radio label="1">是</el-radio>
          <el-radio label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="t('isLongTermValid')" prop="is_long_term_valid">
        <el-radio-group v-model="formData.is_long_term_valid" :placeholder="t('isLongTermValidPlaceholder')">
          <el-radio label="1">是</el-radio>
          <el-radio label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-show="formData.is_long_term_valid !=='1'" :label="t('validTime')" prop="valid_time">
        <el-date-picker v-model="formData.valid_time" type="daterange"
                        value-format="YYYY-MM-DD"
                        :start-placeholder="t('startDate')" :end-placeholder="t('endDate')"/>
      </el-form-item>

    </el-form>

    <template #footer>
            <span class="dialog-footer">
                <el-button @click="showDialog = false">{{ t('cancel') }}</el-button>
                <el-button type="primary" :loading="loading" @click="confirm(formRef)">{{
                    t('confirm')
                  }}</el-button>
            </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {ref, reactive, computed, watch} from 'vue'
import {useDictionary} from '@/app/api/dict'
import {t} from '@/lang'
import type {FormInstance} from 'element-plus'

import {addCoupons, editCoupons, getCouponsInfo,} from '@/addon/hygl/api/coupons'

let showDialog = ref(false)
const loading = ref(false)

/**
 * 表单数据
 */
const initialFormData = {
  id: '',
  name: '',
  nominal_value: '',
  stock: '100',
  is_show: '1',
  is_long_term_valid: '1',
  is_obsolete: '0',
  valid_time: [],
}
const formData: Record<string, any> = reactive({...initialFormData})

const formRef = ref<FormInstance>()

// 表单验证规则
const formRules = computed(() => {
  return {
    name: [
      {required: true, message: t('namePlaceholder'), trigger: 'blur'},

    ]
    ,
    nominal_value: [
      { required: true, message: t('nominalValuePlaceholder'), trigger: 'blur' },
      {
        validator: (rule: any, value: string, callback: any) => {
          const floatValue = parseFloat(value);

          if (isNaN(floatValue) || floatValue <= 0 || floatValue > 99999 || !/^\d+(\.\d{1,2})?$/.test(value)) {
            callback(new Error(t('请输入0.1-99999')))
          } else {
            callback()
          }
        }
      },
    ]
    ,
    stock: [
      {required: true, message: t('stockPlaceholder'), trigger: 'blur'},
      {
        validator: (rule: any, value: string, callback: any) => {
          if (value && !/^\d{0,99999}$/.test(value)) {
            callback(new Error(t('generateBetween')))
          } else {
            callback()
          }
        }
      },
    ]
    ,
    is_show: [
      {required: true, message: t('isShowPlaceholder'), trigger: 'blur'},

    ]
    ,
    is_long_term_valid: [
      {required: true, message: t('isLongTermValidPlaceholder'), trigger: 'blur'},
    ]
    ,
  }
})

const emit = defineEmits(['complete'])

/**
 * 确认
 * @param formEl
 */
const confirm = async (formEl: FormInstance | undefined) => {
  if (loading.value || !formEl) return
  let save = formData.id ? editCoupons : addCoupons

  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true

      let data = formData

      save(data).then(res => {
        loading.value = false
        showDialog.value = false
        emit('complete')
      }).catch(err => {
        loading.value = false
      })
    }
  })
}

// 获取字典数据
let is_showList = ref([])
const is_showDictList = async () => {
  is_showList.value = await (await useDictionary('is_show_radio')).data.dictionary
}
is_showDictList();
watch(() => is_showList.value, () => {
  formData.is_show = is_showList.value[0].value
})


const setFormData = async (row: any = null) => {
  Object.assign(formData, initialFormData)
  loading.value = true
  if (row) {
    const data = await (await getCouponsInfo(row.id)).data
    if (data) Object.keys(formData).forEach((key: string) => {
      if (data[key] != undefined) formData[key] = data[key]
    })
  }
  loading.value = false
}

// 验证手机号格式
const mobileVerify = (rule: any, value: any, callback: any) => {
  if (value && !/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error(t('generateMobile')))
  } else {
    callback()
  }
}

// 验证身份证号
const idCardVerify = (rule: any, value: any, callback: any) => {
  if (value && !/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(value)) {
    callback(new Error(t('generateIdCard')))
  } else {
    callback()
  }
}

// 验证邮箱号
const emailVerify = (rule: any, value: any, callback: any) => {
  if (value && !/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(value)) {
    callback(new Error(t('generateEmail')))
  } else {
    callback()
  }
}

// 验证请输入整数
const numberVerify = (rule: any, value: any, callback: any) => {
  if (!Number.isInteger(value)) {
    callback(new Error(t('generateNumber')))
  } else {
    callback()
  }
}

defineExpose({
  showDialog,
  setFormData
})
</script>

<style lang="scss" scoped></style>
<style lang="scss">
.diy-dialog-wrap .el-form-item__label {
  height: auto !important;
}
</style>
