<template>
    <el-dialog v-model="dialogVisible" :title="title" :width="width" :before-close="close">
        <div class="dialog-body">
            <el-card shadow="never">
                <template #header>
                    <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                        <el-form-item label="关键字" prop="applicationName">
                            <el-input
                                v-model="queryParams.keywords"
                                placeholder="请输入关键字"
                                clearable
                                style="width: 240px"
                                @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                            <!-- <el-button type="primary" icon="Search" @click="handleQuery">新增企业成员</el-button> -->
                        </el-form-item>
                    </el-form>
                </template>
                <el-table :data="list" border style="width: 100%">
                    <el-table-column label="序号" width="60">
                        <template #default="{ $index }">
                            {{ queryParams.pageSize * (queryParams.pageNum - 1) + ($index + 1) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="userInfo.name" label="姓名" width="100" />
                    <el-table-column prop="userInfo.phone" width="120" label="手机号码" />
                    <el-table-column prop="createTime" show-overflow-tooltip label="申请时间" />
                    <el-table-column prop="address" label="角色">
                        <template #default="{ row }">
                            <template v-if="row.isAdmin">管理员</template>
                            <template v-if="row.res * 1 === 0">待审核成员</template>
                            <template v-if="row.res * 1 === 1 && !row.isAdmin">普通成员</template>
                        </template>
                    </el-table-column>
                    <el-table-column prop="res" width="90" label="状态">
                        <template #default="{ row }">
                            <div :style="{ color: cpy_res_status.find((item: any) => item.value === row.res).elTagClass }">
                                {{ selectDictLabel(cpy_res_status, row.res) }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" min-width="160" label="操作">
                        <template #default="{ row }">
                            <template v-if="row.res === '1'">
                                <template v-if="!row.isAdmin">
                                    <el-button @click="submitRemoveUser(row)" type="danger">移除人员</el-button>
                                </template>
                                <template v-if="!row.isAdmin">
                                    <el-button @click="submitSettingCpyAdmin(row)" type="primary">设为管理员</el-button>
                                </template>
                            </template>
                            <template v-if="row.res === '0'">
                                <el-button @click="handleApproval(row, '1')" type="success">审核通过</el-button>
                                <el-button @click="handleApproval(row, '2')" type="warning">审核不通过</el-button>
                            </template>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="d-flex j-c">
                    <el-pagination
                        v-model:page-size="queryParams.pageSize"
                        background
                        v-model:current-page="queryParams.pageNum"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"
                        hide-on-single-page
                        @size-change="changePageSize"
                        @current-change="changePage"
                    />
                </div>
            </el-card>
        </div>
    </el-dialog>
</template>
<script setup name="Staff" lang="ts">
import { propTypes } from '@/utils/propTypes';
import { debounce } from 'lodash';
import router from '@/router';
import { bindInfoApproval, companyMembers, removeUser, settingCpyAdmin } from '@/api/settled';
import { CircleCheck, CircleClose } from '@element-plus/icons-vue';
const emit = defineEmits(['update:show']);
const dialogVisible = ref(false);
const queryFormRef = ref();
const props = defineProps({
    show: propTypes.bool.def(false),
    title: propTypes.string.def('维护成员'),
    width: propTypes.string.def('1100px'),
    info: propTypes.object.def({})
});
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { cpy_res_status } = toRefs<any>(proxy?.useDict('cpy_res_status'));
const list = ref<any[]>([]);
const total = ref(0);
const infoForm = ref<any>(null);
const queryParams = ref({
    pageSize: 10,
    pageNum: 1,
    keywords: '',
    cpyid: ''
});
const submitRemoveUser = async (row: any) => {
    const confirm = await proxy?.$modal.confirm('您确定移除该成员么').catch(() => {});
    if (confirm === 'confirm') {
        const params = {
            cpyid: infoForm.value.id,
            userids: [row.userid]
        }
        proxy?.$modal.loading('移除中...')
        const res = await removeUser(params).catch(() => proxy?.$modal.closeLoading())
        proxy?.$modal.closeLoading()
        if (!res) return
        proxy?.$modal.msgSuccess('移除成功')
        onSearch()
    }
};
const submitSettingCpyAdmin = async (row: any) => {
    const confirm = await proxy?.$modal.confirm('您确定将该该成员设为管理员么').catch(() => {});
    if (confirm === 'confirm') {
        const params = {
            cpyid: infoForm.value.id,
            userid: row.userid
        }
        proxy?.$modal.loading('加载中...')
        const res = await settingCpyAdmin(params).catch(() => proxy?.$modal.closeLoading())
        proxy?.$modal.closeLoading()
        if (!res) return
        proxy?.$modal.msgSuccess('设置成功')
        onSearch()
    }
};
// 审批办理
const handleApproval = async (row: any, res: string) => {
    if (res === '1') {
        ElMessageBox.confirm('该成员审核通过?', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'success',
            icon: markRaw(CircleCheck)
        })
            .then(() => {
                const params = {
                    approvalType: '2',
                    targetId: row.id,
                    res
                };
                approvalAjax(params);
            })
            .catch(() => {
                proxy?.$modal.msgWarning('取消审核');
            });
    } else {
        ElMessageBox.prompt('该成员审核不通过', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            inputPlaceholder: '不通过理由',
            inputErrorMessage: '请填写不通过理由',
            type: 'error',
            icon: markRaw(CircleClose),
            inputValidator: (value) => {
                return value ? true : false
            }
        })
            .then(({ value }) => {
                const params = {
                    approvalType: '2',
                    targetId: row.id,
                    res,
                    msg: value
                };
                approvalAjax(params);
            })
            .catch(() => {
                proxy?.$modal.msgWarning('取消审核');
            });
    }
};
const approvalAjax = async (params: any) => {
    proxy?.$modal.loading('审核中...')
    const res = await bindInfoApproval(params).catch(() => {});
    proxy?.$modal.closeLoading()
    if (!res) return;
    proxy?.$modal.msgSuccess('操作完成')
    handleQuery()
};
/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};
const onSearch = () => {
    queryParams.value.pageNum = 1;
    getList();
};

const changePageSize = (pageSize: number) => {
    queryParams.value.pageSize = pageSize;
    getList();
};
const changePage = (pageNum: number) => {
    queryParams.value.pageNum = pageNum;
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};
const getList = debounce(async () => {
    proxy?.$modal.loading('加载中');
    const res = await companyMembers(queryParams.value).catch(() => {
        proxy?.$modal.closeLoading();
    });
    if (!res || res.code !== 200) return;
    proxy?.$modal.closeLoading();
    total.value = res.total;
    list.value = [...res.rows];
}, 300);
const close = () => {
    emit('update:show', false);
};
watch(
    () => props.show,
    (val) => {
        dialogVisible.value = val;
        if (val) {
            onSearch();
        }
    },
    { immediate: true }
);
watch(
    () => props.info,
    (val) => {
        infoForm.value = { ...val };
        queryParams.value.cpyid = val?.id;
    }
);
</script>
<style lang="scss" scoped>
.my-header {
    padding: 16px 16px 0;
}
.my-footer {
    .el-checkbox {
        white-space: pre-wrap;
    }
}
</style>
