<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--维保目录-->
            <el-col :span="sidebarSpan" :xs="24" v-show="showSidebar">
                <MaintenanceSidebar v-model="queryParams.maintenanceId" v-model:maintenanceList="maintenanceList"
                    v-model:maintenanceOptions="maintenanceOptions" v-model:maintenance="maintenance"
                    @onView="handleMaintenanceView" />
            </el-col>
            <!--维保项目-->
            <el-col :span="showSidebar ? 24 - sidebarSpan : 24" :xs="24">
                <el-tabs type="border-card" v-model="activeTabName">
                    <el-tab-pane label="目录" name="maintenance">
                        <MaintenanceDescription :maintenance="maintenance" class="margin-top"
                            v-show="queryParams.maintenanceId != null" />
                        <el-empty v-show="queryParams.maintenanceId == null" />
                    </el-tab-pane>
                    <el-tab-pane label="计划" name="maintenancePlan">

                        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch"
                            label-width="120px">
                            <el-form-item label="维保" prop="maintenanceId">
                                <el-tree-select v-model="queryParams.maintenanceId" :data="maintenanceOptions"
                                    :props="{ value: 'maintenanceId', label: 'maintenanceName', children: 'children' }"
                                    value-key="maintenanceId" placeholder="请选择维保" check-strictly filterable clearable
                                    @change="handleQuery" @keyup.enter="handleQuery" />
                            </el-form-item>
                            <el-form-item label="维保项目" prop="maintenanceProjectName">
                                <el-input v-model="queryParams.maintenanceProjectName" placeholder="请输入维保项目" clearable
                                    @keyup.enter="handleQuery" />
                            </el-form-item>
                            <el-form-item label="维保项目标准" prop="maintenanceProjectStandard">
                                <el-input v-model="queryParams.maintenanceProjectStandard" placeholder="请输入维保项目标准"
                                    clearable @keyup.enter="handleQuery" />
                            </el-form-item>
                            <el-form-item label="维保项目责任人" prop="maintenanceProjectPersonLiable">
                                <el-select v-model="queryParams.maintenanceProjectPersonLiable" filterable
                                    placeholder="请选择维保项目责任人" @change="handleQuery" clearable>
                                    <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName"
                                        :value="item.roleId" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="维保项目周期" prop="maintenanceProjectCycle">
                                <el-select v-model="queryParams.maintenanceProjectCycle" filterable
                                    placeholder="请选择维保项目周期" @change="handleQuery" clearable>
                                    <el-option v-for="item in maintenance_project_cycle" :key="item.value"
                                        :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <!-- <el-form-item label="启用/停用" prop="maintenanceProjectDepType">
                        <el-select v-model="queryParams.maintenanceProjectDepType" filterable placeholder="请选择启用/停用"
                            @change="handleQuery" clearable>
                            <el-option label="启用" value="1" />
                            <el-option label="停用" value="0" />
                        </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-row :gutter="10" class="mb8" style="min-height:32px">
                            <!-- <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleAddWarehouse"
                            v-hasPermi="['maintenanceProject:maintenanceProject:add']">新增
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="success" plain icon="Edit" :disabled="single"
                            @click="handleUpdateMaintenanceProject"
                            v-hasPermi="['maintenanceProject:maintenanceProject:edit']">修改
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="Delete" :disabled="multiple"
                            @click="handleDeleteMaintenanceProject"
                            v-hasPermi="['maintenanceProject:maintenanceProject:remove']">删除
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain icon="Download" @click="handleExportWarehouse"
                            v-hasPermi="['maintenanceProject:maintenanceProject:export']">导出
                        </el-button>
                    </el-col> -->
                            <el-col :span="1.5">
                                <el-button type="warning" plain :icon="showSidebar ? 'DArrowLeft' : 'DArrowRight'"
                                    @click="showSidebar = !showSidebar">
                                    {{ showSidebar? "隐藏": "显示" }}侧边栏
                                </el-button>
                            </el-col>
                            <el-col :span="1.5">
                                <el-button type="warning" plain icon="MostlyCloudy"
                                    @click="sidebarSpan < 12 ? sidebarSpan += 3 : sidebarSpan = 6" v-show="showSidebar">
                                    侧边栏比例 {{ sidebarSpan }}:{{ 24 - sidebarSpan }}
                                </el-button>
                            </el-col>
                            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                        </el-row>

                        <el-card shadow="never">
                            <el-table v-loading="loadingMaintenanceProject" :data="maintenanceProjectList">
                                <!-- @selection-change="handleSelectionChange" -->
                                <!-- <el-table-column type="selection" width="40" align="center" /> -->
                                <el-table-column type="expand" width="30">
                                    <template #default="scope">
                                        <div class="padding">
                                            <el-descriptions :column="1">
                                                <el-descriptions-item label="维保">
                                                    <TextTag :options="maintenanceList" column="maintenanceId"
                                                        label="maintenanceName" :value="scope.row.maintenanceId"
                                                        style="display:inline-block" />
                                                </el-descriptions-item>
                                                <el-descriptions-item label="维保项目">
                                                    {{ scope.row.maintenanceProjectName }}
                                                </el-descriptions-item>
                                                <el-descriptions-item label="维保项目标准">
                                                    {{ scope.row.maintenanceProjectStandard }}
                                                </el-descriptions-item>
                                                <el-descriptions-item label="维保项目责任人">
                                                    <TextTag :options="roleList" column="roleId" label="roleName"
                                                        :value="scope.row.maintenanceProjectPersonLiable"
                                                        style="display:inline-block" />
                                                </el-descriptions-item>
                                                <el-descriptions-item label="维保项目周期">
                                                    <dict-tag :options="maintenance_project_cycle"
                                                        :value="scope.row.maintenanceProjectCycle"
                                                        style="display:inline-block" />
                                                </el-descriptions-item>
                                            </el-descriptions>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="序号" align="center" type="index" width="50" />
                                <el-table-column label="维保" align="center" prop="maintenanceId">
                                    <template #default="scope">
                                        <TextTag :options="maintenanceList" column="maintenanceId"
                                            label="maintenanceName" :value="scope.row.maintenanceId" />
                                    </template>
                                </el-table-column>
                                <el-table-column label="维保项目" align="center" prop="maintenanceProjectName"
                                    :show-overflow-tooltip="true" />
                                <el-table-column label="维保项目标准" align="center" prop="maintenanceProjectStandard"
                                    :show-overflow-tooltip="true" />
                                <el-table-column label="维保项目责任人" align="center" prop="maintenanceProjectPersonLiable">
                                    <template #default="scope">
                                        <TextTag :options="roleList" column="roleId" label="roleName"
                                            :value="scope.row.maintenanceProjectPersonLiable" />
                                    </template>
                                </el-table-column>
                                <el-table-column label="维保项目周期" align="center" prop="maintenanceProjectCycle">
                                    <template #default="scope">
                                        <dict-tag :options="maintenance_project_cycle"
                                            :value="scope.row.maintenanceProjectCycle" />
                                    </template>
                                </el-table-column>
                                <el-table-column label="自定义维保项目周期" align="center" prop="maintenanceProjectCycleCustom">
                                    <template #default="scope">
                                        <span v-if="scope.row.maintenanceProjectCycle != 50"></span>
                                        <span v-else>{{ scope.row.maintenanceProjectCycleCustom }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="启用/停用" align="center" prop="maintenanceProjectDepType"
                                    class-name="small-padding fixed-width" fixed="right">
                                    <template #default="scope">
                                        <el-switch v-model="scope.row.maintenanceProjectDepType" active-value="1"
                                            inactive-value="0"
                                            @change="handleMaintenanceProjectCheckedChange(scope.row)">
                                        </el-switch>
                                    </template>
                                </el-table-column>

                                <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200"
                        fixed="right">
                        <template #default="scope">
                            <el-button link type="primary" icon="View" @click="handleView(scope.row)"
                                v-hasPermi="['maintenanceProject:maintenanceProject:query']">详细
                            </el-button>
                            <el-button link type="success" icon="Edit"
                                @click="handleUpdateMaintenanceProject(scope.row)"
                                v-hasPermi="['maintenanceProject:maintenanceProject:edit']">修改
                            </el-button>
                            <el-button link type="danger" icon="Delete"
                                @click="handleDeleteMaintenanceProject(scope.row)"
                                v-hasPermi="['maintenanceProject:maintenanceProject:remove']">删除
                            </el-button>
                        </template>
                    </el-table-column> -->
                            </el-table>
                        </el-card>
                        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                            v-model:limit="queryParams.pageSize" @pagination="getList" />
                    </el-tab-pane>
                </el-tabs>

            </el-col>
        </el-row>

        <!-- 添加或修改维保管理-维保目录对话框 -->
        <el-dialog :title="title" v-model="openMaintenanceDialog" width="500px" append-to-body>
            <el-form ref="maintenanceRef" :model="maintenanceForm" :rules="rules" label-width="80px">
                <el-form-item label="父级维保" prop="parentId" v-if="maintenanceForm.maintenanceId == null">
                    <el-tree-select v-model="maintenanceForm.parentId" :data="maintenanceOptions"
                        :props="{ value: 'maintenanceId', label: 'maintenanceName', children: 'children' }"
                        value-key="maintenanceId" placeholder="请选择父级维保" check-strictly
                        :disable="maintenanceForm.maintenanceId != null" />
                </el-form-item>
                <el-form-item label="维保名称" prop="maintenanceName">
                    <el-input maxlength="100" v-model="maintenanceForm.maintenanceName" placeholder="请输入维保名称" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitIMPAForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 添加或修改维保管理-维保项目对话框 -->
        <el-dialog :title="title" v-model="openMaintenanceProjectDialog" width="500px" append-to-body>
            <el-form ref="maintenanceProjectRef" :model="maintenanceProjectForm" :rules="rules" label-width="120px">
                <el-form-item label="维保" prop="maintenanceId">
                    <el-tree-select v-model="maintenanceProjectForm.maintenanceId" :data="maintenanceOptions"
                        :props="{ value: 'maintenanceId', label: 'maintenanceName', children: 'children' }"
                        value-key="maintenanceId" placeholder="请选择维保" check-strictly />
                </el-form-item>
                <el-form-item label="维保项目" prop="maintenanceProjectName">
                    <el-input maxlength="100" v-model="maintenanceProjectForm.maintenanceProjectName"
                        placeholder="请输入维保项目" />
                </el-form-item>
                <el-form-item label="维保项目标准" prop="maintenanceProjectStandard">
                    <el-input maxlength="300" v-model="maintenanceProjectForm.maintenanceProjectStandard"
                        placeholder="请输入维保项目标准" type="textarea" :rows="4" />
                </el-form-item>
                <el-form-item label="维保项目责任人" prop="maintenanceProjectPersonLiable">
                    <el-select v-model="maintenanceProjectForm.maintenanceProjectPersonLiable" filterable
                        placeholder="请选择维保项目责任人">
                        <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName"
                            :value="item.roleId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="维保项目周期" prop="maintenanceProjectCycle">
                    <el-select v-model="maintenanceProjectForm.maintenanceProjectCycle" filterable
                        placeholder="请选择维保项目周期">
                        <el-option v-for="item in maintenance_project_cycle" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>


            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitMaintenanceProjectForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="maintenanceManage">
import MaintenanceSidebar from "@/components/Maintenance/sidebar"
import MaintenanceDescription from "@/components/Maintenance/description"
import { listMaintenance, delMaintenance, addMaintenance, updateMaintenance } from "@/api/maintenance/maintenance";
import { listMaintenanceProject, getMaintenanceProject, delMaintenanceProject, addMaintenanceProject, updateMaintenanceProject, downloadMaintenanceProject } from "@/api/maintenanceProject/maintenanceProject";
import { listRole } from "@/api/system/role";
import { updateMaintenanceProjectDepType } from "@/api/maintenanceProjectDept/maintenanceProjectDept";


const store = useStore();

const { proxy } = getCurrentInstance();
const { maintenance_project_cycle } = proxy.useDict('maintenance_project_cycle');

const maintenanceProjectList = ref([]);
const roleList = ref([]);
const maintenanceList = ref([]);

const open = ref(false);
const openMaintenanceDialog = ref(false);
const openMaintenanceProjectDialog = ref(false);
const showSidebar = ref(true);
const sidebarSpan = ref(6);

const loadingMaintenanceProject = ref(true);

const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const maintenanceName = ref("");
const maintenanceOptions = ref(undefined);
const maintenance = ref({});
const activeTabName = ref("maintenancePlan");

const data = reactive({
    maintenanceForm: {},
    maintenanceProjectForm: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
    },
    rules: {
        parentId: [
            {
                required: true,
                message: "父级维保不能为空",
                trigger: "blur",
            },
        ],
        maintenanceName: [
            {
                required: true,
                message: "维保名称不能为空",
                trigger: "blur",
            },
        ],
        maintenanceId: [
            {
                required: true, message: "维保编号不能为空", trigger: "blur"
            }
        ],
        maintenanceProjectName: [
            {
                required: true, message: "维保项目不能为空", trigger: "blur"
            }
        ],
        maintenanceProjectStandard: [
            {
                required: true, message: "维保项目标准不能为空", trigger: "blur"
            }
        ],
        maintenanceProjectPersonLiable: [
            {
                required: true, message: "维保项目责任人不能为空", trigger: "blur"
            }
        ],
        maintenanceProjectCycle: [
            {
                required: true, message: "维保项目周期能为空", trigger: "blur"
            }
        ],
    },
});

const { queryParams, form, rules, maintenanceForm, maintenanceProjectForm } = toRefs(data);

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
    if (!value) return true;
    return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选部门树 */
watch(maintenanceName, (val) => {
    proxy.$refs["maintenanceRef"].filter(val);
});

watch(() => maintenance.value, (newValue) => {
    // queryParams.value.maintenanceId = newValue;
    handleQuery();
})


/** 查询部门下拉树结构 */
function getTreeselect() {
    listMaintenance({ pageNum: 1, pageSize: 9999 }).then(response => {
        response.data.map((item) => {
            item.label = `${item.maintenanceName}`;
        });
        maintenanceList.value = response.data;
        maintenanceOptions.value = proxy.handleTree(response.data, "maintenanceId", "parentId");
        //// console.log(maintenanceOptions.value)
    });
}

/** 查询维保管理-维保目录列表 */
function getList() {
    loadingMaintenanceProject.value = true;

    listMaintenanceProject(queryParams.value).then((response) => {
        maintenanceProjectList.value = response.rows;
        total.value = response.total;
        loadingMaintenanceProject.value = false;
    });
}

/** 节点单击事件 */
function handleMaintenanceClick(data) {
    console.log(data)
    if (queryParams.value.maintenanceId == data.maintenanceId) {
        queryParams.value.maintenanceId = null;
    } else {
        queryParams.value.maintenanceId = data.maintenanceId;
    }
    handleQuery();
}
/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

/** 重置操作表单 */
function reset() {
    maintenanceForm.value = {};
    maintenanceProjectForm.value = {};
    proxy.resetForm("userRef");
}
/** 取消按钮 */
function cancel() {
    openMaintenanceDialog.value = false;
    openMaintenanceProjectDialog.value = false;
    reset();
}

/** 新增按钮操作 */
function handleAddMaintenance() {
    reset();
    title.value = "新增维保管理-维保目录";
    openMaintenanceDialog.value = true;
}
/** 修改按钮操作 */
function handleUpdateMaintenance(data) {
    maintenanceForm.value = data;
    openMaintenanceDialog.value = true;
    title.value = "修改维保管理-维保目录";
}
/** 删除按钮操作 */
function handleRemoveMaintenance(node, data) {
    // console.log(node, data);
    proxy.$modal
        .confirm(`是否删除【${data.label}】？`)
        .then(() => {
            delMaintenance(data.maintenanceId).then(() => {
                getTreeselect();
            });
        })
        .catch(() => { });
}
/** 提交按钮 */
function submitIMPAForm() {
    proxy.$refs["maintenanceRef"].validate((valid) => {
        // console.log(valid);
        if (valid) {
            if (maintenanceForm.value.maintenanceId != undefined) {
                updateMaintenance(maintenanceForm.value).then((response) => {
                    proxy.$modal.msgSuccess("修改成功");
                    openMaintenanceDialog.value = false;
                    getTreeselect();
                });
            } else {
                addMaintenance(maintenanceForm.value).then((response) => {
                    proxy.$modal.msgSuccess("新增成功");
                    openMaintenanceDialog.value = false;
                    getTreeselect();
                });
            }
        }
    });
}

// 多选框选中数据
function handleSelectionChange(selection) {
    //// console.log(selection);
    ids.value = selection.map((item) => item.maintenanceProjectId);
    //// console.log(maintenanceProjectIds.value);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAddWarehouse() {
    reset();
    openMaintenanceProjectDialog.value = true;
    title.value = "添加维保管理-维保项目";
}
/** 删除按钮操作 */
function handleDeleteMaintenanceProject(row) {
    // console.log(row.maintenanceProjectId)
    const maintenanceProjectIds = row.maintenanceProjectId || ids.value;
    const maintenanceProjectListFilter = Array.isArray(maintenanceProjectIds)
        ? maintenanceProjectList.value.filter((item) => maintenanceProjectIds.includes(item.maintenanceProjectId))
        : maintenanceProjectList.value.filter((item) => [row.maintenanceProjectId].includes(item.maintenanceProjectId));
    const maintenanceProjectDeleteList = maintenanceProjectListFilter.map((item) => item.maintenanceProjectName);
    proxy.$modal
        .confirm('是否确认删除维保项目为"' + maintenanceProjectDeleteList + '"的数据项？')
        .then(function () {
            return delMaintenanceProject(maintenanceProjectIds);
        })
        .then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
}
/** 修改按钮操作 */
function handleUpdateMaintenanceProject(row) {
    // reset();
    // getTreeselect();
    const maintenanceProjectId = row.maintenanceProjectId || ids.value;
    getMaintenanceProject(maintenanceProjectId).then((response) => {
        maintenanceProjectForm.value = response.data;
        openMaintenanceProjectDialog.value = true;
        title.value = "修改维保管理-维保项目";
    });
}
/** 提交按钮 */
function submitMaintenanceProjectForm() {
    proxy.$refs["maintenanceProjectRef"].validate((valid) => {
        if (valid) {
            if (maintenanceProjectForm.value.maintenanceProjectId != undefined) {
                updateMaintenanceProject(maintenanceProjectForm.value).then((response) => {
                    proxy.$modal.msgSuccess("修改成功");
                    openMaintenanceProjectDialog.value = false;
                    getList();
                });
            } else {
                addMaintenanceProject(maintenanceProjectForm.value).then((response) => {
                    proxy.$modal.msgSuccess("新增成功");
                    openMaintenanceProjectDialog.value = false;
                    getList();
                });
            }
        }
    });
}
/** 导出按钮操作 */
function handleExportWarehouse() {
    downloadMaintenanceProject(queryParams.value);
}


function handleMaintenanceProjectCheckedChange(row) {
    // console.log(row)
    if (row.maintenanceProjectDepType == undefined) {
        return
    }

    let text = row.maintenanceProjectDepType === "0" ? "停用" : "启用";
    proxy.$modal.confirm('确认要"' + text + '"维保项目"' + row.maintenanceProjectName + '"?').then(function () {
        let data = {
            maintenanceProjectId: row.maintenanceProjectId,
            maintenanceProjectDepType: row.maintenanceProjectDepType,
            roleId: row.maintenanceProjectPersonLiable,
        }
        return updateMaintenanceProjectDepType(data);
    }).then(() => {
        proxy.$modal.msgSuccess(text + "成功");
    }).catch(function () {
        row.maintenanceProjectDepType = row.maintenanceProjectDepType === "0" ? "1" : "0";
    });
};

function handleMaintenanceView(data) {
    //// console.log(data)
    queryParams.value.maintenanceId = data.maintenanceId
    maintenance.value = data
    activeTabName.value = "maintenance"
}

function initialData() {
    listRole(proxy.addDateRange({
        pageNum: 1,
        pageSize: 9999,
    }, undefined)).then(response => {
        roleList.value = response.rows;
    });
    getTreeselect();
    getList();
}

onActivated(() => {
    //// console.log("onActivated")
    initialData();
})
onMounted(() => {
    //// console.log("onMounted")
    initialData();
})

</script>


<style lang="scss">
.impa-tree-node {
    width: 90%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    // padding-right: 10px;
    .action {
        display: none;
        margin-right: 10px;
    }

    >.left {
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        // margin-right:20px;
        // max-width: 50%;
    }

    &:hover {
        .action {
            display: flex;
        }
    }
}
</style>