<template>
    <div class="page">
        <headNav :title="title"></headNav>

        <div class="illegal-container" v-if="formData">
            <van-cell-group>
                <van-cell title="车牌号" :value="formData.license_plate_num" />
                <van-cell title="违法类型" value="占用消防车通道" />
                <van-cell title="检查时间" :value="formData.examTime" />
                <van-cell title="检查人员" :value="formData.create_user_name" />
                <van-cell class="font-pace" title="检查地址" center :value="formData.inspection_location" @click="onShowMap">
                    <template #right-icon>
                        <van-icon name="location-o" color="#02A7F0" />
                    </template>
                </van-cell>
                <van-cell title="现场照片">
                    <div class="pics">
                        <template v-for="(url, index) in formData.pictureList">
                            <van-image class="pics-item" :key="index" width="80" height="80" :src="url" @click="onPreviewImage(index)" />
                        </template>
                    </div>
                </van-cell>
            </van-cell-group>
            <van-cell-group class="mt10">
                <van-cell title="车主姓名" :value="formData.vehicle_owner_name" />
                <van-cell title="联系方式" :value="formData.vehicle_owner_phone" />
                <van-cell title="违法状态">
                    <span :class="formData.statusColor">{{formData.statusDesc}}</span>
                </van-cell>
            </van-cell-group>
            <van-cell-group title="违法告知">
                <van-cell title="短信通知" is-link value="已发送" @click="showMessage(1)" />
                <van-cell v-if="formData.illegal_notice > 0" is-link title="违法行为告知单" value="已上传" @click="showFile(1)" />
                <van-cell v-else title="违法行为告知单">
                    <van-uploader name="notice" v-model="noticeFile" preview-size="70" :max-count="1" :before-read="beforeRead" :after-read="afterRead" />
                </van-cell>
            </van-cell-group>
            <div class="tips">
                <div>对于实施停车违法嫌疑人在规定时间内通知到场，到场对违法事实无异议，责令改正后，自主移离车辆；消除消防违法行为</div>
            </div>
            <van-cell-group title="简易处罚">
                <template v-if="formData.move_result">
                    <van-cell class="font-pace" title="移离情况" @click="onPickerMoveStatus">
                        <div v-if="formData.move_result == 'MOVED'" class="FontColorSuccess">规定时限内移离车辆，不进行处罚</div>
                        <div v-else class="FontColorError">规定时限内未移离车辆，简易处罚并通知</div>
                    </van-cell>
                </template>
                <template v-else>
                    <van-cell v-if="noticeTime" title="处罚计时">
                        <span class="time FontColorError">{{noticeTime}}</span>
                    </van-cell>
                    <van-cell v-else title="处罚计时">
                        <span class="FontColorError">已超过规定时限</span>
                    </van-cell>
                    <van-cell title="移离情况" is-link @click="onPickerMoveStatus">
                        <span class="FontColorOther">待确定</span>
                    </van-cell>
                </template>
                <template v-if="formData.move_result == 'UN_MOVED'">
                    <van-cell title="短信通知" is-link value="已发送" @click="showMessage(2)" />
                    <van-cell v-if="formData.simple_penalty_decision > 0" is-link title="简易处罚决定书" value="已上传" @click="showFile(2)" />
                    <van-cell v-else title="简易处罚决定书">
                        <van-uploader name="simple" v-model="simpleFile" preview-size="70" :max-count="1" :before-read="beforeRead" :after-read="afterRead" />
                    </van-cell>
                </template>
            </van-cell-group>

            <div class="space"></div>
        </div>

        <van-popup
            v-model="showMap"
            position="bottom"
            @click-overlay="showMap = false">
            <div v-if="showMap">
                <baiduMap :coor="coor" :zoom="zoom"></baiduMap>
            </div>
        </van-popup>

        <v-mask :showOverLay="showOverLay" :tipMsg="tipMsg"></v-mask>
    </div>
</template>

<script>
import headNav from '@/components/headNav.vue';
import mask_overLay from "@/components/overLay_xy.vue";
import baiduMap from "@/components/baiduMap.vue";

import { dateFormat, notEmpty } from '@/utils/tool';
import punishmentMixin from '@/mixins/punishment';
import { get, put } from '@/utils/http.js';
import { handleProblemImgs } from '@/utils/index';
import { ImagePreview } from 'vant';
import { compressAccurately } from 'image-conversion';

export default {
    components: {
        headNav,
        "v-mask": mask_overLay,
        baiduMap,
    },
    data () {
        return {
            showOverLay: false,
            tipMsg: '加载中',
            formData: null,
            noticeFile: [],
            simpleFile: [],
            noticeTime: null,
            doTimeInterval: null,
            showMap: false,
            coor: {
                lat: 106.504962,
                lng: 29.533155,
            },
            zoom: 12,
        }
    },
    computed: {
        id() {
            return this.$route.params.id + '';
        },
        title() {
            let t = '违法占道详情';
            if (this.formData) {
                const s = this.parseStatus(this.formData.processing_status);
                t += `（${s}）`;
            }
            return t;
        },
    },
    mixins: [punishmentMixin],
    mounted () {
        if (notEmpty(this.id)) {
            this.loadDetail();
        }
    },
    methods: {
        loadDetail() {
            this.showOverLay = true;
            get(`/v2/api/illegal_occupy/${this.id}`).then(res => {
                res.examTime = dateFormat('YYYY-mm-dd HH:MM:SS', new Date(res.inspection_time));
                res.statusDesc = this.parseStatus(res.processing_status);
                res.statusColor = 'FontColorSuccess';
                if (res.processing_status == 'NOTICED') {
                    res.statusColor = 'FontColorWarn';
                }
                if (res.processing_status == 'PUNISHMENTED') {
                    res.statusColor = 'FontColorError';
                }
                let pics = [];
                res.pictures.split(',').map(id => {
                    pics.push(handleProblemImgs(id));
                });
                res.pictureList = pics;
                // res.inspection_time = new Date().toString();
                this.formData = res;
                this.handleNoticeTime();
                this.showOverLay = false;
            });
        },
        formatNum(num) {
            if (num > 9) {
                return `${num}`;
            }
            return `0${num}`;
        },
        handleNoticeTime() {
            const item = this.formData;
            let str = null;
            if (item.processing_status == 'NOTICED' && item.inspection_time) {
                const dis = 300 - parseInt((new Date() - new Date(item.inspection_time)) / 1000);
                if (dis > 0) {
                    const m = parseInt(dis / 60);
                    const s = parseInt(dis % 60);
                    str = this.formatNum(m) + ':' + this.formatNum(s);
                }
            }
            this.noticeTime = str;

            if (str) {
                if (!this.doTimeInterval) {
                    this.doTimeInterval = setInterval(() => {
                        this.handleNoticeTime();
                    }, 1000);
                }
            }
            else if (this.doTimeInterval) {
                clearInterval(this.doTimeInterval);
            }
        },
        onShowMap() {
            const item = this.formData;
            this.coor = {
                lng: 106.504962,
                lat: 29.533155,
            };
            if (item.inspection_location_latitude && item.inspection_location_longitude) {
                this.coor = {
                    lng: parseFloat(item.inspection_location_longitude),
                    lat: parseFloat(item.inspection_location_latitude),
                }
            }
            this.showMap = true;
        },
        onPreviewImage(index) {
            ImagePreview({
                images: this.formData.pictureList,
                startPosition: index,
            });
        },
        beforeRead(file) {
            console.log('beforeRead');
            const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
			if (!isJpgOrPng) {
				this.$toast.fail("图片只能是 JPG 或 PNG 格式!");
				return false;
			}
			this.showOverLay = true;
			this.tipMsg = '图片处理中';
			return new Promise((resolve) => {
				compressAccurately(file, {
					size: 100, //图片大小压缩到100kb
					width: 1280, //宽度压缩到1280
				})
				.then((res) => {
					this.showOverLay = false;
					resolve(res);
				});
			});
        },
        afterRead(file, params) {
            console.log('afterRead: ', params);
            if (file && file.file && file.file.size > 2000000) {
				let canvas = document.createElement('canvas');
				let context = canvas.getContext('2d');
				let img = new Image();
				img.src = file.content;

                const vm = this;
				img.onload = () => {
					canvas.width = img.width;
					canvas.height = img.height;
					context.drawImage(img, 0, 0, img.width, img.height);
					let base_img = canvas.toDataURL(file.file.type, 0.75);
					const blodBin = atob(base_img.split(',')[1]);
					let data = [];
					for (let i = 0; i < blodBin.length; i++) {
						data.push(blodBin.charCodeAt(i));
					}
					let blob1 = new Blob([new Uint8Array(data)], { type: 'image/jpeg' });
					let file1 = new File([blob1], new Date().getTime() + '.jpg');
					file.file = file1;
                    vm.uploadFile(file, params);
				};
			}
            else {
                this.uploadFile(file, params);
            }
        },
        uploadFile(file, params) {
            file.status = 'uploading';
            file.message = '上传中...';
            const name = file.file.name ? file.file.name : (new Date().getTime() + '.jpg');
            const form = new FormData();
            form.append('fileName', name);
            form.append('fileBinary', file.file);
            const vm = this;
            this.$http.post('/v2/api/file', form).then(res => {
                if (res && res.data && res.data.id) {
                    file.fileID = res.data.id;
                    vm.onSubmit(file, params);
                }
                else {
                    file.status = 'failed';
                    file.message = '上传失败';
                }
            }).catch(e => {
                file.status = 'failed';
                file.message = '上传失败';
            });
        },
        showMessage(type) {
            this.$router.push(`/carList/message/${this.id}/${type}`);
        },
        showFile(type) {
            const fileId = type == 1 ? this.formData.illegal_notice : this.formData.simple_penalty_decision;
            let date = type == 1 ? this.formData.illegal_notice_time : this.formData.simple_penalty_time;
            if (fileId > 0) {
                date = date ? dateFormat('YYYY-mm-dd HH:MM:SS', new Date(date)) : '-';
                this.$router.push(`/carList/file/${fileId}/${type}/${date}`);
            }
        },
        onPickerMoveStatus() {
            this.$router.push(`/carList/move/${this.id}`);
        },
        onSubmit(file, params) {
            const name = params && params.name;
            const obj = name == 'notice' ? { illegal_notice: file.fileID } : { simple_penalty_decision: file.fileID };
            put(`/v2/api/illegal_occupy/${this.id}`, obj).then(res => {
                console.log('put: ', res);
                this.formData.illegal_notice = file.fileID;
                file.status = 'done';
                file.message = '';
                this.loadDetail();
            }).catch(e => {
                this.showOverLay = false;
            });
        },
    },
}
</script>

<style lang="scss">
.illegal-container {
    .van-cell__title {
        flex: 0;
        width: 100px;
        min-width: 100px;
        color: #666666;
    }
    .van-cell__value {
        color: #343434;
        font-size: 14px;
    }
    .font-pace {
        .van-cell__title {
            width: 90px;
            min-width: 90px;
        }
    }
}
</style>

<style lang="scss" scoped>
.illegal-container {
    margin-top: 47px;
    height: calc(100vh - 47px);
    overflow-y: auto;
    .pics {
        overflow-x: auto;
        &-item {
            min-width: 80px;
        }
        &-item:not(:first-child) {
            margin-left: 10px;
        }
    }
    .tips {
        padding: 10px 15px;
        font-size: 12px;
        color: #999;
        &>div {
            padding: 3px 5px;
            background: #ebf5ff;
        }
    }
    .time {
        font-size: 28px;
        color: #F00;
    }
    .space {
        width: 100%;
        height: 20px;
        min-height: 20px;
    }
}
</style>