<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="realname">
        <el-input placeholder="请输入姓名" v-model="formParams.realname" />
      </el-form-item>
      <el-form-item label="角色" prop="roleIdList">
        <el-select clearable v-model="formParams.roleIdList" multiple v-if="isCanAddTenant && isSysTenant">
          <el-option v-for="item in roleData" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input v-else placeholder="租户管理员默认拥有全部角色权限" disabled />
      </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="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, watch } from 'vue';
  import { FormRules, ElMessage } from 'element-plus';
  import { userInfo } from '@/api/system/user';
  import { cloneDeep } from 'lodash-es';
  import { addTenantAdmin, AddTenantAdminProps, updateUser, addSingleUser } from '@/api/system/user-operate';
  import { EditType, OptionsProps, DisabledEnum } from './types';
  import { useTargetTenantIdSetting } from '@/utils/useTargetTenantIdSetting';
  import { ResultEnum } from '@/enums/httpEnum';

  const { isSysTenant } = useTargetTenantIdSetting();
  let rules: FormRules = {
    username: {
      required: true,
      message: '登录账号不能为空',
      trigger: 'blur',
    },
    realname: {
      required: true,
      message: '姓名不能为空',
      trigger: 'blur',
    },
    roleIdList: {
      required: true,
      message: '请选择角色',
      trigger: 'change',
    },
    password: {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    },
    passwordRe: {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    },
  };

  const emit = defineEmits(['change']);
  const props = withDefaults(
    defineProps<{
      title: string;
      width: number;
      editType: EditType;
      roleData: OptionsProps[];
      isCanAddTenant: boolean;
      isSysTenant: boolean;
      departmentList: OptionsProps[];
    }>(),
    {
      title: '添加用户',
      width: 450,
    },
  );

  const defaultValueRef = () => ({
    username: '',
    isDisabled: true,
    realname: '',
    roleIdList: [],
    password: '',
    passwordRe: '',
  });
  const message = ElMessage;
  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);
  const formParams = ref<AddTenantAdminProps>(defaultValueRef());

  async function openDrawer(userId?) {
    if (userId) {
      formParams.value.userId = userId;
      getInfo();
      return;
    }
    isDrawer.value = true;
  }

  const isAddUser = computed(() => {
    return props.editType === EditType.create;
  });

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

  function formSubmit() {
    formRef.value.validate((valid) => {
      if (!valid) {
        message.error('请填写完整信息');
        return;
      }

      // 克隆
      const params = cloneDeep(formParams.value);
      if (params.password != params.passwordRe) {
        return message.error('两次密码不一致');
      }
      if (isAddUser.value) {
        formParams.value.isDisabled ? (params.isDisabled = DisabledEnum.NO) : (params.isDisabled = DisabledEnum.YES);
        if (!isSysTenant) {
          addTenantAdmin(params).then((res) => {
            message.success('添加管理员账户成功');
            emit('change');
            handleReset();
            closeDrawer();
          });
        } else {
          addSingleUser(params)
            .then((res) => {
              if (res.code !== ResultEnum.SUCCESS) {
                return Promise.reject(res.msg);
              }
              emit('change');
              handleReset();
              closeDrawer();
              ElMessage.success('添加成功');
            })
            .catch((error) => {
              ElMessage.error(error);
            });
        }
      } else {
        formParams.value.isDisabled ? (params.isDisabled = DisabledEnum.NO) : (params.isDisabled = DisabledEnum.YES);
        updateUser(params)
          .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.deptId = res.deptId;
      formParams.value.passwordRe = res.password;
      formParams.value.isDisabled = res.isDisabled === DisabledEnum.NO ? true : false;
      isDrawer.value = true;
    });
  }

  watch(
    () => props,
    () => {
      if (props.isCanAddTenant && !props.isSysTenant) {
        rules!.roleIdList!.required = false;
      }
    },
    {
      immediate: true,
    },
  );

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
<style scoped>
  .text-mode {
    cursor: pointer;
  }
</style>
