<template>
    <div class='user-manage'>

        <div class='main-container'>
            <qu-search-area ref='topScreenRef' :model='screenForm' @search='restSearch' @reset="clearScreen(screenFormRef, ['timeArr', 'districtId'])">
                    <el-form-item label="查询日期" prop="name">
                        <TimeSelectCom v-model="screenForm.timeArr" clearable></TimeSelectCom>
                    </el-form-item>
                    <el-form-item label="所属站点" prop="districtId">
                        <div class="screen-item">
                            <district-screen v-model:districtId="screenForm.districtId" ref="districtScreenRef"
                                @districtChange="districtChange"></district-screen>
                        </div>
                    </el-form-item>
                    <el-form-item label="任务派单号" prop="no">
                        <div class="screen-item">
                            <el-input v-model="screenForm.no" placeholder="请输入任务派单号" clearable></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="路线名称" prop="name">
                        <div class="screen-item">
                            <el-input v-model="screenForm.name" placeholder="请输入路线名称" clearable></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="巡检人员" prop="modifyId">
                        <div class="screen-item">
                            <el-select v-model="screenForm.modifyId" clearable filterable>
                                <el-option v-for="item in principas" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </div>
                    </el-form-item>
                    <el-form-item label="巡检路线" prop="gridAndScenes">
                        <div class="screen-item">

                            <el-cascader :options="scenesTree" v-model="screenForm.gridAndScenes" filterable clearable
                                :show-all-levels="false" :props="lineProps" ref="screenLinesRef">
                            </el-cascader>
                        </div>
                    </el-form-item>
                    <el-form-item label="巡检状态" prop="isCheck">
                        <div class="screen-item">
                            <el-select v-model="screenForm.isCheck" clearable>
                                <template v-for="(item, index) in selectItems['isCheck']" :key="index">
                                    <el-option :label="item.value" :value="item.key"></el-option>
                                </template>
                            </el-select>
                        </div>
                    </el-form-item>
                    <el-form-item label="是否巡检上报" prop="reportStatus">
                        <div class="screen-item">
                            <el-select v-model="screenForm.reportStatus" clearable>
                                <template v-for="(item, index) in selectItems['reportStatus']" :key="index">
                                    <el-option :label="item.value" :value="item.key"></el-option>
                                </template>
                            </el-select>
                        </div>
                    </el-form-item>
            </qu-search-area>
            <el-skeleton :rows='10' v-if='!isLoaded' :throttle='500' />
            <div class='main-table' v-if='isLoaded'>
                <qu-table :tableData='tableData' v-model:tableHeader='tableHeader' :height='tableHeight'
                    :pageProps='pageProps' :rowButtons='rowButtons' @rowButtonClick='rowButtonClick'
                    @pageChange='pageChange' @sortChange='sortChange' v-loading='tableLoading' showOverflowTooltip
                    :tableButtons='tableButtons' @buttonClick='buttonClick'>
                </qu-table>
            </div>
            <div v-if="showPatrolDetail">
                <el-dialog title="巡检结果详情" v-model="showPatrolDetail" width="700px">
                    <div class="detail-item">
                        <el-descriptions border :column="1">
                            <el-descriptions-item label="巡检结果评分">
                                <el-rate v-model="currentDetail.score" disabled show-score text-color="#ff9900" />
                            </el-descriptions-item>
                            <el-descriptions-item label="">
                                <el-input type="textarea" :rows="4" v-model="currentDetail.content" placeholder=""
                                    :maxlength="500" disabled :show-word-limit="true"
                                    :autosize="{ minRows: 2, maxRows: 4 }">
                                </el-input>

                            </el-descriptions-item>
                            <el-descriptions-item label=""
                                v-if="currentDetail.inspectPicList && currentDetail.inspectPicList.length != 0">
                                <el-scrollbar style="width: 450px;">
                                    <div style="display: flex;">
                                        <el-image style="width: 100px; height: 100px" :src="item.url"
                                            :preview-src-list="currentDetail.inspectPicList.map(item => item.url)"
                                            :initial-index="index" fit="cover" class="scrollbar-item"
                                            v-for="(item, index) in currentDetail.inspectPicList" :key="index" />
                                    </div>

                                </el-scrollbar>
                            </el-descriptions-item>

                        </el-descriptions>
                    </div>
                    <template #footer>
                        <span>
                            <el-button @click="showPatrolDetail = false">取消</el-button>
                        </span>
                    </template>
                </el-dialog>

            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue';
import templateHooks from '@/Hooks/templateHooks';
import { dropdownService } from '@/ApiService/dropdownService';
import { patrolTaskService } from '@/ApiService/taskCenterService';
import TimeSelectCom from '@/Components/taskCenter/timeSelectCom.vue';

const isLoaded = ref(false);
const tableLoading = ref(false);
const topScreenRef = ref()
const tableHeight = ref(500)
const showPatrolDetail = ref(false)
const districtScreenRef = ref()
const principas = ref([])
const scenesTree = ref([])
const lineProps = ref({ expandTrigger: 'hover', multiple: true, checkStrictly: true, value: 'id', label: 'name', children: 'childNode', disabled: 'disable' })
const screenLinesRef = ref()
const currentDetail = ref({})
// 数据定义 end
const buttonClick = (button) => {
    currentButton.data = button;
    buttonsClickFun.data[button.enName]();
};
const rowButtonClick = ({ row, $column }) => {
    for (let i in row) {
        currentRow.data[i] = row[i];
    }
    currentButton.data = $column;
    buttonsClickFun.data[$column.enName]();
};
const fetchData = () => {
    tableLoading.value = true
    const { districtId, no, name, modifyId, timeArr, isCheck, reportStatus } = screenForm
    const { page, rows, sidx, sord } = pageProps
    let createTimeStart = '';
    let createTimeEnd = '';
    if (timeArr) {
        createTimeStart = timeArr[0]
        createTimeEnd = timeArr[1]
    } else {
        createTimeStart = ''
        createTimeEnd = ''
    }
    console.log('screenForm', screenForm);
    const gridAndSceneNodes = screenLinesRef.value.getCheckedNodes()
    console.log(gridAndSceneNodes);
    let gridAndScenes = []
    if (gridAndSceneNodes.length != 0) {
        gridAndScenes = gridAndSceneNodes.map(item => item.data)
    }

    console.log(gridAndScenes);
    patrolTaskService.scenesPageList({
        districtId,
        page, rows, no, name, modifyId, sidx, sord, createTimeStart, createTimeEnd, gridAndScenes, isCheck, reportStatus
    }).then(res => {
        isLoaded.value = true
        tableLoading.value = false
        if (res.code == 0) {
            tableData.value = res.data.rows
            pageProps.records = res.data.records
        } else {
            $message.error(res.err)
        }
    })
};
const { $route, $router, $store, $common, $message, screenForm, screenFormRef, selectItems, tableData, tableHeader, currentRow, currentButton, tableButtons, rowButtons, pageProps, buttonsClickFun, pageChange, sortChange, restSearch, clearScreen, } = templateHooks(fetchData);
const fetchDistricts = () => {
    return new Promise(resolve => {
        districtScreenRef.value.fetchDistricts().then((res) => {
            resolve()
            console.log(res);
            if (res && res.length != 0) {
                screenForm.districtId = res[0].id;
                console.log(typeof screenForm.districtId);
            } else {
                screenForm.districtId = null;
            }

        });
    })
}
// 根据站点获取巡检人员
const fetchPrincipas = () => {
    dropdownService.principalList({ districtId: screenForm.districtId }).then(res => {
        if (res.code == 0) {
            principas.value = res.data
        } else {
            $message.error(res.err)
        }
    })
}
const fetchScenesTree = () => {
    dropdownService.inspectScenesTree({ districtId: screenForm.districtId }).then(res => {
        if (res.code == 0) {
            scenesTree.value = res.data.childNode
        } else {
            $message.error(res.err)
        }
    })
}
// 监听站点变化
const districtChange = (obj) => {
    screenForm.modifyId = null;
    screenForm.gridAndScenes = null;

    if (obj) {
        fetchPrincipas()
        fetchScenesTree()
    } else {
        principas.value = []
        scenesTree.value = []
    }
};
const fetchPatrolDetail = () => {
    patrolTaskService.lookInspectDetail({ id: currentRow.data.id }).then(res => {
        if (res.code == 0) {
            currentDetail.value = res.data
        } else {
            $message.error(res.err)
        }
    })
}
// 函数定义 end
onMounted(() => {
    // 
    fetchDistricts().then(() => {
        const start = new Date()
        const end = new Date();

        const startDateTime = $common.fomatDateTime(start.getTime() - 3600 * 1000 * 24 * 30)
        const endDateTime = $common.fomatDateTime(end.getTime())
        screenForm.timeArr = [startDateTime, endDateTime]
        fetchData();
        fetchPrincipas()
        fetchScenesTree()
    })
    buttonsClickFun.data = {
        add: () => { },
        export: () => {
            const { districtId, no, name, modifyId, timeArr, isCheck, reportStatus } = screenForm
            const { sidx, sord } = pageProps
            let createTimeStart = '';
            let createTimeEnd = '';
            if (timeArr) {
                createTimeStart = timeArr[0]
                createTimeEnd = timeArr[1]
            } else {
                createTimeStart = ''
                createTimeEnd = ''
            }
            const gridAndSceneNodes = screenLinesRef.value.getCheckedNodes()
            console.log(gridAndSceneNodes);
            let gridAndScenes = []
            if (gridAndSceneNodes.length != 0) {
                gridAndScenes = gridAndSceneNodes.map(item => item.data)
            }

            console.log(gridAndScenes);
            patrolTaskService.scenesExport({
                districtId,
                no, name, modifyId, sidx, sord, createTimeStart, createTimeEnd, gridAndScenes, isCheck, reportStatus
            })
        },
        edit: () => { },
        delete: () => { },
        showPatrolDetail: () => {
            if (currentRow.data.isCheck == 0) {
                $message.error('该任务暂未巡检，请巡检后再试')
                return
            }
            showPatrolDetail.value = true
            fetchPatrolDetail()
        }
    };
});
watch(tableButtons, (val) => {
    console.log($route.name);
    if ($route.name == "PatrolTaskList") {
        nextTick(() => {

            tableHeight.value =
                document.body.clientHeight -
                topScreenRef.value.clientHeight -
                170;
        });
    }
});
// 生命周期 end
</script>
<script>
export default {
    name: 'PatrolTaskList',
};
</script>
<style>
.scrollbar-item {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    margin: 10px;
    text-align: center;
    border-radius: 4px;
    background: var(--el-color-danger-light-9);
    color: var(--el-color-danger);
}
</style>