<script setup lang="ts" name="User">
import apis from "@/api"
import type { VbFormItem } from "@/components/form/models"
import AuthRole from "./_authRole.vue"
import { permissionNames } from "@/core/services/PermissionNames"
import message from "@/core/utils/message"
import { download } from "@/core/services/RequestService"
const deptTreeRef = ref()
const deptOptions = ref<any>()
function loadDept() {
  apis.system.userApi.deptTreeSelect().then((res) => {
    deptOptions.value = res.data
  })
}

const tableRef = ref()
const tableOpts = reactive({
  permission: permissionNames.SystemUser,
  columns: [
    { field: "userId", name: `用户编号`, width: 85 },
    { field: "userName", name: `用户名称` },
    { field: "nickName", name: `用户昵称` },
    { field: "deptName", name: `部门` },
    { field: "phonenumber", name: `手机号码` },
    { field: "status", name: `状态` },
    { field: "createTime", name: `创建时间` },
    { field: "actions", name: `操作` },
  ],
  queryParams: {
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined,
    dateRange: [],
  },
  searchFormItems: [
    {
      field: "userName",
      label: "用户名称",
      placeholder: "请输入用户名称",
      required: false,
      component: "i",
      listeners: {
        keyup: (e: KeyboardEvent) => {
          if (e.code == "Enter") {
            handleQuery()
          }
        },
      },
      span: 4,
    },
    {
      field: "phonenumber",
      label: "手机号码",
      placeholder: "请输入手机号码",
      required: false,
      component: "I",
      listeners: {
        keyup: (e: KeyboardEvent) => {
          if (e.code == "Enter") {
            handleQuery()
          }
        },
      },
      span: 4,
    },
    {
      field: "status",
      label: "用户状态",
      required: false,
      component: "Dict",
      span: 5,
      props: {
        placeholder: "请选择用户状态",
        dictType: "sys_normal_disable",
      },
    },
    {
      field: "dateRange",
      label: "创建时间",
      placeholder: "请选择创建时间",
      required: false,
      component: "d",
      span: 6,
      props: {
        placeholder: "请选择创建时间",
        valueFormat: "YYYY-MM-DD",
        type: "daterange",
        rangeSeparator: "-",
        startPlaceholder: "开始日期",
        endPlaceholder: "结束日期",
      },
      listeners: {
        change: (v: any) => {
          queryParams.value.dateRange = v
        },
      },
    },
  ],
  handleFuns: {
    handleCreate,
    handleUpdate: () => {
      const row = tableRef.value.getSelected()
      handleUpdate(row)
    },
    handleDelete: () => {
      const rows = tableRef.value.getSelecteds()
      handleDelete(rows)
    },
    handleImport,
    handleExport,
  },
})
const { permission, columns, queryParams, searchFormItems, handleFuns } = toRefs(tableOpts)
function handleQuery() {
  addDateRange(queryParams.value, queryParams.value.dateRange)
  tableRef.value?.search()
}
function resetQuery() {
  queryParams.value.dateRange = []
  addDateRange(queryParams.value, queryParams.value.dateRange)
  queryParams.value.deptId = undefined
  deptTreeRef.value.setCurrentKey(null)
}

const userPosts = ref([])
const userRoles = ref([])
const modalRef = ref()
const modalOpts = reactive({
  title: "用户",
  formItems: [
    {
      field: "nickName",
      label: "用户昵称",
      placeholder: "请输入用户昵称",
      required: true,
      component: "i",
      span: 12,
    },
    {
      field: "deptId",
      label: "归属部门",
      class: "w-100",
      required: true,
      data: () => deptOptions.value,
      component: "vst",
      props: {
        //dataFun: loadDept,
        placeholder: "请选择归属部门",
      },
      span: 12,
    },
    {
      field: "phonenumber",
      label: "手机号码",
      placeholder: "请输入手机号码",
      required: true,
      component: "i",
      props: {
        maxlength: 11,
      },
      span: 12,
    },
    {
      field: "email",
      label: "邮箱",
      placeholder: "请输入邮箱",
      required: true,
      component: "i",
      rules: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
      props: {
        maxlength: 11,
      },
      span: 12,
    },
    {
      field: "userName",
      label: "用户名称",
      placeholder: "请输入用户名称",
      required: true,
      rules: [{ min: 2, max: 20, message: "用户名称长度必须介于 2 和 20 之间", trigger: "blur" }],
      span: 12,
    },
    {
      field: "password",
      label: "用户密码",
      type: "password",
      placeholder: "请输入用户密码",
      required: false,
      rules: [{ min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }],
      span: 12,
    },
    {
      field: "sex",
      label: "用户性别",
      class: "w-100",
      component: "dict",
      props: {
        placeholder: "请选择用户性别",
        dictType: "sys_user_sex",
      },
      span: 12,
    },
    {
      field: "status",
      label: "用户状态",
      class: "w-100",
      component: "dict",
      props: {
        placeholder: "请选择用户状态",
        dictType: "sys_normal_disable",
      },
      span: 12,
    },
    {
      field: "postIds",
      label: "用户岗位",
      class: "w-100",
      component: "vs",
      data: () => userPosts.value,
      placeholder: "请选择用户岗位",
      span: 12,
      props: {
        //multiple: true,
      },
    },
    {
      field: "roleIds",
      //id: () => role_id.value,
      label: "用户角色",
      class: "w-100",
      placeholder: "请选择用户角色",
      data: () => userRoles.value,
      component: "vs",
      props: {
        //dataFun: loadUserRole,
        multiple: true,
      },
      span: 12,
    },
    {
      field: "remark",
      label: "备注",
      type: "textarea",
      placeholder: "请输入备注内容",
      required: false,
      component: "i",
      span: 24,
    },
  ],
  emptyFormData: {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: "0",
    status: "0",
    remark: undefined,
    postIds: [],
    roleIds: [],
  },
})
const { title: modalTitle, emptyFormData, formItems } = toRefs(modalOpts)
const form = ref(emptyFormData)
function reset() {
  form.value = emptyFormData.value
}
const initPassword = ref(undefined)
function handleCreate() {
  console.log("C")
  modalTitle.value = "新增用户"
  reset()
  apis.system.userApi.getUser().then((res: any) => {
    setOptions(res)
    form.value.password = initPassword.value
    modalRef.value.show()
  })
}
function handleUpdate(row: any) {
  modalTitle.value = "编辑用户"
  //row = row ||
  const userId = row.userId
  console.log("U", userId, row)
  apis.system.userApi.getUser(userId).then((res: any) => {
    setOptions(res)
    form.value = res.data
    form.value.postIds = res.postIds
    form.value.roleIds = res.roleIds
    form.value.password = undefined
    modalRef.value.show()
  })
}
function setOptions(data: any) {
  userPosts.value = data.posts.map((v: any) => {
    return {
      label: v.postName,
      value: v.postId,
      disabled: v.status == 1,
    }
  })
  userRoles.value = data.roles.map((v: any) => {
    return {
      label: v.roleName,
      value: v.roleId,
      disabled: v.status == 1,
    }
  })
}
function submitForm() {
  if (form.value.userId != undefined) {
    apis.system.userApi.updateUser(form.value).then(() => {
      message.msgSuccess("修改成功")
      handleQuery()
    })
  } else {
    apis.system.userApi.addUser(form.value).then(() => {
      message.msgSuccess("新增成功")
      handleQuery()
    })
  }
}
function handleDelete(rows?: Array<any>) {
  rows = rows || tableRef.value.getSelecteds()
  if (!rows) {
    return
  }
  const userIds = rows.map((v) => v.userId)
  message
    .confirm('是否确认删除用户编号为"' + userIds.join("，") + '"的数据项？')
    .then(() => {
      apis.system.userApi.delUser(userIds).then(() => {
        handleQuery()
      })
    })
    .catch(() => {
      //
    })
}
const uploadModalRef = ref<any>()
const upload = {
  // 弹出层标题
  title: "导入数据",
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + apis.system.userApi.importUrl,
  accept: ".xlsx, .xls",
  templateUrl: apis.system.userApi.importTemplateUrl,
  templateName: "USER",
}
function handleImport() {
  uploadModalRef.value.show()
}

/** 文件上传成功处理 */
const handleFileSuccess = () => {
  handleQuery()
}
function handleExport() {
  download(apis.system.userApi.exportUrl, { ...queryParams }, `USER_${new Date().getTime()}.xlsx`)
}
/** 用户状态修改  */
function handleStatusChange(row: any) {
  const text = row.status === "0" ? "启用" : "停用"
  message
    .confirm('确认要"' + text + '""' + row.userName + '"用户吗?')
    .then(function () {
      return apis.system.userApi.changeUserStatus(row.userId, row.status)
    })
    .then(() => {
      message.msgSuccess(text + "成功")
    })
    .catch(function () {
      row.status = row.status === "0" ? "1" : "0"
    })
}
function handleResetPwd(row: any) {
  console.log("RP==>", row)
  message
    .prompt('请输入"' + row.userName + '"的新密码', "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
    })
    .then(({ value }) => {
      apis.system.userApi.resetUserPwd(row.userId, value).then(() => {
        message.msgSuccess("修改成功，新密码是：" + value)
      })
    })
    .catch(() => {
      //
    })
}
const authRoleModalRef = ref()
const authRoleRef = ref()
const authRoleUserId = ref()
function handleAuthRole(row: any) {
  console.log("AR==>", row)
  authRoleUserId.value = row.userId
  authRoleModalRef.value.show()
}
function submitAuthRole() {
  const roleIds = authRoleRef.value.getSelectedRoleIds()
  console.log("ROLEIDS", roleIds)
}
loadDept()
// onMounted(() => {

//   //console.log("PROXY", proxy?.$refs)
// })
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <DeptTree v-model="queryParams.deptId" :data="deptOptions" @node-click="handleQuery"></DeptTree>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <VbDataTable
          ref="tableRef"
          :handle-perm="permission"
          :handle-funs="handleFuns"
          :search-form-items="(searchFormItems as Array<VbFormItem>)"
          :header="columns"
          :query-params="queryParams"
          :url="apis.system.userApi.tableUrl"
          :check-multiple="true"
          :reset-search-form-fun="resetQuery"
          :custom-search-fun="handleQuery"
          :show-right-toolbar="true"
          :auto-search="false"
        >
          <template #deptName="{ row }">
            {{ row.dept.deptName }}
          </template>
          <template #status="{ row }">
            <el-switch
              v-model="row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(row)"
            ></el-switch>
          </template>
          <template #actions="{ row }">
            <span v-if="row.userId == 1" class="text-muted">-</span>
            <template v-else>
              <vb-tooltip content="修改" placement="top">
                <el-button
                  link
                  type="primary"
                  @click="handleUpdate(row)"
                  v-hasPermission="permissionNames.SystemUserEdit"
                >
                  <template #icon>
                    <KTIcon icon-name="notepad-edit" icon-type="duotone" class="fs-3"></KTIcon>
                  </template>
                </el-button>
              </vb-tooltip>
              <vb-tooltip content="删除" placement="top">
                <el-button
                  link
                  type="primary"
                  @click="handleDelete([row])"
                  v-hasPermission="permissionNames.SystemUserRemove"
                >
                  <template #icon>
                    <KTIcon icon-name="trash-square" icon-type="duotone" class="fs-3"></KTIcon>
                  </template>
                </el-button>
              </vb-tooltip>
              <vb-tooltip content="重置密码" placement="top">
                <el-button
                  link
                  type="primary"
                  @click="handleResetPwd(row)"
                  v-hasPermission="permissionNames.SystemUserResetpwd"
                >
                  <template #icon>
                    <KTIcon icon-name="key-square" icon-type="duotone" class="fs-3"></KTIcon>
                  </template>
                </el-button>
              </vb-tooltip>
              <vb-tooltip content="分配角色" placement="top">
                <el-button
                  link
                  type="primary"
                  @click="handleAuthRole(row)"
                  v-hasPermission="permissionNames.SystemUserEdit"
                >
                  <template #icon>
                    <KTIcon icon-name="user-square" icon-type="duotone" class="fs-3"></KTIcon>
                  </template>
                </el-button>
              </vb-tooltip>
            </template>
          </template>
        </VbDataTable>
      </el-col>
    </el-row>
    <VbModal
      v-model:modal="modalRef"
      :title="modalTitle"
      :form-items="(formItems as Array<VbFormItem>)"
      :form-data="form"
      @confirm="submitForm"
      append-to-body
    ></VbModal>
    <ImportModal ref="uploadModalRef" :options="upload" @on-success="handleFileSuccess" append-to-body></ImportModal>
    <VbModal v-model:modal="authRoleModalRef" title="分配角色" @confirm="submitAuthRole" append-to-body>
      <template #body>
        <AuthRole ref="authRoleRef" :user-id="authRoleUserId"></AuthRole>
      </template>
    </VbModal>
  </div>
</template>
