<template>
  <el-drawer v-model="isDrawer" :size="width" :title="props.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="!isAddUser"
        />
      </el-form-item>
      <el-form-item label="所属部门" prop="deptId">
        <el-tree-select
          v-model="formParams.deptId"
          :data="props.departmentList"
          :render-after-expand="false"
          :default-expand-all="true"
          check-strictly
          placeholder="请选择所属组织"
          class="protocal-select"
        />
      </el-form-item>
      <el-form-item v-if="isAddUser" label="密码" prop="password">
        <el-input
          type="password"
          show-password-on="mousedown"
          placeholder="请输入密码"
          v-model="formParams.password"
        />
      </el-form-item>
      <el-form-item
        v-if="isAddUser"
        label="确认密码"
        :prop="!formParams.username ? 'passwordRe' : ''"
      >
        <el-input
          type="password"
          show-password-on="mousedown"
          placeholder="请输入密码"
          v-model="formParams.passwordRe"
        />
      </el-form-item>

      <el-form-item label="角色" prop="roleIdList">
        <el-select clearable v-model="formParams.roleIdList" multiple>
          <el-option
            v-for="item in roleData"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="realname">
        <el-input placeholder="请输入姓名" v-model="formParams.realname" />
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input placeholder="请输入手机" v-model="formParams.mobile" />
      </el-form-item>
      <el-form-item label="工号" prop="staffNo">
        <el-input placeholder="请输入工号" v-model="formParams.staffNo" />
      </el-form-item>
      <el-form-item label="是否启用" prop="isDisabled">
        <el-switch v-model="formParams.isDisabled" />
      </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, computed } from 'vue';
  import { FormRules, ElMessage } from 'element-plus';
  import { userInfo } from '@/api/system/user';
  import { cloneDeep } from 'lodash-es';
  import { UserType, addSingleUser, updateUser } from '@/api/system/user-operate';
  import { OptionsProps } from './types';
  import { ResultEnum } from '@/enums/httpEnum';

    const rules: FormRules = {
      username: {
        required: true,
        message: '登录账号不能为空',
        trigger: 'blur',
      },
      deptId: {
        required: true,
        message: '部门不能为空',
        trigger: 'change',
        type: 'number',
      },
      roleIdList: {
        required: true,
        message: '角色不能为空',
        trigger: 'change',
        type: 'array',
      },
      password: {
        required: true,
        message: '密码不能为空',
        trigger: 'blur',
      },
      passwordRe: {
        required: true,
        message: '密码不能为空',
        trigger: 'blur',
      },
      realname: {
        required: true,
        message: '用户名不能为空',
        trigger: 'blur',
      },
      mobile: {
        required: true,
        message: '手机不能为空',
        trigger: 'blur',
      },
      staffNo: {
        required: true,
        message: '工号不能为空',
        trigger: 'blur',
      },
    };
    const emit = defineEmits(['change']);

  const props = withDefaults(defineProps
  <{ title: string; width: number; departmentList: OptionsProps[], roleData: OptionsProps[] }>(),
      {
        title: '添加用户',
        width: 450,
      });
    const defaultValueRef = () => ({
      password: '',
      passwordRe: '',
      deptId: null,
      username: '',
      staffNo: '',
      mobile: '',
      isDisabled: true,
      realname: '',
      roleIdList: [],
    });

    const message = ElMessage;
    const formRef: any = ref(null);
    const isDrawer = ref(false);
    const subLoading = ref(false);
    const formParams = ref<UserType>(defaultValueRef());
    const isAddUser = computed(() => {
      return props.title === '添加用户';
    });

    async function openDrawer(userId?) {
      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.deptId) {
          params.deptId = params.deptId;
        }
        if (params.password != params.passwordRe) {
          return message.error('两次密码不一致');
        }
        if (isAddUser.value) {
          addSingleUser(formParams.value)
            .then((res) => {
              if (res.code !== ResultEnum.SUCCESS) {
                return Promise.reject(res.msg);
              }
              emit('change');
              handleReset();
              closeDrawer();
              ElMessage.success('添加成功');
            })
            .catch((error) => {
              ElMessage.error(error);
            });
        } else {
          updateUser(formParams.value)
            .then((res) => {
              if (res.code !== ResultEnum.SUCCESS) {
                return Promise.reject(res.msg);
              }
              emit('change');
              handleReset();
              closeDrawer();
              ElMessage.success('修改成功');
            })
            .catch((error) => {
              ElMessage.error(error);
            });
        }
      });
    }

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

    function getInfo() {
      userInfo({ userId: Number(formParams.value.userId)}).then((res) => {
        Object.entries(res).forEach(([key, value]) => {
          formParams.value[key] = value
        })
        formParams.value.roleIdList = res.roleIds;
        formParams.value.passwordRe = res.password;
        isDrawer.value = true;
      });
    }
   
    defineExpose({
      openDrawer,
      closeDrawer,
    });
</script>
