<template>
    <div>
        <headNav :Larrow="false" title="地图"></headNav>

        <div class="container">
            <div class="map" id="map"></div>
            <div class="content">
                <div class="title">任务执行路线规划</div>
                <div class="row date" @click="showChooseDate = true">
                    <span>{{showDate}}</span>
                    <van-icon name="arrow" />
                </div>
                <div class="row">
                    <div class="info">
                        <span>今日任务：{{taskInfo.count}}条</span>
                        <span>任务时长：{{taskInfo.time}}</span>
                        <span>通勤时长：{{taskInfo.work}}</span>
                    </div>
                    <div class="process">
                        <van-progress stroke-width="6" :percentage="taskInfo.percent" />
                    </div>
                </div>
                <div class="list">
                    <van-steps direction="vertical" finish-icon="stop" active-icon="location-o" :active="-1">
                        <template v-for="row in list">
                            <van-step :key="row.id">
                                <div class="list-title">{{row.enforce_obj_name}}</div>
                                <div class="list-info">
                                    <span :class="row.statusColor">{{row.statusDesc}}</span>
                                    <span v-if="row.job_status == 'ARCHIVED'">使用时长：{{row.jobTime}}</span>
                                    <span v-else>预计时长：{{row.jobTime}}</span>
                                </div>
                            </van-step>    
                        </template>
                    </van-steps>
                </div>
            </div>
        </div>

        <van-popup v-model="showChooseDate" position="bottom">
          <van-datetime-picker
            v-model="date"
            type="date"
            title="选择日期"
            :min-date="minDate"
            :max-date="maxDate"
            @cancel="showChooseDate = false"
            @confirm="onConfirmDate"
          />
        </van-popup>
        
        <v-mask :showOverLay="showOverLay"></v-mask>
    </div>
</template>

<script>
import headNav from '@/components/headNav.vue';
import mask_overLay from "@/components/overLay_xy.vue";
import { formatYYYYMMDD } from '@/utils/tool';
import { get } from '@/utils/http.js';
import { getInfo } from '@/utils/auth';

export default {
    components: {
        headNav,
        "v-mask": mask_overLay,
    },
    data () {
        return {
            showOverLay: false,
            minDate: new Date(2000, 0, 1),
            maxDate: new Date(2050, 10, 1),
            date: new Date(),
            showChooseDate: false,
            taskInfo: {
                count: 0,
                time: 0,
                work: 0,
                percent: 0,
            },
            query: {
                page: 1,
                size: 10,
                sort: 'create_time desc',
            },
            finishList: [],
            otherList: [],
            map: null,
            locationResp: null,
            marker: null,
        }
    },
    computed: {
        showDate() {
            if (this.date) {
                return formatYYYYMMDD(this.date);
            }
            return '';
        },
        userInfo() {
            return getInfo();
        },
        list() {
            return [...this.finishList, ...this.otherList];
        },
    },
    mounted () {
        this.initMap();
    },
    methods: {
        initMap () {
            // eslint-disable-next-line no-undef
            const map = new AMap.Map('map', {
                resizeEnable: true,
                zoom: 10,
                center: [106.504962,29.533155],
            });
            this.marker = new AMap.Marker({
                map: map,
                icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
            });
            this.map = map;
            const scale = new AMap.Scale({
                visible: true
            });
            const toolBar = new AMap.ToolBar({
                visible: true
            });
            map.addControl(scale);
            map.addControl(toolBar);

            this.loadTask();

            // if (window.FireJS) {
            //     const vm = this;
            //     window.setLocation = function(res) {
            //         if (res) {
            //             const json = JSON.parse(res);
            //             console.log('json: ', json);
            //             vm.locationResp = json;
            //             const position = new AMap.LngLat(json.poi.lon, json.poi.lat);
            //             setTimeout(() => {
            //                 vm.map.setCenter(position);
            //                 vm.marker.setPosition(position);
            //             }, 1000);
            //         }
            //         else {
            //             vm.locationFail();
            //         }
            //     }
            //     window.FireJS.location();
            // }
            // else {
            //     const vm = this;
            //     AMap.plugin('AMap.Geolocation', function() {
            //         const geolocation = new AMap.Geolocation({
            //             enableHighAccuracy: true,
            //             timeout: 10000,
            //             buttonOffset: new AMap.Pixel(10, 20),
            //             zoomToAccuracy: true,
            //             buttonPosition: 'RB'
            //         })

            //         geolocation.getCurrentPosition()
            //         AMap.event.addListener(geolocation, 'complete', onComplete)
            //         AMap.event.addListener(geolocation, 'error', onError)

            //         function onComplete (data) {
            //             console.log('location complete: ', data);
            //             if (data) {
            //                 this.locationResp = {
            //                     address: data.formattedAddress,
            //                     current: {
            //                         address: data.formattedAddress,
            //                         lat: data.position.lat,
            //                         lon: data.position.lon,
            //                         info: data
            //                     },
            //                     poi: data.position,
            //                 }
            //                 const position = new AMap.LngLat(data.position.lon, data.position.lat);
            //                 vm.map.setCenter(position);
            //                 vm.marker.setPosition(position);
            //                 vm.locationSuccess();
            //             }
            //         }

            //         function onError (err) {
            //             console.log('location err: ', err);
            //             vm.locationFail();
            //         }
            //     })
            // }
        },
        locationFail() {
            this.$toast.fail("定位失败，请检查是否开启定位功能或者网络");
        },
        locationSuccess() {
            if (!this.otherList || this.otherList.length <= 0) {
                return
            }

            if (!this.userInfo) {
                return
            }

            // if (!this.locationResp) {
            //     return
            // }

            let res = [];
            this.otherList.map(item => {
                res.push(new AMap.LngLat(parseFloat(item.enforce_obj.longitude), parseFloat(item.enforce_obj.latitude)));
            });

            const enforceObj = this.userInfo.enforce_org_detail;
            const start = new AMap.LngLat(parseFloat(enforceObj.longitude),parseFloat(enforceObj.latitude));
            const map = this.map;
            const vm = this;
            AMap.plugin('AMap.Driving', function() {
                const driving = new AMap.Driving({
                    map: map,
                    policy: AMap.DrivingPolicy.LEAST_TIME,
                }); 
                // 根据起终点经纬度规划驾车导航路线
                driving.search(start, start,{
                    waypoints:res,
                }, function(status, result) {
                    if (status === 'complete' && result && result.routes && result.routes.length > 0) {
                        console.log('绘制驾车路线完成')
                        let time = result.routes[0].time;
                        time = vm.formatTaskTime(time/60);
                        vm.taskInfo.work = time;
                    } else {
                        console.log('获取驾车数据失败：' + result)
                    }
                });
            });
        },
        onConfirmDate() {
            this.showChooseDate = false;
            this.loadTask();
        },
        computeTaskTime(item) {
            if (item.job_status == 'ARCHIVED' && item.start_time && item.finish_time) {
                let dis = (new Date(item.finish_time) - new Date(item.start_time)) / 1000;
                if (dis < 60) {
                    return `${dis} 秒`;
                }
                dis = dis / 60;
                return this.formatTaskTime(dis);
            }

            if (item.item_sum && item.item_sum > 0) {
                let count = 3 * parseInt(item.item_sum);
                return this.formatTaskTime(count);
            }

            return '30 分钟';
        },
        formatTaskTime(minute) {
            if (minute >= 60) {
                return (minute / 60).toFixed(1) + ' 小时';
            }
            return `${parseInt(minute)} 分钟`;
        },
        loadTask() {
            this.showOverLay = true;
            let query = [];
            if (this.userInfo) {
                query.push(`executor_ids==*${this.userInfo.uid}*`);
            }
            if (this.showDate) {
                query.push('last_enforce_date==' + this.showDate);
            }
            this.query.query = query.join(';');
            get("/v2/api/enforce-job", this.query).then(res => {
                const data = res.data || [];
                let finished = [], other = [];
                data.map(item => {
                    let status = '待执行';
                    let color = 'FontColorWarn';
                    if (item.job_status) {
                        if (item.job_status == 'TODO') {
                            status = '执行中';
                            color = 'FontColorOther';
                        }
                        if (item.job_status == 'ARCHIVED') {
                            status = '已完成';
                            color = 'FontColorSuccess';
                        }
                    }
                    item.statusColor = color;
                    item.statusDesc = status;
                    item.jobTime = this.computeTaskTime(item);
                    if (item.job_status && item.job_status == 'ARCHIVED') {
                        finished.push(item);
                    }
                    else {
                        other.push(item);
                    }
                });
                this.finishList = finished;
                this.otherList = other;
                this.loadProcessRate();
                this.locationSuccess();
            });
        },
        loadProcessRate() {
            get('/v2/api/enforce-job/progress-rate', this.query).then(res => {
                this.taskInfo.count = res && res.job_sum || '0';
                this.taskInfo.time = res.cost;//this.formatTaskTime(res && res.cost || 0);
                this.taskInfo.percent = parseFloat(res && res.progress_rate || 0) * 100;
                this.showOverLay = false;
            });
        },
    }
}
</script>

<style lang="scss">
.list {
    .van-step--vertical:not(:last-child)::after {
        border-bottom: none;
    }
}
.content {
    .van-cell::after {
        border-bottom: none;
    }
}
</style>

<style lang="scss" scoped>
.container {
    margin-top: 47px;
    width: 100%;
    height: calc(100vh - 47px - 49px);
    overflow-y: auto;
}
.map {
    width: 100%;
    height: 400px;
}
.content {
    width: 100%;
    position: relative;
    background-color: #FFFFFF;
    .title {
        width: 100%;
        text-align: center;
        font-size: 18px;
        font-weight: bolder;
        padding: 8px 0;
    }
    .row {
        font-size: 16px;
        padding: 0 16px;
    }
    .date {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .info {
        color: #686868;
        margin-top: 8px;
        font-size: 12px;
        &>span {
            margin-right: 8px;
        }
    }
    .process {
        margin-top: 10px;
    }
    .list {
        margin-top: 14px;
        &-title {
            font-size: 14px;
            font-weight: bold;
            color: #343435;
        }
        &-info {
            font-size: 12px;
            &>span:last-child {
                margin-left: 14px;
            }
        }
    }
}
</style>