<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-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 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="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 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 { useDictionary } from '@/hooks/web/useDictionary';
  import { userInfo } from '@/api/system/user';
  import { postList } from '@/api/common/index';
  import { cloneDeep } from 'lodash-es';
  import { UserType, addSingleUser, updateUser } from '@/api/system/user-operate';
  import useSelectContent from './hooks/use-user-para';

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

  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',
    },
    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 = defineProps({
    title: {
      type: String,
      default: '添加用户',
    },
    width: {
      type: Number,
      default: 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 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(username?) {
    const postListRes = await postList();
    postDataList.value = postListRes;
    if (username) {
      formParams.value.username = username;
      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);

      // 处理部门
      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,
          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,
        };
        addSingleUser(addData)
          .then((res) => {
            if (res.code !== 200) {
              return Promise.reject(res.msg);
            }
            emit('change');
            handleReset();
            closeDrawer();
            ElMessage.success('添加成功');
          })
          .catch((error) => {
            ElMessage.error(error);
          });
      } 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((res) => {
            if (res.code !== 200) {
              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: formParams.value.username }).then((res) => {
      const params = {
        userId: formParams.value.username,
        deleteStatus: parseInt(res.deleteStatus),
        isEnable: res.isEnable,
        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>
