<template>
  <el-dialog v-model="showDialog" :title="formData.id ? t('updateUser') : t('addUser')" 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('tel')" prop="tel">
        <el-input v-model="formData.tel" clearable :placeholder="t('telPlaceholder')" class="input-width"/>
      </el-form-item>

      <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('pic')">
        <upload-image v-model="formData.pic"/>
      </el-form-item>

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

      <el-form-item :label="t('pid')" prop="pid">
        <el-select class="input-width" v-model="formData.pid" clearable :placeholder="t('pidPlaceholder')">
          <el-option label="顶级" :value="0"></el-option>
          <el-option
              v-for="(item, index) in pidList"
              :key="index"
              :label="item['name']"
              :value="item['id']"
          />
        </el-select>
      </el-form-item>

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

      <el-form-item :label="t('wxOpenid')" v-show="!formData.id">
        <el-input v-model="formData.wx_openid" clearable :placeholder="t('wxOpenidPlaceholder')" class="input-width"/>
      </el-form-item>

      <el-form-item :label="t('wxUnionid')" v-show="!formData.id">
        <el-input v-model="formData.wx_unionid" clearable :placeholder="t('wxUnionidPlaceholder')" class="input-width"/>
      </el-form-item>


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

      <el-form-item :label="t('birthday')" class="input-width">
        <el-date-picker
            class="flex-1 !flex"
            v-model="formData.birthday"
            clearable
            type="date"
            value-format="YYYY-MM-DD"
            :placeholder="t('birthdayPlaceholder')">
        </el-date-picker>
      </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>

    <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 {addUser, editUser, getUserInfo, getWithUserList,} from '@/addon/hygl/api/user'

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

/**
 * 表单数据
 */
const initialFormData = {
  id: '',
  tel: '',
  name: '',
  pic: '',
  password: '',
  pid: 0,
  // level: '',
  wx_openid: '',
  wx_unionid: '',
  sex: '1',
  birthday: '',
  is_show: '1',
}
const formData: Record<string, any> = reactive({...initialFormData})

const formRef = ref<FormInstance>()

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

    ]
    ,
    name: [
      {required: true, message: t('namePlaceholder'), trigger: 'blur'},

    ]
    ,
    pic: [
      {required: true, message: t('picPlaceholder'), trigger: 'blur'},

    ]
    ,
    password: [
      {required: true, message: t('passwordPlaceholder'), trigger: 'blur'},

    ]
    ,
    pid: [
      {required: true, message: t('pidPlaceholder'), trigger: 'blur'},

    ]
    ,
    level: [
      {required: true, message: t('levelPlaceholder'), trigger: 'blur'},

    ]
    ,
    wx_openid: [
      {required: true, message: t('wxOpenidPlaceholder'), trigger: 'blur'},

    ]
    ,
    wx_unionid: [
      {required: true, message: t('wxUnionidPlaceholder'), trigger: 'blur'},

    ]
    ,
    sex: [
      {required: true, message: t('sexPlaceholder'), trigger: 'blur'},

    ]
    ,
    birthday: [
      {required: true, message: t('birthdayPlaceholder'), trigger: 'blur'},

    ]
    ,
    is_show: [
      {required: true, message: t('isShowPlaceholder'), trigger: 'blur'},

    ]
    ,
  }
})

const emit = defineEmits(['complete'])

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

  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 site_idList = ref([])
const site_idDictList = async () => {
  site_idList.value = await (await useDictionary('placeholder_')).data.dictionary
}
site_idDictList();
watch(() => site_idList.value, () => {
  formData.site_id = site_idList.value[0].value
})

//获取全部用户列表
const pidList = ref([] as any[])
const setPidList = async () => {
  pidList.value = await (await getWithUserList({})).data.data
}
setPidList()

let sexList = ref([])
const sexDictList = async () => {
  sexList.value = await (await useDictionary('sex_radio')).data.dictionary
}
sexDictList();
watch(() => sexList.value, () => {
  formData.sex = sexList.value[0].value
})
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 getUserInfo(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>
