<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="staffNo">
        <el-input placeholder="请输入工号" v-model="formParams.staffNo" v-if="staffNoHtmlType === 'INPUT'" />
        <el-tree-select
          v-model="formParams.staffNo"
          check-strictly
          placeholder="请选择工号"
          class="protocal-select"
          filterable
          remote
          clearable
          :loading="loading"
          :data="staffNoOptions"
          :render-after-expand="false"
          :default-expand-all="true"
          :remote-method="debouncedRemoteMethod"
          @clear="handleClear"
          @change="handleChange"
          v-else
        />
        <el-text class="mx-1 text-mode" type="primary" @click="handleChangeStaff">{{
          `工号${staffNoHtmlType === 'INPUT' ? '选择' : '输入'}方式`
        }}</el-text>
      </el-form-item>
      <el-form-item label="所属部门" prop="deptId">
        <el-tree-select
          v-model="formParams.deptId"
          :data="departmentArr"
          :render-after-expand="false"
          :default-expand-all="true"
          check-strictly
          placeholder="请选择所属部门"
          class="protocal-select"
        />
      </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="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="mobile">
        <el-input placeholder="请输入手机" v-model="formParams.mobile" />
      </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, queryOrganizationUserTree } from '@/api/system/user';
  import { cloneDeep } from 'lodash-es';
  import { UserType, addSingleUser, updateUser } from '@/api/system/user-operate';
  import { OptionsProps, DisabledEnum, OrganizationUserTree } from './types';
  import { ResultEnum } from '@/enums/httpEnum';
  import { debounce } from 'lodash-es';
  import {
    findUserByWorkNo,
    findOrgCodeByWorkNo,
    transformTreeData,
    TransformedTreeNode,
    removeParentheses,
  } from '@/utils/findUserByWorkNo';

  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 === '添加用户';
  });

  const loading = ref(false);
  const staffNoOptions = ref<TransformedTreeNode[]>([]);
  const OrganizationSourceData = ref<OrganizationUserTree[]>([]);
  const departmentArr = ref<OptionsProps[]>([]);

  const remoteMethod = (query: string) => {
    if (query) {
      loading.value = true;
      queryOrganizationUserTree(Number(query)).then((res) => {
        if (res) {
          loading.value = false;
          staffNoOptions.value = transformTreeData(res, true);
           /* 保存原始数据，用于选中后将数据返显到表单 */
          OrganizationSourceData.value = res;
          /* 选中数据后将部门设置为当前数据的部门 */
          departmentArr.value = transformTreeData(OrganizationSourceData.value, false);
        } 

        if (res.length === 0) {
          departmentArr.value = props.departmentList;
        }
      });
    } else {
      staffNoOptions.value = [];
    }
  };
  /* 防抖 */
  const debouncedRemoteMethod = debounce(remoteMethod, 1000);

  type STAFFNO_HTML_TYPE = 'INPUT' | 'SELECT';
  const staffNoHtmlType = ref<STAFFNO_HTML_TYPE>('SELECT');
  const handleChangeStaff = () => {
    staffNoHtmlType.value = staffNoHtmlType.value === 'INPUT' ? 'SELECT' : 'INPUT';
    if (staffNoHtmlType.value === 'INPUT') {
       departmentArr.value = props.departmentList;
    }
  };

  const handleClear = () => {
    formRef.value.resetFields();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
  };

  const handleChange = (value) => {
    /* 将选中的数据返显到表单 */
    const findUser = findUserByWorkNo(OrganizationSourceData.value, value);
    if (findUser) {
      formParams.value.realname = findUser.appAccountAccountName;
      formParams.value.staffNo = findUser.idtUserWorkNo;
      formParams.value.username = findUser.idtUserWorkNo;
      formParams.value.roleIdList = JSON.parse(findUser.useTypes);
      formParams.value.mobile = findUser.idtUserMobile;
      formParams.value.deptId = findOrgCodeByWorkNo(OrganizationSourceData.value, value);
    }
  };

  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('两次密码不一致');
      }
      params.staffNo = removeParentheses(params.staffNo);
      formParams.value.isDisabled ? (params.isDisabled = DisabledEnum.NO) : (params.isDisabled = DisabledEnum.YES);
      if (isAddUser.value) {
        addSingleUser(params)
          .then((res) => {
            if (res.code !== ResultEnum.SUCCESS) {
              return Promise.reject(res.message);
            }
            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.message);
            }
            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;
      formParams.value.isDisabled = res.isDisabled === DisabledEnum.NO ? true : false;
      isDrawer.value = true;
      remoteMethod(res.username)
    });
  }

   watch(
    () => props.departmentList,
    (newVal) => {
      departmentArr.value = newVal;
    },
    {
      immediate: true,
    },
  );


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