<template>
    <div class="page">
        <headNav title="新增违法占道"></headNav>

        <div class="illegal-container">
            <van-cell-group>
                <van-cell title="记录时间" :value="showDate" />
                <van-cell title="检查人员" :value="userName" />
            </van-cell-group>
            <van-cell-group class="mt10">
                <van-cell class="required" title="车辆类型" is-link :value="formData.vehicle_model_name" @click="showVehicleModelPopup=true" />
                <van-cell class="required" title="车牌号" is-link :value="formData.license_plate_num" @click="onChoosePlateNumber" />
                <van-field v-model="formData.vehicle_owner_name" label="车主姓名" input-align="right" placeholder="请输入车主姓名" />
                <van-field v-model="formData.vehicle_owner_phone" type="tel" label="联系方式" input-align="right" placeholder="请输入联系方式" />
            </van-cell-group>
            <van-cell-group class="mt10">
                <van-cell class="required" title="违法类型" value="占用消防车通道" />
                <van-cell class="required" title="地理位置" is-link :value="`${formData.inspection_location_longitude}, ${formData.inspection_location_latitude}`" @click="showPickerMap" />
                <van-field class="required" v-model="formData.inspection_location" label="检查地点" input-align="right" placeholder="请输入检查地点" />
                <van-cell class="required noLine" title="现场照片">
                    <van-uploader multiple v-model="pictures" preview-size="70" :before-read="beforeRead" :after-read="afterRead" :max-count="9" capture="camera" accept="image/*;" />
                </van-cell>
                <div class="tips">在拍照取证过程中，应对消防车通道警示标识标牌、集中划线包含在照片中，并能清晰的看清车辆车牌号</div>
                <van-cell title="违法行为告知单">
                    <van-uploader v-model="noticeFile" preview-size="70" :max-count="1" :before-read="beforeRead" :after-read="afterRead" />
                </van-cell>
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button block type="info" @click="onSubmit">提交，并发送违法占道短信通知</van-button>
            </div>
        </div>

        <van-popup v-model="showVehicleModelPopup" position="bottom">
            <van-picker
                show-toolbar
                title="选择车辆类型"
                :columns="vehicle_model"
                value-key="v"
                @confirm="onConfirmVehicleModel"
                @cancel="showVehicleModelPopup = false"/>
        </van-popup>

        <van-popup
			v-model="showPlateNumberPopup"
			position="bottom"
			closeable
			close-icon="close"
			style="height: 100%;">
			<keyword v-if="showPlateNumberPopup" @getPlateLicense="onGetPlateLicense"></keyword>
		</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 keyword from '@/components/keyword.vue';

import { dateFormat, isEmpty, notEmpty, isMobile } from '@/utils/tool';
import punishmentMixin from '@/mixins/punishment';
import { getInfo } from '@/utils/auth';
import { Notify } from 'vant';
import Bus from '@/bus';
import { compressAccurately } from 'image-conversion';

export default {
    components: {
        headNav,
        "v-mask": mask_overLay,
        keyword,
    },
    data () {
        return {
            showOverLay: false,
            tipMsg: '加载中',
            formData: {
                license_plate_num: '',
                vehicle_model: '',
                vehicle_model_name: '',
                vehicle_owner_name: '',
                vehicle_owner_phone: '',
                illegal_stop_types: 'OCCUPY',
                inspection_location: '',
                inspection_location_longitude: '',
                inspection_location_latitude: '',
                pictures: '',
                enforce_org_id: '',
                enforce_org_name: '',
                illegal_notice: '',
            },
            pictures: [],
            noticeFile: [],
            showVehicleModelPopup: false,
            showPlateNumberPopup: false,
        }
    },
    computed: {
        showDate() {
            return dateFormat('YYYY-mm-dd HH:MM:SS', new Date());
        },
        userName() {
            const user = getInfo();
            return user ? user.name : '';
        },
    },
    mixins: [punishmentMixin],
    mounted () {
        this.resetFormData();
    },
    methods: {
        resetFormData() {
            this.formData = {
                license_plate_num: '',
                vehicle_model: '',
                vehicle_model_name: '',
                vehicle_owner_name: '',
                vehicle_owner_phone: '',
                illegal_stop_types: 'OCCUPY',
                inspection_location: '',
                inspection_location_longitude: '',
                inspection_location_latitude: '',
                pictures: '',
                enforce_org_id: '',
                enforce_org_name: '',
                illegal_notice: '',
            };
            this.pictures = [];
            this.noticeFile = [];
        },
        onConfirmVehicleModel(data) {
            this.formData.vehicle_model = data.k;
            this.formData.vehicle_model_name = data.v;
            this.showVehicleModelPopup = false;
        },
        onChoosePlateNumber() {
            if (isEmpty(this.formData.vehicle_model)) {
                Notify({ type: 'warning', message: '请选择车辆类型后操作' });
                return
            }
            this.showPlateNumberPopup = true;
        },
        onGetPlateLicense(data) {
            this.formData.license_plate_num = data;
            this.showPlateNumberPopup = false;
            if (notEmpty(data)) {
                this.tipMsg = '查询车牌信息中';
                this.showOverLay = true;
                this.$http.post('/v2/api/data-sync', {
                    search: `[{\"HPZL.eq\":\"${
						this.formData.vehicle_model
					}\"},{\"and.HPHM.eq\":\"${data}\"}]`,
					pageSize: 1,
					pageNum: 1
                }).then(res => {
                    if (res.result.result.length === 0) {
						this.$toast.fail('未查询到该车牌所属车主信息');
					} 
                    else {
						const obj = res.result.result[0];
						if (obj && notEmpty(obj.SYR)) {
							this.$toast.success('查询成功');
							this.formData.vehicle_owner_name = obj.SYR;
							this.formData.vehicle_owner_phone = obj.SJHM;
						}
						else {
							const msg = obj && obj.ZSXXDZ || '查询无结果';
							this.$toast.fail(msg);
						}
					}
					this.showOverLay = false;
                });
            }
        },
		showPickerMap() {
			this.$router.push('/pickPlace');
			const vm = this;
			Bus.$on('changePosition', data => {
				if (data) {
                    vm.formData.inspection_location = data.address;
					vm.formData.inspection_location_longitude = data.point.lng;
					vm.formData.inspection_location_latitude = data.point.lat;
				}
			})
		},
        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;
					// const file = new File([res], new Date().getTime() + '.jpg');
					// console.log('beforeAvatarUpload res: ', file);
					resolve(res);
				});
			});
        },
        afterRead(file) {
            console.log('afterRead: ');
            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;
                    this.uploadFile(file);
				};
			}
            else {
                this.uploadFile(file);
            }
        },
        uploadFile(file) {
            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);
            this.$http.post('/v2/api/file', form).then(res => {
                if (res && res.data && res.data.id) {
                    file.fileID = res.data.id;
                    file.status = 'done';
                    file.message = '';
                }
                else {
                    file.status = 'failed';
                    file.message = '上传失败';
                }
            }).catch(e => {
                file.status = 'failed';
                file.message = '上传失败';
            });
        },
        onSubmit() {
            if (isEmpty(this.formData.vehicle_model_name)) {
                Notify({ type: 'warning', message: '请选择车辆类型' });
                return
            }
            if (isEmpty(this.formData.license_plate_num)) {
                Notify({ type: 'warning', message: '请选择车牌号' });
                return
            }
            if (isEmpty(this.formData.inspection_location_longitude) || isEmpty(this.formData.inspection_location_latitude)) {
                Notify({ type: 'warning', message: '请选择地理位置' });
                return
            }
            if (isEmpty(this.formData.inspection_location)) {
                Notify({ type: 'warning', message: '请输入检查地点' });
                return
            }
            if (!this.pictures || this.pictures.length <= 0) {
                Notify({ type: 'warning', message: '请现场照片' });
                return
            }
            if (notEmpty(this.formData.vehicle_owner_phone) && !isMobile(this.formData.vehicle_owner_phone)) {
                Notify({ type: 'warning', message: '请输入11位手机号码' });
                return
            }
            let pics = [];
            this.pictures.map(item => {
                if (item.fileID) {
                    pics.push(`${item.fileID}`);
                }
            });
            if (pics.length < 4) {
                Notify({ type: 'warning', message: '最少上传四张现场照片' });
                return
            }

            this.tipMsg = '提交中';
            this.showOverLay = true;
            this.formData.pictures = pics.join(',');
            if (this.noticeFile && this.noticeFile.length > 0) {
                let files = [];
                this.noticeFile.map(item => {
                    if (item.fileID) {
                        files.push(`${item.fileID}`);
                    }
                });
                this.formData.illegal_notice = files.join(',');
            }
            this.$http.post('/v2/api/illegal_occupy', this.formData).then(res => {
                console.log('add: ', res);
                this.$toast.success('提交成功');
                this.resetFormData();
                this.showOverLay = false;
                this.$router.back();
            }).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;
    }
    .noLine::after {
        border-bottom: none !important;
    }
    .required {
        .van-cell__title {
            &>span {
                position: relative;
            }
            &>span::after {
                content: '*';
                position: absolute;
                color: #F00;
                font-size: 24px;
                right: -10px;
                top: 0;
            }
        }
    }
}
</style>

<style lang="scss" scoped>
.illegal-container {
    margin-top: 47px;
    height: calc(100vh - 47px);
    overflow-y: auto;
    .tips {
        margin-top: -10px;
        font-size: 12px;
        color: #888888;
        padding: 0 20px 10px;
        position: relative;
    }
    .tips::after {
        position: absolute;
        box-sizing: border-box;
        content: ' ';
        pointer-events: none;
        right: 16px;
        bottom: 0;
        left: 16px;
        border-bottom: 0.02667rem solid #ebedf0;
        transform: scaleY(.5);
    }
    .required {
        position: relative;
    }
}
</style>