<template>
    <div class='user-manage'>
        <!-- <el-skeleton :rows='10' v-if='!isLoaded' :throttle='500' /> -->
        <div class='main-container'>
            <qu-search-area ref='topScreenRef' :model='screenForm' @search='restSearch' @reset="clearScreen(screenFormRef, ['districtId', 'timeArr'])">
                    <el-form-item label="查询日期" prop="timeArr">
                        <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="taskAcceptUser">
                        <div class="screen-item">
                            <el-select v-model="screenForm.taskAcceptUser" clearable filterable>
                                <el-option v-for="item in principas" :key="item.id" :label="item.name"
                                    :value="item.name">
                                </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" clearable filterable
                                :show-all-levels="false" :props="lineProps" ref="screenLinesRef">
                            </el-cascader>

                        </div>
                    </el-form-item>
                    <el-form-item label="任务状态" prop="status">
                        <div class="screen-item">
                            <el-select v-model="screenForm.status" clearable multiple>
                                <template v-for="(item, index) in selectItems['status']" :key="index">
                                    <el-option :label="item.value" :value="item.key"></el-option>
                                </template>
                            </el-select>
                        </div>
                    </el-form-item>
            </qu-search-area>
            <div class='main-table' v-if='isLoaded'>
                <el-card class="box-card">
                    <template #header>
                        <div class="card-header" style="font-size: 14px;">
                            <b>统计查询</b>

                        </div>
                    </template>
                    <div class="text item">
                        <p style="font-size: 14px;"><template v-if="statistics.createTimeStart">统计：查询日期<b>{{
                                statistics.createTimeStart
                        }} </b>至<b>{{ statistics.createTimeEnd }}</b>，</template>路线名称合计<b>{{ statistics.allInspect
}}</b>；应巡合计<b>{{ statistics.shouldInspect
}}</b>；实巡合计<b>{{
        statistics.actualInspect
}}</b>；未巡合计<b>{{ statistics.notInspect }}</b>。
                        </p>
                    </div>
                </el-card>
                <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="showDetail">
                <el-dialog title="任务详情" v-model="showDetail" width="1200px">
                    <patrolTaskDetail :detail="currentTaskDetail"></patrolTaskDetail>
                    <template #footer>
                        <span>
                            <el-button @click="showDetail = false">取消</el-button>

                        </span>
                    </template>
                </el-dialog>

            </div>
            <div v-if="showCancelForm">
                <el-dialog title="取消任务" v-model="showCancelForm" width="30%">
                    <el-form :model="cancelForm" ref="form" :rules="rules" label-width="80px" :inline="false"
                        size="small">
                        <el-form-item label="取消原因" prop="id">
                            <el-select v-model="cancelForm.id" value-key="" placeholder="" clearable filterable>
                                <el-option v-for="item in cancelReasonList" :key="item.id" :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="详细原因" prop="detailReason" v-if="cancelForm.id == 3">
                            <el-input type="textarea" :rows="4" v-model="cancelForm.detailReason" placeholder=""
                                :maxlength="500" :show-word-limit="true" :autosize="{ minRows: 2, maxRows: 4 }">
                            </el-input>

                        </el-form-item>


                    </el-form>

                    <template #footer>
                        <span>
                            <el-button @click="showCancelForm = false">取消</el-button>
                            <el-button type="primary" @click="cancel">确认</el-button>
                        </span>
                    </template>
                </el-dialog>

            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, nextTick, watch, computed } from 'vue';
import templateHooks from '@/Hooks/templateHooks';
import { patrolTaskService } from '@/ApiService/taskCenterService'
import patrolTaskDetail from '@/Components/taskCenter/patrolTask/patrolTaskDetail.vue';
import { dropdownService } from '../../../ApiService/dropdownService';
import TimeSelectCom from '@/Components/taskCenter/timeSelectCom.vue';
const fetchParams = computed(() => {
    const { districtId, no, name, taskAcceptUser, status, timeArr, gridAndScenes: scenes } = screenForm
    const { page, rows, 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)
    }
    return {
        districtId,
        page, rows, no, name, taskAcceptUser, status, sidx, sord, createTimeStart, createTimeEnd, gridAndScenes
    }
})
const fetchData = () => {
    fetchStaticsData()
    tableLoading.value = true
    patrolTaskService.pageList(fetchParams.value).then(res => {
        tableLoading.value = false
        isLoaded.value = true;
        if (res.code == 0) {
            tableData.value = res.data.rows
            pageProps.records = res.data.records
        } else {
            $message.error(res.err)
        }
    }, err => {
        tableLoading.value = false
        isLoaded.value = true;
    })
};
const fetchStaticsData = () => {

    patrolTaskService.statistics(fetchParams.value).then(res => {
        if (res.code == 0) {
            statistics.value = res.data
        } else {
            $message.error(res.err)
        }
    })
}
const { $route, $router, $store, $message, $messageBox, $common, screenForm, screenFormRef, selectItems, tableData, tableHeader, currentRow, currentButton, tableButtons, rowButtons, pageProps, buttonsClickFun, pageChange, sortChange, restSearch, clearScreen, shortcuts } = templateHooks(fetchData);
const isLoaded = ref(false);
const tableLoading = ref(false);
const topScreenRef = ref()
const tableHeight = ref(500)
const showDetail = ref(false)
const showCancelForm = ref(false)
const form = ref()
const rules = ref({
    id: [
        { required: true, message: '请选择取消原因', trigger: 'change' },
    ],
    detailReason: [
        { required: true, message: '请输入详细原因', trigger: 'change' }
    ]
})
const districtScreenRef = ref()
const principas = ref([])
const scenesTree = ref([])
const currentTaskDetail = ref({})
const cancelReasonList = ref([])
const cancelForm = ref({
    id: '',
    detailReason: ''
})
const lineProps = ref({ expandTrigger: 'hover', multiple: true, checkStrictly: true, value: 'id', label: 'name', children: 'childNode', disabled: 'disable' })
const screenLinesRef = ref()
const statistics = 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 districtChange = (obj) => {

    screenForm.taskAcceptUser = null;
    screenForm.gridAndScenes = null;

    if (obj) {
        fetchPrincipas()
        fetchScenesTree()
    } else {
        principas.value = []
        scenesTree.value = []
    }
};
// 获取任务详情
const fetchTaskDetail = () => {
    patrolTaskService.look({ id: currentRow.data.id }).then(res => {
        if (res.code == 0) {
            currentTaskDetail.value = res.data
        } else {
            $message.error(res.err)
        }
    })
}
// 根据站点获取巡检人员
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 cancel = () => {
    form.value.validate(val => {
        if (val) {
            $messageBox.confirm('您确定要进行提交吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消' }).then(_r => {
                console.log(_r);
                const { id, detailReason } = cancelForm.value
                let cancelReason = ''
                cancelReasonList.value.map(item => {
                    if (item.id == id) {
                        cancelReason = item.name
                    }
                })
                patrolTaskService.cancel({
                    id: currentRow.data.id, cancelReason, detailReason
                }).then(res => {
                    if (res.code == 0) {
                        $message.success('取消成功')
                        fetchData()
                        showCancelForm.value = false
                    } else {
                        $message.error(res.err)
                    }
                })
            })
        } else {
            return false
        }
    })
}
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 fetchCancelList = () => {
    dropdownService.getTaskCancelReason().then(res => {
        if (res.code == 0) {
            cancelReasonList.value = res.data
        } else {
            $message.error(res.err)
        }
    })
}
// 函数定义 end
onMounted(() => {

    buttonsClickFun.data = {
        add: () => { },
        export: () => {
            patrolTaskService.export(fetchParams.value)
        },
        edit: () => { },
        delete: () => { },
        showDetail: () => {
            showDetail.value = true
            fetchTaskDetail()
        },
        cancel: () => {
            if (currentRow.data.status != 4) {
                $message.error('当前状态不支持此操作')
                return
            }
            showCancelForm.value = true
            cancelForm.value = {
                id: '',
                detailReason: ''
            }
        }
    };
    nextTick(() => {
        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]
        fetchCancelList()
        fetchDistricts().then(res => {
            fetchData()
            fetchPrincipas()
            fetchScenesTree()
        })
    })
});
watch(tableButtons, (val) => {
    console.log($route.name);
    if ($route.name == "PatrolTask") {
        nextTick(() => {

            tableHeight.value =
                document.body.clientHeight -
                topScreenRef.value.clientHeight -
                320;
        });
    }
});

// 生命周期 end
</script>
<script>
export default {
    name: 'PatrolTask',
};
</script>