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

        <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="taskName">
                        <div class="screen-item">
                            <el-input v-model="screenForm.taskName" placeholder="请输入路线名称" clearable></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="执行方式" prop="circleType">
                        <div class="screen-item">
                            <el-select v-model="screenForm.circleType" clearable>
                                <template v-for="(item, index) in selectItems['circleType']" :key="index">
                                    <el-option :label="item.value" :value="item.key"></el-option>
                                </template>
                            </el-select>
                        </div>
                    </el-form-item>
                    <el-form-item label="巡检人员" prop="actionUserName">
                        <div class="screen-item">
                            <el-input v-model="screenForm.actionUserName" placeholder="请输入巡检人员" clearable>
                            </el-input>

                        </div>
                    </el-form-item>
                    <el-form-item label="巡检路线" prop="gridAndScenes">
                        <el-cascader :options="scenesTree" v-model="screenForm.gridAndScenes" clearable
                            :show-all-levels="false" filterable :props="lineProps" ref="screenLinesRef">
                        </el-cascader>
                    </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>
            <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="showWorkTimeForm">
                <el-dialog title="工时设置" v-model="showWorkTimeForm" width="600px" center>
                    <el-form :model="currentRow.data" ref="form" :rules="rules" label-width="80px" :inline="false"
                        size="small">
                        <el-form-item label="时薪类型" prop="wageId">
                            <el-select v-model="currentRow.data.wageId" placeholder="" clearable filterable>
                                <!-- <el-option :label="item.value" :value="item.key" v-for="item in selectItems['wageId']" :key="item.key">
                </el-option> -->
                                <template v-for="item in wageTypes" :key="item.id">
                                    <el-option :label="item.name" :value="item.id"> </el-option>
                                </template>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="设定工时" prop="wageHour">
                            <el-input-number v-model="currentRow.data.wageHour" label="" :min="0" :step="0.01"
                                :controls="false" step-strictly :precision="2">
                            </el-input-number>

                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="onSubmit">提交</el-button>
                            <el-button @click="showWorkTimeForm = false">取消</el-button>
                        </el-form-item>
                    </el-form>

                </el-dialog>
            </div>
        </div>
    </div>

   <!-- 优先级设置弹窗 start-->
   <div v-if="showPrioritySet">
    <el-dialog title="优先级设置" width="500px" v-model="showPrioritySet">
      <prioritySetCom
        v-model:updateShowPrioritySet="showPrioritySet"
        :currentRow="currentRow.data"
        @confirmSubmit="handlerPrioritySet"
      />
    </el-dialog>
  </div>
  <!-- 优先级设置弹窗 end-->
</template>
<script setup>
import { ref, reactive, onMounted, nextTick, watch, computed } from 'vue';
import templateHooks from '@/Hooks/templateHooks';
import { patrolTaskService,setPlanTaskOrderService } from '@/ApiService/taskCenterService';
import { dropdownService } from '../../../ApiService/dropdownService';
import TimeSelectCom from '@/Components/taskCenter/timeSelectCom.vue';
import prioritySetCom from "@/Components/taskCenter/taskSet/prioritySetCom.vue";
const isLoaded = ref(false);
const tableLoading = ref(false);
const topScreenRef = ref()
const tableHeight = ref(500)
const showWorkTimeForm = ref(false)
const rules = ref({
    wageId: [
        { required: true, message: '请选择时薪类型', trigger: 'change' }
    ],
    wageHour: [
        { required: true, message: '请输入设定工时', trigger: 'change' }
    ]
})
const showPrioritySet = ref(false); // 优先级设置弹窗
const form = ref()
const districtScreenRef = ref()
const screenLinesRef = 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 wageTypes = ref([])
const fetchParams = computed(() => {
    const { page, rows, sord, sidx } = pageProps
    const { districtId, timeArr, taskName, circleType, actionUserName, status, gridAndScenes } = screenForm
    console.log(gridAndScenes);
    let createTimeStart = '';
    let createTimeEnd = '';
    if (timeArr) {
        createTimeStart = timeArr[0]
        createTimeEnd = timeArr[1]
    } else {
        createTimeStart = ''
        createTimeEnd = ''
    }
    const gridAndSceneNodes = screenLinesRef.value.getCheckedNodes()
    let scene = []
    if (gridAndSceneNodes.length != 0) {
        scene = gridAndSceneNodes.map(item => item.data)
    }
    console.log('scene', scene);
    return {
        districtId, taskName, circleType, actionUserName, status, page, rows, sord, sidx, createTimeStart, createTimeEnd, scene
    }
})
// 数据定义 end
// 优先级设置
const handlerPrioritySet = (data) => {
  console.log(data);
  setPlanTaskOrderService
    .setPlanTaskOrder({
      ...data
    })
    .then((res) => {
      console.log(res);
      if (res.code == 0) {
        fetchData();
        $message.success(res.data);
        showPrioritySet.value = false;
      } else {
        $message.error(res.err);
      }
    });
};
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 = () => {

    patrolTaskService.inspectPlanList(fetchParams.value).then(res => {
        isLoaded.value = true
        if (res.code == 0) {
            tableData.value = res.data.rows
            pageProps.records = res.data.records
        } else {
            $message.error(res.err)
        }
    }, () => {
        isLoaded.value = true
    })
};
// 监听站点变化
const districtChange = (obj) => {
    screenForm.gridAndScenes = null;
    if (obj) {
        fetchScenesTree()
    } else {
        scenesTree.value = []
    }
};

const fetchScenesTree = () => {
    dropdownService.inspectScenesTree({ districtId: screenForm.districtId }).then(res => {
        if (res.code == 0) {
            scenesTree.value = res.data.childNode
        } else {
            $message.error(res.err)
        }
    })
}
const onSubmit = () => {
    form.value.validate(val => {
        if (val) {
            $messageBox.confirm('您确定要进行提交吗？', '提示').then(() => {
                const { id: planId, wageHour, wageId } = currentRow.data
                patrolTaskService.setWageHout({
                    planId,
                    wageHour,
                    wageId
                }).then(res => {
                    if (res.code == 0) {
                        $message.success('设置成功')
                        showWorkTimeForm.value = false
                        fetchData()
                    } 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 fetchWageTypes = () => {
    dropdownService.getDistrictWage({ districtId: currentRow.data.districtId }).then(res => {
        if (res.code == 0) {
            wageTypes.value = res.data
        } else {
            $message.error(res.err)
        }
    })
}
const { $route, $router, $store, $message, $common, $messageBox, screenForm, screenFormRef, selectItems, tableData, tableHeader, currentRow, currentButton, tableButtons, rowButtons, pageProps, buttonsClickFun, pageChange, sortChange, restSearch, clearScreen, } = templateHooks(fetchData);
// 函数定义 end
onMounted(() => {
    buttonsClickFun.data = {
        add: () => { },
        export: () => {
            patrolTaskService.planInspectExport(fetchParams.value)
        },
        workTimeSet: () => {
            if (!currentRow.data.districtId) {
                $message.error('行数据缺少站点ID')
                return
            }
            showWorkTimeForm.value = true
            fetchWageTypes()
        },
        edit: () => { },
        delete: () => { },
        prioritySet: () => {
            // 优先级设置
            showPrioritySet.value = true;
        },
    };
    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]
        fetchDistricts().then(res => {
            fetchData()
            fetchScenesTree()
        })
    })
});
watch(tableButtons, (val) => {
    if ($route.name == "PatrolPlan") {
        nextTick(() => {
            tableHeight.value =
                document.body.clientHeight -
                topScreenRef.value.clientHeight -
                170;
            console.log(tableHeight.value);
        });
    }
});
// 生命周期 end
</script>
<script>
export default {
    name: 'PatrolPlan',
};
</script>