<template>
    <el-card shadow="never" class="list-card">
        <template #header>
            <div class="search" v-show="showSearch">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                    <el-form-item prop="mobile">
                        <el-input v-model="queryParams.blurry" 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-form-item>
                </el-form>
            </div>
        </template>

        <MyTable ref="userTable" :tableParams="tableParams" :btnRole="leftBtn" :rightBtn="[]"
            @selectionChange="handleSelectionChange">
            <template #left>
                <el-button v-hasPermi="[`system:user:syncOa`]" :loading="syncOaLoading" @click="syncOa">同步用户</el-button>
                <!-- 离职继承 -->
                <el-button type="primary" :disabled="multiple" @click="handleResignTransfer">离职继承</el-button>
                <el-button type="warning" :disabled="multiple" @click="handleBatchFreeze(1)">用户冻结</el-button>
                <el-button type="success" :disabled="multiple" @click="handleBatchFreeze(0)">用户解冻</el-button>

            </template>
        </MyTable>
    </el-card>
    <!-- 授权 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
        <el-form ref="userFormRef" :model="form" label-width="80px">
            <el-form-item label="用户名称">
                <el-input readonly v-model="form.realName" disabled placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="绑定角色" prop="roleIds">
                <el-select v-model="form.roleIds" multiple placeholder="请选择">
                    <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="handleSelect">提交</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 离职继承弹窗 -->
    <el-dialog title="离职继承" v-model="resignDialog.visible" width="500px" append-to-body>
        <el-form ref="resignFormRef" :model="resignForm" label-width="100px">
            <el-form-item label="离职人员">
                <el-input readonly v-model="resignForm.resignUserNames" disabled placeholder="离职人员" />
            </el-form-item>
            <el-form-item label="选择继承人" prop="newOwnerBy" :rules="[{ required: true, message: '请选择继承人', trigger: 'change' }]">
                <SelectUser v-model="resignForm.newOwnerBy" :multiple="false" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button :loading="resignButtonLoading" type="primary" @click="handleResignSubmit">确定</el-button>
                <el-button @click="resignDialog.visible = false">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="User" lang="ts">
import { pageUserlist, getUser, delUser, addUser, updateUser, enableUser, syncOaApi, setUserRole, resetPrePwd, markFreeze } from '@/api/system/user';
import {UserVO, UserQuery, UserForm} from '@/api/system/user/types';
import {RoleVO, RoleQuery, RoleForm} from '@/api/system/role/types';
import MyTable from '@/components/Table/index.vue'
import {tableTypes} from '@/components/Table/types'
import SelectUser from '@/components/SelectUser/SelectUser.vue'
import {
    bindRoleUser,
    listRole
} from '@/api/system/role';
import { resignTransfer, ResignTransferTypes } from '@/api/customer';

import auth from '@/plugins/auth'
import {completelyDelEmails} from "@/api/emails";

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const userList = ref<UserVO[]>([]);
const roleList = ref<RoleVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const syncOaLoading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const leftBtn = ref<Array<string | number>>(
    [
        'system:user:export',
    ]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const userFormRef = ref<ElFormInstance>();

const form = reactive<UserForm>({
    id: undefined,
    userName: undefined,
    realName: undefined,
    sex: undefined,
    mobile: undefined,
    deptId: undefined,
    jobId: undefined,
    roleIds: [],
    enabled: undefined,
});

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const resignDialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

interface ResignForm {
    resignUserNames: string;
    newOwnerBy: string | number | undefined;
    oldOwnerByIds: (string | number)[];
}

const resignForm = reactive<ResignForm>({
    resignUserNames: '',
    newOwnerBy: undefined,
    oldOwnerByIds: []
});

const resignFormRef = ref<ElFormInstance>();
const resignButtonLoading = ref(false);

const syncOa = async () => {

    ElMessageBox.confirm(
        '是否同步OA用户？',
        '确认提示',
        { type: 'warning' , confirmButtonText: '提交'}
    ).then(async () => {
        syncOaLoading.value = true
        let data = await syncOaApi()
        if(data.code == 200) {
            proxy?.$modal.msgSuccess('同步成功');
        }
        syncOaLoading.value = false

    }).catch(() => {})

}

const tableParams = reactive<tableTypes<UserQuery, UserVO>>({
    tableColumn: [
        {show: true, label: '账号', prop: 'userName',},
        {show: true, label: '姓名', prop: 'realName',},
        {show: true, label: '性别', prop: 'sex',},
        {show: true, label: '手机', prop: 'mobile',},
        {show: true, label: '部门', prop: 'deptName',},
        {show: true, label: '岗位', prop: 'jobName',},
        {show: true, label: '状态', prop: 'enabled', render: ({ column }: { column: UserVO }) => {
            return [
               h(ElSwitch, {value: column.enabled, modelValue: column.enabled, onChange: async (v)=>{
                   let ids:Array<number | string> = []
                       if (column?.id) {
                           ids.push(column.id)
                       }
                       await enableUser(ids, v);
                       column.enabled = v
               }}),
            ]
        }},
        {show: true, label: '冻结状态', prop: 'isFreeze', render: ({ column }: { column: UserVO }) => {
            return [
                h('span', {
                    style: {
                        color: column.isFreeze === 1 ? '#F56C6C' : '#67C23A',
                        fontWeight: 'bold'
                    }
                }, column.isFreeze === 1 ? '已冻结' : '正常')
            ]
        }},
        {show: true, label: '当前角色', prop: 'roleNames',},
        {
            show: true, label: '操作', width: 280, prop: 'operation', disabledMove: true, render: ({ column }: { column: UserVO }) => {
                return [
                    auth.hasPermi('system:user:auth') ?
                        h(ElButton, {link: true, type: 'primary', onClick: ()=>{
                                authPermission(column)
                            }}, '授权')
                        : '',
                    h(ElButton, {link: true, type: 'primary', onClick: ()=>{
                            resetPwd(column)
                        }}, '重置密码'),
                    column.isFreeze === 1 ?
                        h(ElButton, {link: true, type: 'success', onClick: ()=>{
                                handleFreeze(column, 0)
                            }}, '解除冻结')
                        :
                        h(ElButton, {link: true, type: 'warning', onClick: ()=>{
                                handleFreeze(column, 1)
                            }}, '冻结')
                ]
            }
        }
    ],
    queryParams: {
        blurry: undefined,
    },
    listFn: pageUserlist,
    delFn: delUser,
})

const {queryParams} = toRefs(tableParams);
/** 取消按钮 */
const cancel = () => {
    dialog.visible = false;
}


const userTable = ref()

/** 搜索按钮操作 */
const handleQuery = () => {
    userTable.value.getData()
}

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
}

/** 多选框选中数据 */
const selectedUsers = ref<UserVO[]>([]);
const handleSelectionChange = (selection: UserVO[]) => {
    selectedUsers.value = selection;
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 授权 */
const authPermission = async (row?: UserVO) => {
    // const _id = row?.id || ids.value[0]
    form.roleIds = []

    let queryParam = {
        pageIndex: 1,
        pageSize: 999999
    }
    Object.assign(form, row)
    const res = await listRole(queryParam);
    roleList.value = res.result.records
    dialog.visible = true;
    dialog.title = "用户授权";
}

/**选择授权用户操作 */
const handleSelect= async () => {
    // if (form?.userIds.length == 0) {
    //     proxy?.$modal.msgError('请选择要分配的用户');
    //     return;
    // }
    buttonLoading.value = true;
    let data = {
        rids: form.roleIds,
        uid: form.id
    }
    await setUserRole(data);
    proxy?.$modal.msgSuccess('分配成功');
    dialog.visible = false;
    buttonLoading.value = false
}

const getList = () => {
    userTable.value.getData()
}

const resetPwd = async (row?: UserVO)=>{

    await resetPrePwd(row.id)
    proxy?.$modal.msgSuccess('重置成功');
}

/** 冻结/解冻用户 */
const handleFreeze = async (row: UserVO, isFreeze: number) => {
    const action = isFreeze === 1 ? '冻结' : '解除冻结';
    const confirmText = isFreeze === 1
        ? `确认要冻结用户"${row.realName}"吗？冻结后该账号的业务数据"置公时间"将不再变更，直到操作解除。`
        : `确认要解除冻结用户"${row.realName}"吗？`;

    ElMessageBox.confirm(
        confirmText,
        `${action}提示`,
        { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' }
    ).then(async () => {
        let userIds: Array<number | string> = [];
        if (row?.id) {
            userIds.push(row.id);
        }
        await markFreeze(userIds, isFreeze);
        proxy?.$modal.msgSuccess(`${action}成功`);
        row.isFreeze = isFreeze;
        await getList();
    }).catch(() => {});
}

/** 批量冻结/解冻用户 */
const handleBatchFreeze = async (isFreeze: number) => {
    if (ids.value.length === 0) {
        proxy?.$modal.msgWarning('请选择要操作的用户');
        return;
    }

    const action = isFreeze === 1 ? '冻结' : '解除冻结';
    const confirmText = isFreeze === 1
        ? `确认要批量冻结选中的 ${ids.value.length} 个用户吗？冻结后这些账号的业务数据"置公时间"将不再变更，直到操作解除。`
        : `确认要批量解除冻结选中的 ${ids.value.length} 个用户吗？`;

    ElMessageBox.confirm(
        confirmText,
        `批量${action}提示`,
        { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' }
    ).then(async () => {
        await markFreeze(ids.value, isFreeze);
        proxy?.$modal.msgSuccess(`批量${action}成功`);
        await getList();
    }).catch(() => {});
}

/** 离职继承 - 打开弹窗 */
const handleResignTransfer = async () => {
    if (ids.value.length === 0) {
        proxy?.$modal.msgWarning('请选择离职人员');
        return;
    }

    // 获取选中用户的姓名
    const userNames = selectedUsers.value.map(user => user.realName).join('、');

    // 重置表单
    resignForm.resignUserNames = userNames;
    resignForm.newOwnerBy = undefined;
    resignForm.oldOwnerByIds = ids.value;

    // 打开弹窗
    resignDialog.visible = true;
}

/** 离职继承 - 提交 */
const handleResignSubmit = async () => {
    resignFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            if (!resignForm.newOwnerBy) {
                proxy?.$modal.msgWarning('请选择继承人');
                return;
            }

            resignButtonLoading.value = true;
            try {
                const data: ResignTransferTypes = {
                    oldOwnerByIdls: resignForm.oldOwnerByIds,
                    newOwnerBy: resignForm.newOwnerBy
                };
                await resignTransfer(data);
                proxy?.$modal.msgSuccess('离职继承成功');
                resignDialog.visible = false;
                await getList();
            } finally {
                resignButtonLoading.value = false;
            }
        }
    });
}

// /** 提交按钮 */
// const submitForm = () => {
//     userFormRef.value?.validate(async (valid: boolean) => {
//         if (valid) {
//             buttonLoading.value = true;
//             if (form.value.id) {
//                 await updateUser(form.value).finally(() => buttonLoading.value = false);
//             } else {
//                 await addUser(form.value).finally(() => buttonLoading.value = false);
//             }
//             proxy?.$modal.msgSuccess("修改成功");
//             dialog.visible = false;
//             await getList();
//         }
//     });
// }


onMounted(() => {
});
</script>
