<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" />
      </el-form-item>
      <el-form-item label="选择租户" prop="tenantId">
        <el-select v-model="formParams.tenantId" placeholder="请选择租户" class="protocal-select">
          <el-option
            v-for="item in tenantList"
            :key="item.tenantId"
            :label="item.tenantName"
            :value="item.tenantId"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="所属部门" prop="deptId">
        <el-select v-model="formParams.deptId" placeholder="请选择组织" class="protocal-select">
          <el-option
            v-for="item in departmentList"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          />
        </el-select>
      </el-form-item> -->

      <!-- <el-form-item label="角色" prop="roleIds">
        <el-select clearable v-model="formParams.roleIds" multiple>
          <el-option
            v-for="item in roleList!"
            :key="item.roleId"
            :label="item.roleName"
            :value="item.roleId"
          />
        </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="staffNo">
        <el-input placeholder="请输入工号" v-model="formParams.staffNo" />
      </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="passwordRe">
        <el-input
          type="password"
          show-password-on="mousedown"
          placeholder="请输入密码"
          v-model="formParams.passwordRe"
        />
      </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 } from 'vue';
  import { FormRules, ElMessage } from 'element-plus';
  import { useDictionary } from '@/hooks/web/useDictionary';
  import { userInfo } from '@/api/system/user';
  import { postList } from '@/api/common/index';
  import { cloneDeep } from 'lodash-es';
  import { UserType, addAdminUser, addSingleUser, updateUser } from '@/api/system/user-operate';
  import useSelectContent from './hooks/use-user-para';
  import { EditType } from './types';
  import { useTenantList } from './useTenantList';
  import { computed } from 'vue';

  const selectContent = useSelectContent();
  const { roleList, departmentList } = selectContent;

  const rules: FormRules = {
    username: {
      required: true,
      message: '登录账号不能为空',
      trigger: 'blur',
    },
    tenantId: {
      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',
    },
    nickname: {
      required: true,
      message: '用户名不能为空',
      trigger: 'blur',
    },
    mobile: {
      required: true,
      message: '手机不能为空',
      trigger: 'blur',
    },
    staffNo: {
      required: true,
      message: '工号不能为空',
      trigger: 'blur',
    },
  };

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

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

  const props = withDefaults(defineProps<{ title: string; width: number; editType: EditType }>(), {
    title: '添加用户',
    width: 450,
  });

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

  const { data: tenantList, loading } = useTenantList();
  const message = ElMessage;
  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);

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

  async function openDrawer(username?) {
    const postListRes = await postList();
    postDataList.value = postListRes;
    if (username) {
      formParams.value.username = username;
      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;
      }
      console.log('formParams', formParams.value);
      // 克隆
      const params = cloneDeep(formParams.value);

      // 处理部门
      console.log('params', params);

      if (params.deptId) {
        params.deptId = params.deptId;
      }
      if (params.password != params.passwordRe) {
        return message.error('两次密码不一致');
      }
      // const msg = params.username ? '编辑成功' : '添加成功';
      if (isAddUser.value) {
        const addData = {
          password: formParams.value.password!,
          tenantId: formParams.value.tenantId!,
          deptId: formParams.value.deptId!,
          username: formParams.value.username!,
          staffNo: formParams.value.staffNo,
          mobile: formParams.value.mobile,
          isEnable: formParams.value.isEnable,
          nickname: formParams.value.nickname!,
          roleIds: formParams.value.roleIds,
        };
        addAdminUser(addData).then((res) => {
          console.log('添加账户成功', res);
          message.success('添加管理员账户成功');
          emit('change');
          handleReset();
          closeDrawer();
        });
        // addSingleUser(addData).then(() => {
        //   emit('change');
        //   handleReset();
        //   closeDrawer();
        // });
      } else {
        /** 编辑的暂不添加 */
        const updateData = {
          userId: params.userId,
          // password: formParams.value.password,
          deptId: formParams.value.deptId,
          username: formParams.value.username,
          staffNo: formParams.value.staffNo,
          mobile: formParams.value.mobile,
          isEnable: formParams.value.isEnable,
          nickname: formParams.value.nickname,
          roleIds: formParams.value.roleIds,
          deleteStatus: '1',
        };
        // updateUser(updateData).then(() => {
        //   emit('change');
        //   handleReset();
        //   closeDrawer();
        // });
      }
    });
  }

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

  function getInfo() {
    userInfo({ userId: formParams.value.username }).then((res) => {
      const params = {
        userId: formParams.value.username,
        deleteStatus: parseInt(res.deleteStatus),
        email: res.email,
        mobile: res.mobile,
        nickname: res.nickname,
        password: res.password,
        passwordRe: res.password,
        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,
        staffNo: res.staffNo,
      };
      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>
