<template>
  <el-dialog
    v-model="showDialog"
    :title="formData.id ? t('updatePhysicalTest') : t('addPhysicalTest')"
    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('resourceId')" prop="resource_id">
        <el-input
          v-model="formData.resource_id"
          clearable
          :placeholder="t('resourceIdPlaceholder')"
          class="input-width"
        />
      </el-form-item>

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

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

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

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

      <el-form-item :label="t('createdAt')">
        <el-input
          v-model="formData.created_at"
          clearable
          :placeholder="t('createdAtPlaceholder')"
          class="input-width"
        />
      </el-form-item>

      <el-form-item :label="t('updatedAt')">
        <el-input
          v-model="formData.updated_at"
          clearable
          :placeholder="t('updatedAtPlaceholder')"
          class="input-width"
        />
      </el-form-item>

      <el-form-item :label="t('seatedForwardBend')">
        <el-input
          v-model="formData.seated_forward_bend"
          clearable
          :placeholder="t('seatedForwardBendPlaceholder')"
          class="input-width"
        />
      </el-form-item>

      <el-form-item :label="t('sitUps')">
        <el-input
          v-model="formData.sit_ups"
          clearable
          :placeholder="t('sitUpsPlaceholder')"
          class="input-width"
        />
      </el-form-item>

      <el-form-item :label="t('pushUps')">
        <el-input
          v-model="formData.push_ups"
          clearable
          :placeholder="t('pushUpsPlaceholder')"
          class="input-width"
        />
      </el-form-item>

      <el-form-item :label="t('flamingoBalance')">
        <el-input
          v-model="formData.flamingo_balance"
          clearable
          :placeholder="t('flamingoBalancePlaceholder')"
          class="input-width"
        />
      </el-form-item>

      <el-form-item :label="t('thirtySecJump')">
        <el-input
          v-model="formData.thirty_sec_jump"
          clearable
          :placeholder="t('thirtySecJumpPlaceholder')"
          class="input-width"
        />
      </el-form-item>

      <el-form-item :label="t('standingLongJump')">
        <el-input
          v-model="formData.standing_long_jump"
          clearable
          :placeholder="t('standingLongJumpPlaceholder')"
          class="input-width"
        />
      </el-form-item>

      <el-form-item :label="t('agilityRun')">
        <el-input
          v-model="formData.agility_run"
          clearable
          :placeholder="t('agilityRunPlaceholder')"
          class="input-width"
        />
      </el-form-item>

      <el-form-item :label="t('balanceBeam')">
        <el-input
          v-model="formData.balance_beam"
          clearable
          :placeholder="t('balanceBeamPlaceholder')"
          class="input-width"
        />
      </el-form-item>

      <el-form-item :label="t('tennisThrow')">
        <el-input
          v-model="formData.tennis_throw"
          clearable
          :placeholder="t('tennisThrowPlaceholder')"
          class="input-width"
        />
      </el-form-item>

      <el-form-item :label="t('tenMeterShuttleRun')">
        <el-input
          v-model="formData.ten_meter_shuttle_run"
          clearable
          :placeholder="t('tenMeterShuttleRunPlaceholder')"
          class="input-width"
        />
      </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 {
  addPhysicalTest,
  editPhysicalTest,
  getPhysicalTestInfo,
} from '@/app/api/physical_test'

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

/**
 * 表单数据
 */
const initialFormData = {
  id: '',
  resource_id: '',
  student_id: '',
  height: '',
  weight: '',
  coach_id: '',
  created_at: '',
  updated_at: '',
  seated_forward_bend: '',
  sit_ups: '',
  push_ups: '',
  flamingo_balance: '',
  thirty_sec_jump: '',
  standing_long_jump: '',
  agility_run: '',
  balance_beam: '',
  tennis_throw: '',
  ten_meter_shuttle_run: '',
}
const formData: Record<string, any> = reactive({ ...initialFormData })

const formRef = ref<FormInstance>()

// 表单验证规则
const formRules = computed(() => {
  return {
    resource_id: [
      { required: true, message: t('resourceIdPlaceholder'), trigger: 'blur' },
    ],
    student_id: [
      { required: true, message: t('studentIdPlaceholder'), trigger: 'blur' },
    ],
    height: [
      { required: true, message: t('heightPlaceholder'), trigger: 'blur' },
    ],
    weight: [
      { required: true, message: t('weightPlaceholder'), trigger: 'blur' },
    ],
    coach_id: [
      { required: true, message: t('coachIdPlaceholder'), trigger: 'blur' },
    ],
    created_at: [
      { required: true, message: t('createdAtPlaceholder'), trigger: 'blur' },
    ],
    updated_at: [
      { required: true, message: t('updatedAtPlaceholder'), trigger: 'blur' },
    ],
    seated_forward_bend: [
      {
        required: true,
        message: t('seatedForwardBendPlaceholder'),
        trigger: 'blur',
      },
    ],
    sit_ups: [
      { required: true, message: t('sitUpsPlaceholder'), trigger: 'blur' },
    ],
    push_ups: [
      { required: true, message: t('pushUpsPlaceholder'), trigger: 'blur' },
    ],
    flamingo_balance: [
      {
        required: true,
        message: t('flamingoBalancePlaceholder'),
        trigger: 'blur',
      },
    ],
    thirty_sec_jump: [
      {
        required: true,
        message: t('thirtySecJumpPlaceholder'),
        trigger: 'blur',
      },
    ],
    standing_long_jump: [
      {
        required: true,
        message: t('standingLongJumpPlaceholder'),
        trigger: 'blur',
      },
    ],
    agility_run: [
      { required: true, message: t('agilityRunPlaceholder'), trigger: 'blur' },
    ],
    balance_beam: [
      { required: true, message: t('balanceBeamPlaceholder'), trigger: 'blur' },
    ],
    tennis_throw: [
      { required: true, message: t('tennisThrowPlaceholder'), trigger: 'blur' },
    ],
    ten_meter_shuttle_run: [
      {
        required: true,
        message: t('tenMeterShuttleRunPlaceholder'),
        trigger: 'blur',
      },
    ],
  }
})

const emit = defineEmits(['complete'])

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

  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
        })
    }
  })
}

// 获取字典数据

const setFormData = async (row: any = null) => {
  Object.assign(formData, initialFormData)
  loading.value = true
  if (row) {
    const data = await (await getPhysicalTestInfo(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>
