<template>
    <div class="p-2" style="width: 100%;overflow-y: scroll">
        <!--    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">-->
        <!--      <div class="mb-[10px]" v-show="showSearch">-->
        <!--        <el-card shadow="hover">-->
        <!--          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">-->
        <!--            <el-form-item label="部门名称" prop="deptName">-->
        <!--              <el-input v-model="queryParams.deptName" placeholder="请输入部门名称" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
        <!--            </el-form-item>-->
        <!--            <el-form-item label="状态" prop="status">-->
        <!--              <el-select v-model="queryParams.status" placeholder="部门状态" clearable>-->
        <!--                <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />-->
        <!--              </el-select>-->
        <!--            </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>-->
        <!--        </el-card>-->
        <!--      </div>-->
        <!--    </transition>-->

        <el-card shadow="hover">
            <!--      <template #header>-->
            <!--        <el-row :gutter="10">-->
            <!--          <el-col :span="1.5">-->
            <!--            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['system:dept:add']">新增 </el-button>-->
            <!--          </el-col>-->
            <!--          <el-col :span="1.5">-->
            <!--            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>-->
            <!--          </el-col>-->
            <!--          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
            <!--        </el-row>-->
            <!--      </template>-->

            <el-table v-loading="loading" :data="deptList" row-key="treeId"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" ref="deptTableRef"
                :default-expand-all="isExpandAll">
                <el-table-column prop="title" label="部门名称" width="260"></el-table-column>
                <el-table-column prop="leaderName" align="center" label="领导人" width="200"></el-table-column>
                <el-table-column prop="orderNum" align="center" label="排序" width="200"></el-table-column>
                <el-table-column prop="status" align="center" label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.arg?.enabled ? 'success' : 'danger'">
                            {{ scope.row.arg?.enabled ? '启用' : '停用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" prop="createTime" width="200">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" align="center" label="操作" width="200">
                    <template #default="scope">
                        <el-tooltip v-if="scope.row.type == 30" content="设置领导人" placement="top">
                            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
                        </el-tooltip>
                        <el-tooltip v-if="scope.row.type == 20" content="设置分公司负责人" placement="top">
                            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
                        </el-tooltip>
                        <el-tooltip :content="scope.row.arg?.enabled ? '停用' : '启用'" placement="top">
                            <el-button link :type="scope.row.arg?.enabled ? 'danger' : 'success'"
                                :icon="scope.row.arg?.enabled ? 'CircleClose' : 'CircleCheck'"
                                @click="handleStatusChange(scope.row)" />
                        </el-tooltip>
                        <!--                        <el-tooltip content="新增" placement="top">-->
                        <!--                            <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"-->
                        <!--                                       v-hasPermi="['system:dept:add']"/>-->
                        <!--                        </el-tooltip>-->
                        <!--                        <el-tooltip content="删除" placement="top">-->
                        <!--                            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"-->
                        <!--                                       v-hasPermi="['system:dept:remove']"/>-->
                        <!--                        </el-tooltip>-->
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <el-dialog :title="dialog.title" v-model="dialog.visible" destroy-on-close append-to-body width="600px">
            <el-form ref="deptFormRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="负责人" prop="leader">
                    <SelectUser v-model="form.managerId"></SelectUser>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" :loading="btnLoading" @click="submitForm">提交</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Dept" lang="ts">
import { listDeptList, setDepartManager, setLeaderId, enableDept } from "@/api/system/dept"
import { DeptForm, DeptQuery, DeptVO } from "@/api/system/dept/types";
import { UserVO } from "@/api/system/user/types";
import { addCurrencySetting, updateCurrencySetting } from "@/api/system/currencySetting";

// import {listUserByDeptId} from "@/api/system/user";

interface DeptOptionsType {
    deptId: number | string;
    deptName: string;
    children: DeptOptionsType[];

}

const { proxy } = getCurrentInstance() as ComponentInternalInstance
// const { sys_normal_disable } = toRefs<any>(proxy?.useDict("sys_normal_disable"));

const deptList = ref<DeptVO[]>([])
const loading = ref(true)
const showSearch = ref(true)
const deptOptions = ref<DeptOptionsType[]>([])
const isExpandAll = ref(true)
const deptUserList = ref<UserVO[]>([]);

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

const handleAdd = (row: DeptVO) => {


}

const handleUpdateCompany = (row: DeptVO) => {

}

const deptTableRef = ref<ElTableInstance>();
const queryFormRef = ref<ElFormInstance>();
const deptFormRef = ref<ElFormInstance>();

const initFormData: DeptForm = {
    deptId: undefined,
    parentId: undefined,
    deptName: undefined,
    orderNum: 0,
    leader: undefined,
    phone: undefined,
    email: undefined,
    status: "0",
    managerId: undefined,
    type: undefined
}
// const data = reactive<PageData<AllBusinessForm, AllBusinessQuery>>({

const data = reactive<PageData<DeptForm, DeptQuery>>({
    form: { ...initFormData },

    rules: {
        parentId: [{ required: true, message: "上级部门不能为空", trigger: "blur" }],
        deptName: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
        orderNum: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
        email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
        phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
    },
})

const { form, rules } = toRefs<PageData<DeptForm, DeptQuery>>(data)

/** 查询菜单列表 */
const getList = async () => {
    loading.value = true;
    // queryParams.value = [10, 20, 30]
    const res = await listDeptList([10, 20, 30], undefined);
    // const data = proxy?.handleTree<DeptVO>(res.data, "deptId")
    // if (data) {
    //   deptList.value = res
    // }
    deptList.value = res.result
    loading.value = false
}

/** 查询当前部门的所有用户 */
async function getDeptAllUser(deptId: any) {
    // if (deptId !== null && deptId !== "" && deptId !== undefined) {
    //   const res = await listUserByDeptId(deptId);
    //   deptUserList.value = res.data;
    // }
}

/** 取消按钮 */
const cancel = () => {
    reset()
    dialog.visible = false
}
/** 表单重置 */
const reset = () => {
    form.value = { ...initFormData };
    deptFormRef.value?.resetFields();
}

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

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
    isExpandAll.value = !isExpandAll.value;
    toggleExpandAll(deptList.value, isExpandAll.value)
}
/** 展开/折叠所有 */
const toggleExpandAll = (data: DeptVO[], status: boolean) => {
    data.forEach((item) => {
        deptTableRef.value?.toggleRowExpansion(item, status)
        if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
    })
}

const btnLoading = ref(false)
/** 修改按钮操作 */
const submitForm = async () => {

    // dialog.visible = true;
    // dialog.title = "设置领导";
    deptFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            btnLoading.value = true;
            if (form.value.type == 30) {
                await setDepartManager(form.value.deptId, form.value.managerId).finally(() => btnLoading.value = false);
            } else {
                await setLeaderId(form.value.deptId, form.value.managerId).finally(() => btnLoading.value = false);
            }

            proxy?.$modal.msgSuccess("修改成功");
            dialog.visible = false;
            await getList();
        }
    });
}

/** 修改按钮操作 */
const handleUpdate = async (row: DeptVO) => {
    form.value.deptId = row.id
    form.value.managerId = row.leaderId
    form.value.type = row.type
    dialog.visible = true;
    dialog.title = row.type == 20 ? "设置分公司负责人" : "设置领导人";
}

/** 启用/停用操作 */
const handleStatusChange = async (row: DeptVO) => {
    const newStatus = row.arg?.enabled ? false : true;
    const statusText = newStatus ? '启用' : '停用';

    proxy?.$modal.confirm(`确认要${statusText}"${row.title || row.deptName}"吗？`).then(async () => {
        try {
            console.log(row.type)
            await enableDept(row.id, newStatus,  row.type);
            proxy?.$modal.msgSuccess(`${statusText}成功`);
            await getList();
        } catch (error) {
            // proxy?.$modal.msgError(`${statusText}失败`);
        }
    }).catch(() => { });
}

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