<template>
  <el-dialog
    v-model="showDialog"
    :title="
      formData.id ? t('updateCampusPersonRole') : t('addCampusPersonRole')
    "
    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('personId')" prop="person_id">
        <el-select
          class="input-width"
          v-model="formData.person_id"
          clearable
          :placeholder="t('personIdPlaceholder')"
        >
          <el-option label="请选择" value=""></el-option>
          <el-option
            v-for="(item, index) in personIdList"
            :key="index"
            :label="item['name']"
            :value="item['id']"
          />
        </el-select>
      </el-form-item>
	  
	  
<!-- 	  <el-form-item :label="电话">
	    <el-input
	      v-model="formData.age_group"
	      type="number"
	      clearable
	      :placeholder="t('ageGroupPlaceholder')"
	      class="input-width"
	    />
	  </el-form-item> -->
	  

      <el-form-item :label="t('roleId')" prop="role_id">
        <el-select
          class="input-width"
          v-model="formData.role_id"
          clearable
          :placeholder="t('roleIdPlaceholder')"
        >
          <el-option label="请选择" value=""></el-option>
          <el-option
            v-for="(item, index) in roleIdList"
            :key="index"
            :label="item['role_name']"
            :value="item['role_id']"
          />
        </el-select>
      </el-form-item>

  <!--    <el-form-item :label="t('deptId')" v-if="!formData.dept_id">
        <el-select
          class="input-width"
          v-model="formData.dept_id"
          clearable
          :placeholder="t('deptIdPlaceholder')"
        >
          <el-option label="请选择" value=""></el-option>
          <el-option
            v-for="(item, index) in deptIdList"
            :key="index"
            :label="item['department_name']"
            :value="item['id']"
          />
        </el-select> -->
      <!-- </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 { useRoute } from 'vue-router'
const route = useRoute()
import {
  addCampusPersonRole,
  editCampusPersonRole,
  getCampusPersonRoleInfo,
  getWithCampusList,
  getWithPersonnelList,
  getWithSysRoleList,
  getWithDepartmentsList,
} from '@/app/api/campus_person_role'

let showDialog = ref(false)
const loading = ref(false)
const pageName = route.meta.title


/**
 * 表单数据
 */
const initialFormData = {
  id: '',
  campus_id: '',
  person_id: '',
  role_id: '',
  dept_id: ''
}

if(pageName == '市场人员列表'){
	initialFormData.dept_id = 1;
}else if(pageName == '销售人员列表'){
	initialFormData.dept_id = 2;
	// campusPersonRoleTable.searchParam.role_id = 2;
}

const formData: Record<string, any> = reactive({ ...initialFormData })

const formRef = ref<FormInstance>()

// 表单验证规则
const formRules = computed(() => {
  return {
    campus_id: [
      { required: true, message: t('campusIdPlaceholder'), trigger: 'blur' },
    ],
    person_id: [
      { required: true, message: t('personIdPlaceholder'), trigger: 'blur' },
    ],
    role_id: [
      { required: true, message: t('roleIdPlaceholder'), trigger: 'blur' },
    ],
    dept_id: [
      { required: true, message: t('deptIdPlaceholder'), trigger: 'blur' },
    ],
  }
})

const emit = defineEmits(['complete'])

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

  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 campusIdList = ref([] as any[])
const setCampusIdList = async () => {
  campusIdList.value = await (await getWithCampusList({})).data
}
setCampusIdList()
const personIdList = ref([] as any[])
const setPersonIdList = async () => {
  personIdList.value = await (await getWithPersonnelList({})).data
}
setPersonIdList()
const roleIdList = ref([] as any[])
const setRoleIdList = async () => {
  roleIdList.value = await (await getWithSysRoleList({dept_id:formData.dept_id})).data
}
setRoleIdList()
const deptIdList = ref([] as any[])
const setDeptIdList = async () => {
  deptIdList.value = await (await getWithDepartmentsList({})).data
}
setDeptIdList()
const setFormData = async (row: any = null) => {
  Object.assign(formData, initialFormData)
  if (row.dept_id) {
    formData.dept_id = parseInt(row.dept_id)
  }
  loading.value = true
  if (row.id) {
    const data = await (await getCampusPersonRoleInfo(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>
