<template>
  <el-dialog
    v-model="showDialog"
    :title="formData.id ? t('updateClassroom') : t('addClassroom')"
    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('campusId')" prop="campus_id">
        <el-select
          class="input-width"
          v-model="formData.campus_id"
          clearable
          :placeholder="t('campusIdPlaceholder')"
        >
          <el-option label="请选择" value=""></el-option>
          <el-option
            v-for="(item, index) in campusIdList"
            :key="index"
            :label="item['campus_name']"
            :value="item['id']"
          />
        </el-select>
      </el-form-item>

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

      <el-form-item :label="t('headCoach')" prop="head_coach">
        <el-select
          class="input-width"
          v-model="formData.head_coach"
          clearable
          :placeholder="t('headCoachPlaceholder')"
        >
          <el-option label="请选择" value=""></el-option>
          <el-option
            v-for="(item, index) in headCoachList"
            :key="index"
            :label="item['name']"
            :value="item['id']"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('ageGroup')">
        <el-input
          v-model="formData.age_group"
          type="number"
          clearable
          :placeholder="t('ageGroupPlaceholder')"
          class="input-width"
        />
      </el-form-item>

      <el-form-item :label="t('classType')" prop="class_type">
        <el-select
          class="input-width"
          v-model="formData.class_type"
          clearable
          :placeholder="t('classTypePlaceholder')"
        >
          <el-option label="请选择" value=""></el-option>
          <el-option
            v-for="(item, index) in class_typeList"
            :key="index"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('assistantCoach')">
        <el-select
          class="input-width"
          v-model="formData.assistant_coach"
          clearable
          :placeholder="t('assistantCoachPlaceholder')"
        >
          <el-option label="请选择" value=""></el-option>
          <el-option
            v-for="(item, index) in assistantCoachList"
            :key="index"
            :label="item['name']"
            :value="item['id']"
          />
        </el-select>
      </el-form-item>

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

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

      <el-form-item :label="t('remarks')">
        <el-input
          v-model="formData.remarks"
          clearable
          :placeholder="t('remarksPlaceholder')"
          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 {
  addClassroom,
  editClassroom,
  getClassroomInfo,
  getWithCampusList,
  getWithPersonnelList,
} from '@/app/api/classroom'

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

/**
 * 表单数据
 */
const initialFormData = {
  id: '',
  campus_id: '',
  class_name: '',
  head_coach: '',
  age_group: '',
  class_type: '',
  assistant_coach: '',
  status: '',
  sort_order: '',
  remarks: '',
}
const formData: Record<string, any> = reactive({ ...initialFormData })

const formRef = ref<FormInstance>()

// 表单验证规则
const formRules = computed(() => {
  return {
    campus_id: [
      { required: true, message: t('campusIdPlaceholder'), trigger: 'blur' },
    ],
    class_name: [
      { required: true, message: t('classNamePlaceholder'), trigger: 'blur' },
    ],
    head_coach: [
      { required: true, message: t('headCoachPlaceholder'), trigger: 'blur' },
    ],
    age_group: [
      { required: true, message: t('ageGroupPlaceholder'), trigger: 'blur' },
    ],
    class_type: [
      { required: true, message: t('classTypePlaceholder'), trigger: 'blur' },
    ],
    assistant_coach: [
      {
        required: true,
        message: t('assistantCoachPlaceholder'),
        trigger: 'blur',
      },
    ],
    status: [
      { required: true, message: t('statusPlaceholder'), trigger: 'blur' },
    ],
    sort_order: [
      { required: true, message: t('sortOrderPlaceholder'), trigger: 'blur' },
    ],
    remarks: [
      { required: true, message: t('remarksPlaceholder'), trigger: 'blur' },
    ],
  }
})

const emit = defineEmits(['complete'])

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

  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 class_typeList = ref([])
const class_typeDictList = async () => {
  class_typeList.value = await (
    await useDictionary('class_type')
  ).data.dictionary
}
class_typeDictList()
watch(
  () => class_typeList.value,
  () => {
    formData.class_type = class_typeList.value[0].value
  }
)
let statusList = ref([])
const statusDictList = async () => {
  statusList.value = await (await useDictionary('SiteStatus')).data.dictionary
}
statusDictList()
watch(
  () => statusList.value,
  () => {
    formData.status = statusList.value[0].value
  }
)

const campusIdList = ref([] as any[])
const setCampusIdList = async () => {
  campusIdList.value = await (await getWithCampusList({})).data
}
setCampusIdList()
const headCoachList = ref([] as any[])
const setHeadCoachList = async () => {
  headCoachList.value = await (await getWithPersonnelList({})).data
}
setHeadCoachList()
const assistantCoachList = ref([] as any[])
const setAssistantCoachList = async () => {
  assistantCoachList.value = await (await getWithPersonnelList({})).data
}
setAssistantCoachList()
const setFormData = async (row: any = null) => {
  Object.assign(formData, initialFormData)
  loading.value = true
  if (row) {
    const data = await (await getClassroomInfo(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>
