<template>
    <div class="hc-project-wbs-user relative h-full">
        <hc-card>
            <template #header>
                <div class="w-200px">
                    <el-select v-model="searchForm.cId" filterable clearable block placeholder="选择合同段" @change="searchClick">
                        <el-option v-for="item in contractList" :key="item.id" :label="item.contractName" :value="item.id" />
                    </el-select>
                </div>
                <div class="ml-14px w-200px">
                    <el-tree-select
                        v-model="searchForm.rId" placeholder="选择维护人员角色" clearable filterable check-strictly block
                        :data="roleList" :props="roleProps" :render-after-expand="false" @change="searchClick"
                    />
                </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="danger" @click="delRowClick(row)">删除</el-link>
                </template>
            </hc-table>
            <template #action>
                <hc-pages :pages="searchForm" @change="pageChange" />
            </template>
        </hc-card>
    </div>
</template>

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

const router = useRouter()

//双向绑定
const modelData = defineModel('modelValue', {
    default: {},
})

//监听数据
const formModel = ref({})
watch(() => modelData.value, (data) => {
    formModel.value = data
}, { immediate: true, deep: true })

//渲染完成
onMounted(() => {
    getContractList()
    getRoleList()
    searchClick()
    getUserData()
})

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

//获取合同段数据
const contractList = ref([])
const getContractList = async () => {
    const { id } = formModel.value
    if (isNullES(id)) {
        contractList.value = []
        return
    }
    const { data } = await contractApi.getList(id)
    contractList.value = getArrValue(data)
}

//角色列表
const roleList = ref([])
const roleProps = { value: 'id', label: 'dictValue' }
const getRoleList = async () => {
    const { data } = await getBizDictionary({ code: 'maintainer_role' })
    roleList.value = getArrValue(data)
}

//搜索
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: '姓名', width: 120, align: 'center' },
    { key: 'phone', name: '电话', width: 120, align: 'center' },
    { key: 'postName', name: '岗位', width: 120, align: 'center' },
    { key: 'contractName', name: '合同段名称' },
    { key: 'action', name: '操作', width: 80, align: 'center' },
])
const tableData = ref([])

//获取表格数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableData.value = []
    const { id } = formModel.value
    if (isNullES(id)) return
    tableLoading.value = true
    const { data } = await contractApi.getUserListByCondition({
        ...searchForm.value,
        pId: id,
    })
    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 () => {
    const { id } = formModel.value
    if (isNullES(id)) {
        window?.$message?.warning('项目数据异常')
        return
    }
    const { cId, rId } = searchForm.value
    if (isNullES(rId)) {
        window?.$message?.warning('请先选择维护人员角色再进行添加')
        return
    }
    addUserLoading.value = true
    const list = [{
        projectId: id,
        contractId: isNullES(cId) ? undefined : cId,
        userId: userId.value,
        roleId: rId,
    }]
    const { code } = await contractApi.saveUserInfoByProject(list)
    addUserLoading.value = false
    if (code === 200) {
        window?.$message?.success('添加成功')
        getTableData().then()
    }
}

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

//全部删除
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()
        }
    })
}
</script>

<style lang="scss">
.hc-project-wbs-user {
    .el-card.hc-card-box.hc-new-card-box {
        box-shadow: none;
    }
}
</style>
