<script setup>
import { apiSystemDepart, apiSystemRole, apiSystemUser,apiSystemCommon } from '@/api/system'
import { checkPassWord, isMobileNo, patternEmail } from '@/utils/common'
import { Base64 } from 'js-base64'

const show = defineModel('show', { type: Boolean, default: false })
const props=defineProps({
  data:null
})
const emits=defineEmits(['success'])

// 编辑admin 用户标识
const isEditAdmin=computed(()=>{
  return props.data&&props.data.SysUserName==='admin'
})

watch(
  ()=>show.value,
  (n)=>{
    if(n&&props.data){
      // console.log(props.data);
      formState=reactive({
        account: props.data.SysUserName,
        pwd: '',
        name: props.data.SysRealName,
        areacode: props.data.AreaCode,
        mobile: props.data.Phone,
        depart: props.data.SysDepartmentId,
        email: props.data.Email,
        role: props.data.SysRoleId,
        province: props.data.Province,
        city: props.data.City,
        status: props.data.IsEnabled
      })
    }else{
      formState=reactive({
        account: '',
        pwd: '',
        name: '',
        areacode: '86',
        mobile: '',
        depart: '',
        email: '',
        role: '',
        province: '',
        city: '',
        status: true
      })
    }
  }
)

const areaCodeOpts = ref([])
function getPhoneAreaCode(){
  apiSystemCommon.phoneAreaCode().then(res=>{
    if(res.Ret===200){
      areaCodeOpts.value=res.Data||[]
    }
  })
}
getPhoneAreaCode()


// 获取部门数据
const departArr = ref([])
async function getDepartList() {
  const res = await apiSystemDepart.departList()
  if (res.Ret !== 200) return
  const list = res.Data.List || []
  departArr.value = list
}
getDepartList()

// 获取角色
const roleArr = ref([])
async function getRoleList() {
  const res = await apiSystemRole.roleList()
  if (res.Ret !== 200) return
  const list = res.Data.List || []
  roleArr.value = list
}
getRoleList()

const formRules = {
  account: [{ required: true, message: '登录账号不能为空', trigger: 'blur' }],
  pwd: [{
    validator: (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      }
      if (!checkPassWord(value || '')) {
        callback(new Error('密码要求8位及以上，包含数字、大写字母、小写字母、特殊字符中的三个类型'))
      } else {
        callback()
      }
    }
  }],
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  mobile: [{
    validator: (rule, value, callback) => {
      if (value === '' && !formState.email) {
        callback(new Error('手机号码和邮箱至少填一个'));
      } else if (value && formState.areacode === '86' && !isMobileNo(value || '')) {
        callback(new Error('请输入正确的手机号格式'));
      } else if (formState.areacode !== '86' && isNaN(value?.trim())) {
        callback(new Error('请输入正确的手机号格式'));
      } else {
        callback();
      }
    }, trigger: 'blur'
  }],
  email: [{
    validator: (rule, value, callback) => {
      if (value === '' && !formState.mobile) {
        callback(new Error('手机号码和邮箱至少填一个'));
      } else if (value && !patternEmail.test(value)) {
        callback(new Error('请输入正确的邮箱格式'));
      } else {
        callback();
      }
    }, trigger: 'blur'
  }],
  depart: [{ required: true, message: '部门分组不能为空', trigger: 'change' }],
  role: [{ required: true, message: '角色不能为空', trigger: 'change' }],
}
const formRef = ref(null)
let formState = reactive({
  account: '',
  pwd: '',
  name: '',
  areacode: '86',
  mobile: '',
  depart: '',
  email: '',
  role: '',
  province: '',
  city: '',
  status: true
})
function selectRegion(data) {
  formState.province = data.province.value;
  formState.city = data.city.value == '市' ? '' : data.city.value;
}

async function handleSave() {
  await formRef.value.validate()
  let params = {
    sysusername: formState.account,
    password: Base64.encode(formState.pwd),
    realname: formState.name,
    phone: formState.mobile,
    areacode: formState.areacode,
    email: formState.email,
    Province: formState.province,
    City: formState.city,
    sysdepartmentid: formState.depart,
    sysroleid: formState.role,
    isenabled: formState.status
  }
  if(props.data){
    params.SysUserId=props.data.SysUserId
  }
  console.log(params);
  const res =props.data?await apiSystemUser.userEdit(params):await apiSystemUser.userAdd(params)
  if(res.Ret!==200) return
  ElMessage.success(props.data?'编辑成功':'添加成功');
  show.value=false
  emits('success')
}

</script>

<template>
  <el-dialog v-model="show" width="700" draggable>
    <template #header>
      <div style="display: flex; align-items: center">
        <el-icon size="20px">
          <i-ep-CirclePlus v-if="!props.data" />
          <i-ep-Edit v-else />
        </el-icon>
        <span>{{props.data?'编辑用户':'添加用户'}}</span>
      </div>
    </template>
    <el-form
      class="user-form-wrap"
      :model="formState"
      :rules="formRules"
      ref="formRef"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="account">
        <el-input
          v-model="formState.account"
          placeholder="建议使用邮箱前缀或者手机号码"
          clearable
          :disabled="isEditAdmin"
        />
      </el-form-item>
      <el-form-item label="登录密码" prop="pwd" v-if="!props.data&&!isEditAdmin">
        <el-input
          v-model.trim="formState.pwd"
          placeholder="6-12位数字与字母的组合"
          type="password"
          clearable
        />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="formState.name"
          placeholder="请输入用户名称"
          clearable
          :disabled="isEditAdmin"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile" class="mobile-input-item">
        <el-select
          v-model="formState.areacode"
          class="mobile-select"
          placeholder="请选择"
          style="width: 35%"
        >
          <el-option
            v-for="item in areaCodeOpts"
            :key="item.Value"
            :label="item.Name"
            :value="item.Value"
          />
        </el-select>
        <el-input
          v-model.trim="formState.mobile"
          placeholder="请输入手机号码"
          clearable
          class="mobile-input"
          style="width: 60%; margin-left: 5%"
        />
      </el-form-item>
      <el-form-item label="所属部门" prop="depart" v-if="!props.data&&!isEditAdmin">
        <el-cascader
          style="width: 100%"
          :options="departArr"
          :props="{
            value: 'SysDepartmentId',
            label: 'SysDepartmentName',
            children: 'Child',
            checkStrictly: true,
            emitPath:false
          }"
          v-model="formState.depart"
          placeholder="请选择部门分组"
          clearable
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formState.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="分配角色" prop="role">
        <el-select v-model="formState.role" placeholder="分配角色" :disabled="isEditAdmin">
          <el-option
            v-for="item in roleArr"
            :key="item.SysRoleId"
            :label="item.SysRoleName"
            :value="item.SysRoleId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工作地点" prop="city">
        <div style="width: 100%">
          <province-city-select
            :provinceInfo="formState.province"
            :cityInfo="formState.city"
            @selected="selectRegion"
          />
        </div>
      </el-form-item>
      <el-form-item label="状态" prop="status" v-if="!isEditAdmin">
        <el-radio-group v-model="formState.status">
          <el-radio :value="true">启用</el-radio>
          <el-radio :value="false">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div style="text-align: center">
      <el-button type="primary" size="large" @click="handleSave"
        >保存</el-button
      >
      <el-button type="primary" plain size="large" @click="show = false"
        >取消</el-button
      >
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped>
.user-form-wrap {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  .el-form-item {
    width: 46%;
  }
}
</style>