<template>
    <div class="container" v-loading='loading' element-loading-text="上传图片中，时间或许会很久，请耐心等待哦！">
        <div class="top" v-if="orderInfo.productInfo">
            <span>订单号:{{orderInfo.orderCode}}</span>
            <span style="margin-left:20px;">{{orderInfo.productInfo.title}}</span>
            <span style="color:#666;font-size:14px;margin-left:20px">全部{{allNumber}}张图片,还需上传{{notUp}}张</span>
            <el-button style="float:right;margin:15px 10px 0 20px;width:100px" v-if="!notUp" type="primary" class="btn" @click="submit">提交</el-button>
            <el-select v-if="!isChange" size="mini" style="float:right;margin-top:25px;width:120px" clearable v-model="unFinished" placeholder="筛选状态" @change="getImage">
                <el-option key="1" label="未上传" value="1">
                </el-option>
                <el-option key="0" label="已上传" value="0">
                </el-option>
            </el-select>
            <el-button type="primary" size="mini" style="float:right;margin-top:25px;margin-right:20px" class="btn" plain @click="dialogVisible=true,upLoadImg=[],addImage=[],num=0">批量上传</el-button>
        </div>

        <div class="content">

            <template v-if="orderImage.length>0">
                <div class="imgList">
                    <div class="title">原<br/>片</div>
                    <img-item v-for="(item,index) in orderImage" @changeRemark="getImage" :label='"originalImage"' :index='index' :img='item' :imgStyle='"showInfo"' @delImg='getImage' style="display:inline-block;margin:0 30px 0 0;vertical-align: middle;"></img-item>
                </div>

                <div class="imgList" style="margin-top:50px;">
                    <div class="title" style="color:#FB6E08">成<br/>片</div>
                    <div style="display:inline-block;vertical-align: middle" v-for="(item,index) in orderImage">
                        <single-upload-title v-if="!item.finishedImage||item.statusFlag==2" class="box" :needName='item.imageName' :nowIndex='index' :url='url' @input="changeImg" @start='loading=true' :title='"上传成片"' :width='120' :height='150'>
                        </single-upload-title>
                        <img-item v-if="item.finishedImage" :isChange='isChange' @changeRemark="changeRemark" :label='"finishedImage"' :index='index' :img='item' :imgStyle='"storeUpload"' @delImg='getImage' style="display:inline-block;margin:0 30px 0 0;vertical-align: middle;"></img-item>

                    </div>
                </div>
            </template>
            <div v-else class="nothing">
                <img src="../assetsPre/nothingImg.png" alt="">
                <p>没有图片哦!</p>
            </div>

        </div>

        <el-pagination v-if="totalNumber>7" background :page-size="7" @current-change="currentPageChange" :current-page="currentPage" layout="total, prev, pager, next" :total="totalNumber">
        </el-pagination>

        <div class="bottom">
            <template v-if="!isChange">
                <!-- <span v-if="canUploadNum>0">当前已上传{{orderImage.length}}张图片，还需上传{{canUploadNum}}张</span> -->

            </template>

        </div>

        <el-dialog title="上传图片" class="uploadDialog" :visible.sync="dialogVisible" width="80%" top="50px" :close-on-click-modal='false'>
            <div v-if="tip.length>0" class="tip" style="margin-bottom:10px;">
                <template v-if="tip[0].indexOf('正在压缩')!=-1">
                    <i class="el-icon-loading"></i>{{tip[0]}}请不要关闭窗口耐心等待
                </template>
                <template v-else>
                    {{tip[0]}}
                </template>
            </div>
            <el-upload class="upload-demo" :file-list="upLoadImg" drag :action="url" multiple :before-upload="handleOn" :on-success='handleSuccess' :on-progress='handleProgress' :on-remove="handleRemove">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或
                    <em>点击上传</em>
                </div>
                <div class="el-upload__tip" slot="tip">只能上传RGB图片类型的jpg/png文件,已上传/总张数：{{orderInfo.quantity-notUp}} / {{orderInfo.quantity}}</div>
            </el-upload>

            <!-- <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="upload" :loading="isLoading">确 定</el-button>
            </span> -->
        </el-dialog>

    </div>
</template>
<script>
import { mapState } from 'vuex'
import imgItem from '../components/ImgItem'
import formValidator from '../formValidator'
const baseUrl = process.env.NODE_ENV === 'production' ? '../' : 'http://localhost:8080';
export default {
    created() {
        this.$http.get({
            url: '/userOrder/getOne',
            data: {
                id: this.$route.query.orderId
            }
        }).then(res => {
            if (res.success) {
                this.orderInfo = res.data
                if (this.$route.query.repairId) {
                    this.repairId = this.$route.query.repairId
                }
                else {
                    if (this.orderInfo.orderRepairList.length > 0) {
                        this.repairId = this.orderInfo.orderRepairList[0].id
                    }

                }
                this.getImage()
            }
        })

        if (this.$route.query.isChange) {
            this.isChange = true
        }

        // //获取全部修图数量
        // this.$http.get({
        //     url: '/orderImage/page',
        //     data: {
        //         orderId: this.$route.query.orderId,
        //         currentPage: 1,
        //         pageNumber: 1,
        //         repairId: this.$route.query.repairId,
        //     }
        // }).then(res => {
        //     if (res.success) {

        //         this.allNumber = res.data.page.totalNumber;
        //     }
        // })



    },
    computed: {
        ...mapState(['userInfo']),
        url() {
            return baseUrl + '/orderImage/uploadFileForOrder?storeId=' + this.orderInfo.storeId + '&orderId=' + this.orderInfo.id + '&userId=' + this.userInfo.id + '&typeFlag=finished'
        },
        repairNum() {
            var num = 0
            if (this.orderInfo.orderRepairList.length) {
                num = this.orderInfo.orderRepairList[this.orderInfo.orderRepairList.length - 1].typeFlag + 1
                if (this.orderInfo.orderRepairList[this.orderInfo.orderRepairList.length - 1].statusFlag != 0) {
                    num++
                }
            }

            return num
        },
        orderImgId() {
            var list = []
            this.orderImage.forEach(item => {
                list.push(item.id)
            })
            return list
        }
    },
    data() {
        return {
            tip: [],
            orderInfo: {},
            dialogVisible: false,
            addImage: [],
            orderImage: [],
            currentPage: 1,
            totalNumber: 0,
            isSuccess: false,
            isFail: false,
            repairId: 0,
            isChange: false,
            unFinished: '',
            upLoadImg: [],
            notUp: 0,
            allNumber: 0,
            num: 0,
            isLoading: false,
            loading: false,
        }
    },
    methods: {
        handleOn(file) {
            const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
            if (!isJPG) {
                return isJPG
            }


            return new Promise((resolve, reject) => {
                this.$http.get({
                    url: '/orderImage/getOne',
                    data: {
                        orderId: this.$route.query.orderId,
                        imageName: file.name
                    }
                }).then(res => {
                    if (res.data) {
                        if (res.data.statusFlag == 1) {

                            reject()
                        }
                        else {
                            this.num++
                            resolve()
                        }

                    }
                    else {
                        this.$message({
                            message: file.name + '图片不在任务中，不能上传',
                            type: 'warning'
                        });
                        reject()
                    }
                })
            })




        },
        changeRemark() {
            if (!this.repairId) {
                this.$http.get({
                    url: '/userOrder/getOne',
                    data: {
                        id: this.$route.query.orderId
                    }
                }).then(res => {
                    if (res.success) {
                        this.orderInfo = res.data
                        if (this.$route.query.repairId) {
                            this.repairId = this.$route.query.repairId
                        }
                        else {
                            if (this.orderInfo.orderRepairList.length > 0) {
                                this.repairId = this.orderInfo.orderRepairList[0].id
                            }

                        }
                        this.getImage()
                    }
                })


            }
            else {
                this.getImage()
            }
        },
        currentPageChange(page) {
            this.currentPage = page;
            this.getImage();
        },
        getImage() {
            var data = {
                orderId: this.$route.query.orderId,
                currentPage: this.currentPage,
                pageNumber: 7,
            }

            //普通审核筛选
            if (this.unFinished) {
                data.unFinished = this.unFinished
            }

            //返修筛选
            if (this.$route.query.repairId) {
                data.repairId = this.$route.query.repairId
                if (data.unFinished == '1') {
                    data.statusFlag = 2
                }
                else if (data.unFinished == '0') {
                    data.statusFlag = 0
                }
                data.unFinished = ''
                data.baseRepairId = this.$route.query.repairId


            }

            this.orderImage = []
            this.$http.get({
                url: '/orderImage/page',
                data: data
            }).then(res => {
                if (res.success) {
                    this.orderImage = res.data.pp
                    this.totalNumber = res.data.page.totalNumber;
                    this.allNumber = res.data.page.totalNumber;
                }
            })

            //未上传数量
            this.$http.get({
                url: '/orderImage/all',
                data: {
                    orderId: this.$route.query.orderId,
                    unFinished: this.$route.query.repairId ? '' : 1,
                    repairId: this.$route.query.repairId,
                    statusFlag: this.$route.query.repairId ? 2 : ''
                }
            }).then(res => {
                this.notUp = res.data.length
            })


        },
        chooseImg(index) {
            console.log(index)
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
            // var list = []
            // fileList.forEach(item => {
            //     item.response.data.forEach(todo => {
            //         var jsop = {
            //             originalImage: todo,
            //             remark: ''
            //         }
            //         list.push(jsop)
            //     })
            // })
            // this.addImage = list
            this.num = this.addImage.length
        },
        handleProgress(e, file) {
            if (e.percent == 100) {
                this.tip.splice(0, 0, file.name + '文件正在压缩')
            }
        },
        handleSuccess(res, flie) {
            console.log(res)
            var tips = [...this.tip]
            tips.forEach((item, index) => {
                var list = item.split('文件正在压缩')
                if (list[0] === flie.name) {
                    tips.splice(index, 1)
                }
            })
            tips.splice(0, 0, flie.name + (res.success ? '文件上传成功' : '上传失败'))
            this.tip = tips
            setTimeout(() => {
                var tips = [...this.tip]
                tips.forEach((item, index) => {
                    if (item.indexOf((res.success ? '文件上传成功' : '上传失败')) != -1) {
                        tips.splice(index, 1)
                    }
                })
                this.tip = tips
            }, 1000)
            if (res.success) {
                if (this.orderImgId.indexOf(res.data[0].id) != -1) {
                    this.$http.get({
                        url: '/orderImage/all',
                        data: {
                            orderId: this.$route.query.orderId,
                            unFinished: this.$route.query.repairId ? '' : 1,
                            repairId: this.$route.query.repairId,
                            statusFlag: this.$route.query.repairId ? 2 : ''
                        }
                    }).then(res => {
                        this.notUp = res.data.length
                    })
                    this.orderImage.splice(this.orderImgId.indexOf(res.data[0].id), 1, res.data[0])
                }
            }
            else {
                return false
            }

        },
        delImg(index) {
            this.addImage.splice(index, 1)
        },
        upload() {
            const loading = this.$loading({
                lock: true,
                text: '加载中',
            });
            var id = []
            this.addImage.forEach(item => {
                id.push(item.id)
            })
            this.$http.post({
                url: '/orderImage/updateFinishedImages',
                data: {
                    imageIds: id.toString(),
                    orderId: this.orderInfo.id
                }
            }).then(res => {
                if (res.success) {
                    loading.close();
                    this.$message.success('成功');
                    this.dialogVisible = false
                    this.getImage()
                } else {
                    this.$message.warning('失败')
                }
            });
        },
        saveImage(i) {
            if (i == this.allImage.length) {
                this.$message.success('成功');
                this.dialogVisible = false
                this.getImage()
            }
            else {
                var data = {
                    originalImage: this.allImage[i],
                    orderId: this.orderInfo.id,
                    userId: this.userInfo.id,
                    storeId: this.orderInfo.storeId

                }
                this.$http.post({
                    url: '/orderImage/save',
                    data: data
                }).then(res => {
                    if (res.success) {
                        this.saveImage(i + 1)
                    } else {
                        this.$message.warning('失败')
                    }
                });
            }
        },
        submit() {
            this.$http.post({
                url: '/orderImage/delOssImage',
                data: {
                    orderId: this.orderInfo.id
                }
            })
            if (this.$route.query.repairId) {
                if (this.orderInfo.orderRepairList.length == 3 && this.orderInfo.orderRepairList[this.orderInfo.orderRepairList.length - 1].typeFlag == 2) {
                    this.$http.post({
                        url: '/orderRepair/update',
                        data: {
                            id: this.$route.query.repairId,
                            statusFlag: 3
                        }
                    }).then(res => {
                        if (res.success) {
                            this.$http.post({
                                url: '/userOrder/update',
                                data: {
                                    id: this.orderInfo.id,
                                    statusFlag: 3
                                }
                            }).then(res2 => {
                                if (res2.success) {
                                    // this.$message.success('提交成功');
                                    // history.back()

                                    this.$http.post({
                                        url: '/userOrder/confirm',
                                        data: {
                                            id: this.orderInfo.id,
                                        }
                                    }).then(res3 => {
                                        if (res3.success) {
                                            this.$message.success('提交成功');
                                            history.back()
                                        }
                                    })
                                }
                            })

                        }
                    })
                }
                else {
                    this.$http.post({
                        url: '/orderRepair/update',
                        data: {
                            id: this.$route.query.repairId,
                            statusFlag: 2
                        }
                    }).then(res => {
                        if (res.success) {
                            this.$message.success('提交成功');
                            history.back()

                        }
                    })
                }

            }
            else {
                this.$http.post({
                    url: '/userOrder/update',
                    data: {
                        id: this.orderInfo.id,
                        statusFlag: 3
                    }
                }).then(res => {
                    if (res.success) {
                        this.$message.success('提交成功');
                        history.back()

                    }
                })
            }

        },
        changeImg(newVal) {
            this.$message.success('提交成功');
            this.loading = false
            this.getImage()
        },
        updateImg(index, img, size, artworkUrl) {
            this.$http.post({
                url: '/orderImage/update',
                data: {
                    id: this.orderImage[index].id,
                    finishedImage: img,
                    finishedSize: size,
                    statusFlag: 0,
                    finishedArtwork: artworkUrl
                }
            }).then(res => {
                if (res.success) {
                    this.getImage()

                }
            })
        }
    },
    components: {
        imgItem
    }
}
</script>
<style lang="less" scoped>
.container {
    background: rgba(255, 255, 255, 1);
    border-bottom: 1px solid rgba(234, 234, 234, 1);
    .top {
        height: 78px;
        background: rgba(255, 255, 255, 1);
        border: 1px solid rgba(234, 234, 234, 1);
        padding: 0 30px;
        span {
            font-size: 18px;
            font-family: MicrosoftYaHei;
            color: rgba(51, 51, 51, 1);
            line-height: 78px;
        }
        .btn {
            float: right;
            margin-top: 20px;
        }
    }

    .content {
        padding: 0 30px;
        min-height: 450px;
        .title {
            font-size: 14px;
            font-family: MicrosoftYaHei-Bold;
            font-weight: bold;
            color: rgba(11, 158, 192, 1);
            line-height: 19px;
            margin-bottom: 20px;
            display: inline-block;
            vertical-align: middle;
            margin-right: 20px;
        }

        .imgList {
            margin-top: 20px;
        }
    }

    .bottom {
        height: 58px;
        border-top: 1px solid rgba(234, 234, 234, 1);
        line-height: 58px;
        padding: 0 30px;
        margin-top: 20px;
        span {
            font-size: 14px;
            color: #999;
        }
    }

    .nothing {
        margin-top: 20px;
        img {
            width: 167px;
            height: 167px;
            display: block;
            margin: auto;
        }

        p {
            font-size: 14px;
            text-align: center;
            color: rgba(51, 51, 51, 1);
            line-height: 19px;
            margin-top: 24px;
        }
    }

    .box {
        width: 120px;
        height: 150px;
        margin-right: 30px;
        border-radius: 4px;
    }
}
</style>
