<template>
    <div class="hc-contract-info-user relative h-full">
        <hc-card>
            <template #header>
                <div class="w-200px">
                    <el-select v-model="rId" filterable clearable block placeholder="选择角色方" @change="setRolePostData">
                        <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id" />
                    </el-select>
                </div>
                <div class="ml-14px w-200px">
                    <el-select v-model="postId" filterable clearable block placeholder="选择岗位" @change="searchPostClick">
                        <el-option v-for="item in postList" :key="item.id" :label="item.roleName" :value="item.id" />
                    </el-select>
                </div>
            </template>
            <template #extra>
                <el-button hc-btn type="primary" @click="addUserClick">创建新用户</el-button>
                <el-button hc-btn type="danger" @click="allDelClick">全部删除</el-button>
            </template>
            <template #search>
                <div class="mr-14px w-160px">
                    <el-select-v2
                        v-model="userId" :options="userList" :props="userProps"
                        placeholder="选择系统内部人员" filterable clearable block
                    />
                </div>
                <el-button type="primary" :disabled="isNullES(userId)" @click="addUserTap">添加</el-button>
            </template>
            <hc-table :column="tableColumn" :datas="tableData" :loading="tableLoading" :is-index="false">
                <template #action="{ row }">
                    <el-link type="primary" @click="copyRowClick(row)">复制</el-link>
                    <el-link type="warning" @click="resetRowClick(row)">重置密码</el-link>
                    <el-link type="danger" @click="delRowClick(row)">删除</el-link>
                </template>
            </hc-table>
            <template #action>
                <hc-pages :pages="searchForm" @change="pageChange" />
            </template>
        </hc-card>
        <div class="action">
            <el-button hc-btn class="mr-4" @click="saveAndExit">保存并退出</el-button>
            <el-button hc-btn type="primary" @click="saveAndBackStep">保存并返回上一步</el-button>
        </div>
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { HcFirmMsg, NewDelMsg } from 'hc-vue3-ui'
import { arrToId, deepClone, getArrValue, getObjValue, isNullES, setCopyText } from 'js-fast-way'
import contractApi from '~api/project/contract'

const props = defineProps({
    data: {
        type: Object,
        default: () => ({}),
    },
})

//事件
const emit = defineEmits(['close', 'back'])

//路由
const router = useRouter()

//监听数据
const dataInfo = ref(props.data)
watch(() => props.data, (data) => {
    dataInfo.value = data
    getDataApi()
}, { deep: true })

//渲染完成
onMounted(() => {
    getDataApi()
})

//获取数据
const getDataApi = () => {
    getRoleList()
    getUserData()
}

//搜索表单
const searchForm = ref({
    rId: '', current: 1, size: 30, total: 0,
})

//获取合同段数据
const rId = ref('')
const roleName = ref('')
const roleList = ref([])
const getRoleList = async () => {
    const { data } = await contractApi.searchRole()
    const res = getArrValue(data)
    roleList.value = res
    if (res.length > 0) {
        rId.value = res[0].id
        roleName.value = res[0].roleName
    } else {
        rId.value = ''
    }
    await setRolePostData()
}

//处理角色岗位
const postId = ref('')
const postList = ref([])
const setRolePostData = async () => {
    postId.value = ''
    postList.value = []
    if (isNullES(rId.value)) return
    const arr = roleList.value
    const res = arr.find((item) => item.id === rId.value)
    const obj = deepClone(getObjValue(res))
    postList.value = getArrValue(obj.children)
    if (obj.roleName === '超级管理员') {
        searchForm.value.rId = obj.id
        searchClick()
    }
}

//岗位搜索
const searchPostClick = () => {
    searchForm.value.rId = deepClone(postId.value)
    searchClick()
}

//搜索
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

//分页
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//表格数据
const tableColumn = ref([
    { key: 'name', name: '姓名' },
    { key: 'account', name: '登录账号' },
    { key: 'password', name: '密码' },
    { key: 'action', name: '操作', width: 160, align: 'center' },
])
const tableData = ref([])

//获取表格数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableData.value = []
    tableLoading.value = true
    const { pid, cid } = getObjValue(dataInfo.value)
    const { data } = await contractApi.findUserByCondition({
        ...searchForm.value,
        pId: pid,
        cId: cid,
    })
    tableLoading.value = false
    tableData.value = getArrValue(data?.records)
    searchForm.value.total = data?.total || 0
}

//用户列表
const userId = ref('')
const userProps = { value: 'id', label: 'name' }

//获取用户列表
const userList = ref([])
const getUserData = async () => {
    const { data } = await contractApi.findUserList()
    userList.value = getArrValue(data)
}

//将系统用户添加进来
const addUserLoading = ref(false)
const addUserTap = async () => {
    if (isNullES(userId.value)) {
        window?.$message?.warning('请先选择用户再进行添加')
        return
    }
    const search = searchForm.value
    if (isNullES(search.rId)) {
        window?.$message?.warning('请先选择岗位再进行添加')
        return
    }
    addUserLoading.value = true
    const { pid, cid } = getObjValue(dataInfo.value)
    const list = [{
        projectId: pid,
        contractId: cid,
        userId: userId.value,
        roleId: search.rId,
    }]
    const { code } = await contractApi.saveUserInfoByProjectTow(list)
    addUserLoading.value = false
    if (code === 200) {
        window?.$message?.success('添加成功')
        getTableData().then()
    }
}

//创建新用户
const addUserClick = () => {
    router.push({
        path: '/system/user',
        query: { type: 'add' },
    })
}

//复制
const copyRowClick = ({ name, account, password }) => {
    const isRes = setCopyText(`姓名：${name}
账号：${account}
密码：${password}`)
    if (isRes) {
        window?.$message?.success('复制成功')
    } else {
        window?.$message?.warning('复制失败')
    }
}

//重置密码
const resetRowClick = (row) => {
    HcFirmMsg({
        title: '操作确认',
        text: '是否将用户【' + row.name + '】密码重置为123456?',
    }, async (resolve) => {
        const { isRes } = await contractApi.resetPasswordByUserId(row.uid)
        resolve() //关闭弹窗的回调
        if (!isRes) return
        row.password = '123456'
        window.$message.success('重置成功')
    })
}

//全部删除
const allDelClick = () => {
    const data = tableData.value
    if (data.length <= 0) {
        window?.$message?.warning('暂无用户数据')
        return
    }
    NewDelMsg({
        text: '是否将所有用户移除出合同段?',
    }, async (resolve) => {
        const ids = arrToId(data)
        const { code } = await contractApi.removeUsersByIds(ids)
        resolve() //关闭弹窗的回调
        if (code === 200) {
            window?.$message?.success('删除成功')
            getTableData().then()
        }
    })
}

//单独删除
const delRowClick = (row) => {
    NewDelMsg({
        text: '是否将该用户移除出合同段?',
    }, async (resolve) => {
        const { code } = await contractApi.removeUsersByIds(row.id)
        resolve() //关闭弹窗的回调
        if (code === 200) {
            window?.$message?.success('删除成功')
            getTableData().then()
        }
    })
}

//保存并退出
const saveAndExit = async () => {
    emit('close', dataInfo.value)
}

//保存并返回上一步
const saveAndBackStep = async () => {
    emit('back', dataInfo.value)
}
</script>

<style lang="scss">
.hc-contract-info-user {
    .hc-div-new-card-box.hc-full {
        height: calc(100% - 55px);
    }
    .el-card.hc-card-box.hc-new-card-box {
        box-shadow: none;
    }
    .action {
        position: fixed;
        bottom: 14px;
        width: calc(100% - 240px);
        text-align: center;
        background: #fff;
        padding: 14px 0;
    }
}
</style>
