<template>
   <div class="app-container">
      <els-table
        ref="userTable"
        :btnList="btnList"
        :columns="columns"
        :tableData="tableData"
        :searchList="searchList"
        @getTableData="getTableData"
        :pageSet="pageSet"
        @handleAdd="handleAdd"
        :option="tableOption"
        :tableLoading="loading"
        @formChange="tableSearchChange"
      ></els-table>
      <!-- 添加或修改用户配置对话框 -->
      <el-dialog :title="title" v-model="open" width="650px" append-to-body destroy-on-close>
        <els-form
          ref="userForm"
          :fieldList="fieldList"
          :formOption="formOption"
          :formLoading="formLoading"
          @cancel="cancel"
          @ok="submit"
          :form="formData"
          @formChange="tableSearchChange"
        ></els-form>
      </el-dialog>
   </div>
</template>

<script setup name="User">
import { init } from './index.jsx'
import { listDept } from "@/api/system/dept";
import { changeUserStatus, listUser, resetUserPwd, delUser, getUser, updateUser, addUser, deptTreeSelect, getByDeptId, userTeamlist } from "@/api/system/user";
import { nextTick } from 'vue';

const { proxy } = getCurrentInstance();

const deptList = ref([])
const deptTemp = ref([])
const postOptions = ref([])
const teamList = ref([])
const roleOptions = ref([])
const loading = ref(false)
const page = ref({ pageSize:10, pageNum:1 }) // 初始化查询分页数据
const tableData = ref([])
const title = ref('')
const open = ref(false)
const initPassword = ref('')
const formLoading = ref(false)
const formData = ref({})
// 获取部门数据
const getDept = () => {
  listDept().then(res => {
    if(res.code === 200){
      deptList.value = proxy.handleTree(res.data, "deptId")
      deptTemp.value = res.data
    }else{
      proxy.$modal.msgError(res.msg);
    }
  }).catch(err => console.log(err))
}
// 根据部门获取岗位和班组和角色数据
const getDeptList = (id='') => {
  getByDeptId(id).then(res => {
    let data = []
    res.data && res.data.forEach(item => {
      data.push({ label: item.postName, value: item.postId })
    })
    postOptions.value = data
  }).catch(err => console.log(err))
  userTeamlist(id).then(res => {
    let data = []
    res.data && res.data.forEach(item => {
      data.push({ label: item.teamName, value: item.id })
    })
    teamList.value = data
  }).catch(err => console.log(err))
}
const getUserData = () => {
  getUser().then(res => {
    let data = []
    res.data.roles && res.data.roles.forEach(item => {
      data.push({ label: item.roleName, value: item.roleId })
    })
    roleOptions.value = data
  });
}
const userTable = ref(null)
// 部门选择重新获取岗位及班组数据
const tableSearchChange = (val) => {
  if (val.field === 'deptId') {
    getDeptList(val.val)
    nextTick(() => {
      proxy.bus.emit('change',{type:'setValue', a:'postIds', b:[]})
      proxy.bus.emit('change',{type:'setValue', a:'teamId', b:''})
    })
  }
} 
/** 查询用户列表 */
const getList = (val) => {
  loading.value = true;
  listUser(val).then(res => {
    loading.value = false;
    pageSet.value.total = res.total;
    let data = []
    res.rows.forEach(item => {
      data.push({ ...item, deptName: item.dept.deptName})
    })
    tableData.value = data;
  }).catch((err) => {loading.value = false;})
};
// 分页及筛选条件回调
const getTableData = (searchVal) => {
  if(!searchVal.deptId) {
    getDept()
    getDeptList()
  }
  getList(searchVal)
}

const userForm = ref(null)
/** 新增按钮操作 */
const handleAdd = () => {
  open.value = true;
  title.value = "员工档案新建";
  // formLoading.value = true
  formData.value = {}
  nextTick(()=>{
    userForm.value.setValue('password', initPassword.value)
    userForm.value.hidden('password', false)
    userForm.value.disabled('userName', false)
  })
  // reset();
  // postOptions.value = []
  // form.value.password = initPassword.value;
  // getUser().then(response => {
  //   postOptions.value = response.data.posts;
  //   roleOptions.value = response.data.roles;
  //   open.value = true;
  //   title.value = "添加用户";
  //   form.value.password = initPassword.value;
  // });
};
 /** 修改按钮操作 */
 const handleUpdate = (row) => {
  // console.log(row)
  open.value = true;
  title.value = "员工档案修改";
  // formLoading.value = true
  formData.value = { ...row }
  getDeptList(row.deptId)
  nextTick(()=>{
    userForm.value.hidden('password', true)
    userForm.value.disabled('userName', true)
  })
  // reset();
  // const userId = row.userId || ids.value;
  // getDeptList(row.deptId)
  // getUser(userId).then(response => {
  //   form.value = response.data.user;
  //   // postOptions.value = response.data.posts;
  //   // roleOptions.value = response.data.roles;
  //   form.value.postIds = response.data.postIds;
  //   form.value.roleIds = response.data.roleIds;
  //   open.value = true;
  //   title.value = "员工档案修改";
  //   form.password = "";
  // });
};
/** 取消按钮 */
const cancel = () => {
  open.value = false;
  getDept()
  getDeptList()
};
/** 提交按钮 */
const submit = (val) => {
  // console.log(val)
  formLoading.value = true
  if (val.value.userId != undefined) {
    updateUser(val.value).then(response => {
      proxy.$modal.msgSuccess("修改成功");
      open.value = false;
      getList(page.value);
      formLoading.value = false
    }).catch((err) => {formLoading.value = false})
  } else {
    addUser(val.value).then(response => {
      proxy.$modal.msgSuccess("新增成功");
      open.value = false;
      getList(page.value);
      formLoading.value = false
    }).catch((err) => {formLoading.value = false})
  }
};
/** 删除按钮操作 */
const handleDelete = (row) => {
  const userIds = row.userId || ids.value;
  proxy.$modal.confirm('是否确认删除“' + row.nickName + '”用户吗？').then(function () {
    return delUser(userIds);
  }).then(() => {
    getList(page.value);
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};
/** 用户状态修改  */
const handleStatusChange = (row) => {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要' + text + '“' + row.userName + '”用户吗？' + `${row.status === "0" ? '启用后允许正常登录系统。' : '停用后将无法登录系统。'}`).then(function () {
    return changeUserStatus(row.userId, row.status);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0";
  });
};


const ruleFormRef = ref(null)
/** 重置密码按钮操作 */
const handleResetPwd = (row) => {
  // nextTick(()=>{
  //   console.log(ruleFormRef)
  // })
  proxy.$prompt('请输入"' + row.userName + '"的新密码', "重置密码", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    inputPattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,20}$/,
    inputErrorMessage: "用户密码长度至少6位，并且须包含至少一个字母和一个数字，不支持特殊符号和空格！",
  }).then(({ value }) => {
    resetUserPwd(row.userId, value).then(response => {
      proxy.$modal.msgSuccess("修改成功，新密码是：" + value);
    });
  }).catch(() => {});
};

proxy.getConfigKey("sys.user.initPassword").then(res => {
  initPassword.value = res.msg;
});
const {
  searchList,
  btnList,
  columns,
  pageSet,
  tableOption,
  fieldList,
  formOption,
  newPassWord
} = init(proxy, {
  deptList,
  postOptions,
  teamList,
  roleOptions,
  handleStatusChange,
  handleUpdate,
  handleResetPwd,
  handleDelete,
})
getDept()
getDeptList()
getUserData()
getList(page.value)
</script>
