<template>
    <hc-card :scrollbar="false" action-size="lg" class="user-page">
        <template #header>
            <div class="relative w-[300px]">
                <hc-search-input v-model="searchForm.account" color="#151921" text="搜索" @search="searchClick" />
            </div>
        </template>
        <template #extra>
            <el-button color="#20C98B" type="primary" @click="addClick">
                <hc-icon class="text-white" name="add" />
                <span class="text-white">新增</span>
            </el-button>
            <el-button :disabled="tableCheckedKeys.length === 0" color="#FF6C6C" :loading="batchDelLoad" @click="batchDelClick">
                <hc-icon class="text-white" name="delete-bin-2" />
                <span class="text-white">删除</span>
            </el-button>
            <el-button v-yes-com:[refreshPassword1] :disabled="tableCheckedKeys.length === 0" type="info" yes-com-text="是否重置密码为 123456">
                <hc-icon name="refresh" />
                <span>重置密码</span>
            </el-button>
            <el-button v-yes-com:[exportClick] color="#6CC2FF" yes-com-text="确定导出用户数据?" :loading="downloadLoading">
                <hc-icon class="text-white" name="download" />
                <span class="text-white">导出</span>
            </el-button>
        </template>
        <hc-table :column="tableColumn" :datas="tableData" class="user-page-table" is-check :loading="tableLoading" @selection-change="tableSelectionChange">
            <template #action="{ row }">
                <el-link type="success" @click="rowEditClick(row)">
                    <hc-icon name="edit" />编辑
                </el-link>
                <el-link type="success" @click="rowDelClick(row)">
                    <hc-icon name="delete-bin-2" />删除
                </el-link>
            </template>
        </hc-table>
        <template #action>
            <hc-pages :pages="searchForm" @change="pageChange" />
        </template>

        <!-- 新增编辑 -->
        <hc-dialog v-model="addModal" :title="modalTitle" widths="50rem" :loading="addsaveLoading" @save="modalSave">
            <hc-icon class="font-bold" name="user" style="font-size: 18px;" />
            <span class="font-bold">基础信息</span>
            <el-divider style="margin-top: 10px;" />
            <el-form ref="formRef" :inline="true" :model="baseForm" :rules="baseFormRules" label-width="auto">
                <div class="hc-form-item">
                    <el-form-item label="登陆账户:" prop="account">
                        <el-input v-model="baseForm.account" clearable placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="密码:" prop="passText">
                        <el-input v-model="baseForm.passText" clearable placeholder="请输入" show-password type="password" />
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="用户名:" prop="realName">
                        <el-input v-model="baseForm.realName" clearable placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="角色:" prop="roleId">
                        <!-- <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value" /> -->
                        <el-tree-select
                            v-model="roleIdArr"
                            :props="defaultProps"
                            :data="roleOptions"
                            multiple
                            :render-after-expand="false"
                            style="width: 240px"
                            @change="changeRole"
                        />
                    </el-form-item>
                </div>
            </el-form>
        </hc-dialog>
    </hc-card>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { HcDelMsg } from 'hc-vue3-ui'
import { arrToId, downloadBlob, formValidate, getArrValue, getObjValue } from 'js-fast-way'
import { add, getExportExcel, getList, getUser, remove, resetPassword, update } from '~api/system/user.js'
import { getRoleTree } from '~api/system/role.js'






onMounted(()=>{
    getTableData()
})
const tableColumn = [
    { key: 'account', name: '登陆账户', align: 'center' },
    { key: 'realName', name: '用户名', align: 'center' },
    { key: 'roleName', name: '角色', align: 'center' },
    { key: 'action', name: '操作', align: 'center', width: '140' },
]
const tableData = ref([])
const tableLoading = ref(false)

const addModal = ref(false)
const addClick = () => {
    modalTitle.value = '新增'
    addModal.value = true
    getRoleOptions()
}
const baseForm = ref({ account: '', realName: '', passText: '', roleId: '' })
const baseFormRules = {
    account: {
        required: true,
        trigger: 'blur',
        message: '请输入登陆账户',
    },
    passText: {
        required: true,
        trigger: 'blur',
        message: '请输入密码',
    },
    realName: {
        required: true,
        trigger: 'blur',
        message: '请输入用户名',
    },
    roleId: {
        required: true,
        trigger: 'blur',
        message: '请选择角色',
    },
}
const tableCheckedKeys = ref([])
//多选事件
const tableSelectionChange = (rows) => {
    tableCheckedKeys.value = rows
}
//搜索表单
const searchForm = ref({ account: null, current: 1, size: 20, total: 0 })

const searchClick = () => {
    getTableData()
}

const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await getList({
        ...searchForm.value,
    })
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
    } else {
        tableData.value = []
    }
    
}
//分页被点击
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}
const modalTitle = ref('新增')
const rowEditClick = async (row) => {
    modalTitle.value = '编辑'
    getRoleOptions().then()
    addModal.value = true
    roleIdArr.value = row.roleId.split(',')
    const { error, code, data } = await getUser( row.id)
    if (!error && code === 200) {
        baseForm.value = getObjValue(data)
    } else {
        baseForm.value = {}
    }
}
const batchDelClick = ()=>{
    let ids = arrToId(tableCheckedKeys.value)
    HcDelMsg(async (resolve) => {
        await removeUser(ids)
        resolve() //关闭弹窗的回调
    })

}
const batchDelLoad = ref(false)
const rowDelClick = (row) => {
    HcDelMsg(async (resolve) => {
        await removeUser(row.id)
        resolve() //关闭弹窗的回调
    })
}
const removeUser = async (ids) => {
    const { error, code, msg } = await remove(
        ids,
    )
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
       getTableData()
    } else {
        window.$message.error(msg ?? '操作失败')
    }
}
const refreshPassword1 = async (_, resolve) => {
    let ids = arrToId(tableCheckedKeys.value)
    //这里可以写一些操作
    await resetPasswordClick(ids)
    resolve() //这个一定要存在，否则不会关闭弹窗
}
const resetPasswordClick = async (id)=>{
    const { error, code, msg } = await resetPassword(
        id,
    )
    if (!error && code === 200) {
        window?.$message?.success(msg)
       getTableData()
    } else {
        window.$message.error(msg ?? '操作失败')
    }
}
const exportClick = async (_, resolve) => {
    //这里可以写一些操作
   await getExportExcelClick()
    resolve() //这个一定要存在，否则不会关闭弹窗
}
const downloadLoading = ref(false)
const getExportExcelClick = async () => {
    //批量下载
    downloadLoading.value = true
    const { error, disposition, res } = await getExportExcel({
     
    })
    //处理数据
    downloadLoading.value = false
    if (!error) {
        if (disposition) {
            downloadBlob(res, disposition)
        } else {
            window.$message?.error('数据异常')
        }
    }
}

const formRef = ref(null)
const roleIdArr = ref([])
const addsaveLoading = ref(false)
const changeRole = (val)=>{
    baseForm.value.roleId = roleIdArr.value.join(',')
}
const modalSave = async ()=>{
    const isValidate = await formValidate(formRef.value)
    if (!isValidate) return false

    addsaveLoading.value = true
    console.log(baseForm.value, 'baseForm.value')
    
        if (modalTitle.value === '编辑') {
            const { error, code, msg } = await update({
            ...baseForm.value,
            roleId:roleIdArr.value.join(','),
            })
            //判断状态
            addsaveLoading.value = false
            if (!error && code === 200) {
                window?.$message?.success(msg)
                addModal.value = false
                getTableData()
            } else {
                window.$message.error(msg ?? '操作失败')
            }
        } else {
            const { error, code, msg } = await add({
            ...baseForm.value,
            roleId:roleIdArr.value.join(','),
          
            })
            //判断状态
            addsaveLoading.value = false
            if (!error && code === 200) {
                window?.$message?.success(msg)
                getTableData()
            } else {
                window.$message.error(msg ?? '操作失败')
            }
        }

  
}
const roleOptions = ref([])
const defaultProps = {
  children: 'children',
  label: 'title',
}
const getRoleOptions = async () => {
    const { error, code, data } = await getRoleTree('000000')
    if (!error && code === 200) {
        roleOptions.value = getArrValue(data)
        console.log(roleOptions.value, 'roleOptions.value')
    } else {
        roleOptions.value = []
    }
    
  
}
</script>
