<template>
    <div class="container">
        <div v-show="isPhotoOrsize == '图片'"> 
            <div style="padding: 20px 0;">合并签收以下快件:</div>
            <van-form @submit="onSubmit">
                <van-field name="checkboxGroup">
                    <template #input>
                        <van-checkbox-group v-model="checkboxGroup">
                            <van-checkbox disabled style="margin-bottom: 10px;" :name="item.id" shape="square"
                                v-for="item in goodsList" :key="item.id"> {{ item.expressNo }} & {{ item.expressType
                                }} & {{ item.expressQuantity }}件 &{{ item.isPayOnDelivery == '否' ? '非到付' : '到付' }}
                            </van-checkbox>
                        </van-checkbox-group>
                    </template>
                </van-field>

                <van-field readonly clickable name="shelfInformation" label="上传照片或签字板" lable-width="1000px" :value="currentSelect"
                        placeholder="请选择照片或签字板" @click="isShelf = true" :rules="[{ required: true }]" />

                <van-popup v-model="isShelf" position="bottom">
                    <van-picker title="标题" show-toolbar :columns="shelfs" @confirm="onConfirm" @cancel="onCancel" />
                </van-popup>

                <div v-if="currentSelect == '签字板'" style="display: flex;justify-content: flex-start;">
                    <span style="margin-left: 0.4rem; margin-right: 1rem;">签字版图片：</span>
                    <van-image  width="2rem" height="2rem" fit="contain" :src="canvasPhotoIMG"/>
                </div>

                <div v-if="currentSelect == '图片'">
                    <van-field name="uploader" label="上传照片"  :rules="[{ required: true, message: '请上传图片' }]">
                            <template #input>
                                <van-uploader   multiple    :deletable="true"  
                                @delete="onDelete" v-model="uploader" :after-read="afterRead" :before-read="beforeRead" :max-count="1" />
                            </template>
                    </van-field>
                </div>
               
            

                <div>
                    <van-button style="height: 40px; width: 150px; border-radius: 8px; margin-right: 20px;" type="info"
                    native-type="submit">确定签收</van-button>

                    <van-button style="height: 40px; width: 150px; border-radius: 8px;" type="default"
                        @click="back">返回上一级</van-button>
                </div>
                <!-- <van-image class="batch-middel-text-style" width="100" height="100" :src="aaa" /> -->
                
            </van-form>
        </div>

      

        
        <div v-show="isPhotoOrsize == '签字板'">
            <canvas ref="canvas"  
                :width="width"  
                :height="height"  
                @mousedown="startDrawing"  
                @mouseup="stopDrawing"  
                @mousemove="draw"  
                @mouseout="stopDrawing"  
                @touchstart="startDrawing"  
                @touchend="stopDrawing"  
                @touchmove="drawTouch" style="border: 1px solid;" ></canvas>
            <van-button type="default" native-type="button" @click="canvasClose">取消</van-button>
            <van-button type="default" native-type="button" @click="clearCanvas">重写</van-button>
            <van-button type="default" native-type="button" @click="saveSignature" >确定</van-button>
        </div>
    </div>
</template>

<script>
import { appDelivery, appUploadTheSignature } from '@/api/index'
import axios from 'axios';
export default {
    name: 'sureCombine',
    props: ['isCombine', 'goodsList'],
    data() {
        return {
            checkbox: false,
            checkboxGroup: [],
            uploader: [],//图片
            isShelf:false,
            isPhotoOrsize:'图片',//控制展示
            currentSelect:'',
            shelfs:['图片', '签字板'],
            isDrawing: false,  
            hasContent: false,
            context: null,  
            lastX: 0,  
            lastY: 0,  
            width: window.innerWidth - 24,  
            height:  window.innerHeight - 100, 
            photoIMG:'',//储存展示图片
            canvasPhotoIMG:'',//展示图片
            hasUploadedImage: false, // 标记是否已上传图片  
        };
    },
    
    mounted() {
        document.addEventListener('touchmove', this.disabledMove, { passive: false })
        this.initCanvas();
        // 在组件挂载后，设置默认选中的值  
        this.checkboxGroup = this.goodsList.map(item => item.id);
    },
    beforeDestroy(){
        document.removeEventListener('touchmove', this.disabledMove)
    },
    methods: {
        disabledMove(e){
            e.preventDefault();
        },
        initCanvas() {  
            const canvas = this.$refs.canvas;  
            this.context = canvas.getContext('2d');  
            this.context.strokeStyle = '#000000';  
            this.context.lineWidth = 2;  
        },  
        startDrawing(event) {  
            this.isDrawing = true;  
            const rect = this.$refs.canvas.getBoundingClientRect(); 
            this.lastX = event.clientX - rect.left;  
            this.lastY = event.clientY - rect.top; 
        //   this.lastX = event.offsetX || event.touches[0].clientX;  
        //   this.lastY = event.offsetY || event.touches[0].clientY;  
        },  
        stopDrawing() {  
            this.isDrawing = false; 
            this.lastX = null;  
            this.lastY = null;   
        },  
        draw(event) {
           
            if (!this.isDrawing || !this.lastX || !this.lastY) return;  
            const rect = this.$refs.canvas.getBoundingClientRect();  
            const x = event.clientX - rect.left;  
            const y = event.clientY - rect.top;
            this.drawLine(this.lastX, this.lastY, x, y);  
            this.lastX = x;  
            this.lastY = y;  
        },  
        drawTouch(event) {  
            this.hasContent = true;
            if (!this.isDrawing) return;  
                const rect = this.$refs.canvas.getBoundingClientRect();  
                const touch = event.touches[0];  
                const x = touch.clientX - rect.left;  
                const y = touch.clientY - rect.top;  
                this.drawLine(this.lastX, this.lastY, x, y);  
                this.lastX = x;  
                this.lastY = y;  
            }, 
        drawLine(x1, y1, x2, y2) {  
            this.context.beginPath();  
            this.context.moveTo(x1, y1);  
            this.context.lineTo(x2, y2);  
            this.context.stroke();  
        },  
        canvasClose() {
            this.isPhotoOrsize = '图片'
        },
        clearCanvas() {  
            this.context.clearRect(0, 0, this.width, this.height);  
            this.hasContent = false;
        },  
        saveSignature() {
            if(this.hasContent == false) {
                return this.$toast('请签名')
            }
            this.canvasPhotoIMG =  this.$refs.canvas.toDataURL('image/png');  
            const canvas = this.$refs.canvas; 
            canvas.toBlob(async (blob)  => {  
                const file = new File([blob], 'my_image.png', { type: 'image/png' });   
                console.log(file,'file')
                const formData = new FormData();
                formData.append('file', file); 
                const res = await appUploadTheSignature(formData)
                this.getFileUrl = res.data
                console.log(this.getFileUrl,'=addresse')
            }); 
            this.currentSelect = "签字板"
            this.isPhotoOrsize = '图片'
            this.context.clearRect(0, 0, this.width, this.height);  
            this.hasContent = false;
        },  


        onConfirm(value, index) {
            if(value == '签字板') {
                this.show =true
            }
            if(value == '图片') {
                this.uploader = []
            }
            this.currentSelect = value
            this.isPhotoOrsize = value
            this.isShelf = false
        },
        onCancel() {
            this.isShelf = false
        },
        beforeRead(file) {
            // 在这里可以添加对文件的校验逻辑
            // 如果返回 true, 则继续读取文件
            return true;
        },
        // 文件读取完成后的钩子
        async afterRead(file) {
            console.log(file)
            this.photoIMG = file.content
            this.hasUploadedImage = true;  
            console.log(file.content,'--',this.photoIMG)
            const formData = new FormData();
            formData.append('file', file.file); // 这里的 'file' 是后端接收文件的字段名
            const res = await appUploadTheSignature(formData)
            this.getFileUrl = res.data
        },
        async onSubmit(values) {
            let data = []
            this.goodsList.forEach((item) => {
                if (values.checkboxGroup.find((itemA) => itemA === item.id)) {
                    data.push(item.expressNo)
                }
            })
            console.log(this.getFileUrl,'传的对不对，是哪一个')
            const params = {
                signEnclosureImg: this.getFileUrl,//签署图片
                deliveryId: data.join(','),//快递单号逗号隔开
                deliveryPeopleId: localStorage.getItem('courierId'),// 派件员id
            }
            const res = await appDelivery({ ...params }, { emulateJSON: true, loading: true, message: '签收中' })
            if (res.code == 0) {
                this.$toast('签收成功')
                this.$router.push('/')
            } else {
                this.$toast('签收失败')
            }

        },
        back() {
            this.$emit('isCombine', true)
        },
        // phoneSubmit() {
        //     if (this.hasUploadedImage) {  
        //         this.isPhotoOrsize = '图片'
        //         this.currentSelect = '图片'
        //         this.canvasPhotoIMG = this.photoIMG
        //         console.log(this.photoIMG,'--123图片')
        //     } else {  
        //         this.$toast('请先上传图片');  
        //     } 
           
        // },
        // photoClose() {
        //     this.isPhotoOrsize = '图片'
        // },

        // // 删除图片时的处理  
        // onDelete(file) {  
        //     // 标记为未上传图片  
        //     this.hasUploadedImage = false;  
        //     console.log('已删除图片', file);  
        // }, 
    }

};
</script>



<style lang="less" scoped>
.ckickChange {
    padding: 20px 20px;
}
* {
    font-size: 16px;
}

.van-field__label {
    width: 4rem;
}

.container {
    padding: 2px 10px 0 10px;
    background-color: #fff;
}
</style>
