<template>
  <el-drawer v-model="isDrawer" :size="width" :title="title" @close="handleReset">
    <el-form
      :model="formParams"
      :rules="rules"
      ref="formRef"
      label-placement="left"
      :label-width="80"
    >
      <el-form-item label="登录账号" prop="username">
        <el-input
          placeholder="请输入登录账号"
          v-model="formParams.username"
          :disabled="formParams.userId ? true : false"
        />
      </el-form-item>
      <el-form-item label="所属部门" prop="deptId">
        <el-tree-select
          :data="deptList"
          clearable
          check-strictly
          v-model="formParams.deptId"
          placeholder="请选择部门"
        />
      </el-form-item>
      <el-form-item label="密码" :prop="!formParams.userId ? 'password' : ''">
        <el-input
          type="password"
          show-password-on="mousedown"
          placeholder="请输入密码"
          v-model="formParams.password"
        />
      </el-form-item>
      <el-form-item label="确认密码" :prop="!formParams.userId ? 'passwordRe' : ''">
        <el-input
          type="password"
          show-password-on="mousedown"
          placeholder="请输入密码"
          v-model="formParams.passwordRe"
        />
      </el-form-item>

      <el-form-item label="角色" prop="roleIds">
        <el-select clearable v-model="formParams.roleIds" multiple>
          <el-option
            v-for="(item, index) in getRoleList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户名" prop="nickname">
        <el-input placeholder="请输入用户名" v-model="formParams.nickname" />
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input placeholder="请输入手机" v-model="formParams.mobile" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input placeholder="请输入邮箱" v-model="formParams.email" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="formParams.sex" name="sexGroup">
          <el-radio v-for="item in sexList" :key="item.dictValue" :label="item.dictLabel">
            {{ item.dictLabel }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="所在岗位" prop="postId">
        <el-select clearable multiple v-model="formParams.postId" placeholder="请选择所在岗位">
          <el-option
            v-for="(item, index) in postDataList"
            :key="index"
            :label="item.postName"
            :value="item.postId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="个人介绍" prop="remark">
        <el-input type="textarea" placeholder="请输入个人介绍" v-model="formParams.remark" />
      </el-form-item>
      <el-form-item label="是否启用" prop="isEnable">
        <el-switch v-model="formParams.isEnable" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-space>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" :loading="subLoading" @click="formSubmit">提交</el-button>
      </el-space>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
  import { ref, onMounted, computed } from 'vue';
  import { FormRules, ElMessage } from 'element-plus';
  import type { formParamsType } from './types';
  import { useDictionary } from '@/hooks/web/useDictionary';

  import { addUsur, editUsur, userInfo } from '@/api/system/user';
  import { postList } from '@/api/common/index';
  import { deptTreeList } from '@/api/auth/dept';
  import { cloneDeep } from 'lodash-es';
  import { replaceParams } from '@/utils/helper/treeHelper';

  const rules: FormRules = {
    username: {
      required: true,
      message: '登录账号不能为空',
      trigger: 'blur',
    },
    deptId: {
      required: true,
      message: '部门不能为空',
      trigger: 'change',
      type: 'number',
    },
    roleIds: {
      required: true,
      message: '角色不能为空',
      trigger: 'change',
      type: 'array',
    },
    password: {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    },
    passwordRe: {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    },
  };

  interface PostOption {
    postName: string;
    postId: number;
  }

  const emit = defineEmits(['change']);
  const { getDictTypeList } = useDictionary();

  const props = defineProps({
    title: {
      type: String,
      default: '添加会员',
    },
    width: {
      type: Number,
      default: 450,
    },
    roleList: {
      type: Array,
    },
  });

  const sexList = ref<any[]>();
  const deptList = ref<any[]>();
  const postDataList = ref<PostOption[]>([]);
  const defaultValueRef = () => ({
    userId: null,
    roleIds: [],
    isEnable: true,
    deptId: null,
    email: '',
    mobile: '',
    nickname: '',
    password: '',
    passwordRe: '',
    remark: '',
    sex: '',
    username: '',
    postId: [],
  });

  const getRoleList = computed(() => {
    return props.roleList as SelectOption[];
  });

  const message = ElMessage;
  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);

  const formParams = ref<formParamsType>(defaultValueRef());

  async function openDrawer(userId?) {
    const deptResList = await deptTreeList();
    deptList.value = replaceParams(deptResList, 'deptName', 'deptId');
    const postListRes = await postList();
    postDataList.value = postListRes;
    if (userId) {
      formParams.value.userId = userId;
      getInfo();
      return;
    }
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  function formSubmit() {
    formRef.value.validate((valid) => {
      if (!valid) {
        return message.error('请填写完整信息');
      }
      // 克隆
      const params = cloneDeep(formParams.value);
      // 处理岗位
      if (params.postId && params.postId.length) {
        params.postId = params.postId.join(',');
      } else {
        params.postId = '';
      }
      // 处理部门
      if (params.deptId) {
        params.deptId = params.deptId + '';
      }
      if (params.password != params.passwordRe) {
        return message.error('两次密码不一致');
      }
      const msg = params.userId ? '编辑成功' : '添加成功';
      if (params.userId) {
        editUsur(params).then((_) => {
          message.success(msg);
          emit('change');
          handleReset();
          closeDrawer();
        });
      } else {
        addUsur(params).then((_) => {
          message.success(msg);
          emit('change');
          handleReset();
          closeDrawer();
        });
      }
    });
  }

  function handleReset() {
    formRef.value.resetFields();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
  }

  function getInfo() {
    userInfo({ userId: formParams.value.userId }).then((res) => {
      const params = {
        userId: formParams.value.userId,
        deleteStatus: parseInt(res.deleteStatus),
        email: res.email,
        mobile: res.mobile,
        nickname: res.nickname,
        password: '',
        passwordRe: '',
        remark: res.remark,
        sex: res.sex,
        username: res.username,
        roleIds: res.roleIds,
        postId: res.postId ? res.postId.split(',').map(Number) : null,
        deptId: res.deptId || null,
      };
      formParams.value = Object.assign(formParams.value, params);
      isDrawer.value = true;
    });
  }

  onMounted(async () => {
    const list = await getDictTypeList({ dictType: 'sys_user_sex' });
    sexList.value = list;
  });

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
