<template>
    <div class="container">
        <div class="top" v-if="orderInfo.productInfo">
            <span>订单号:{{orderInfo.orderCode}}</span>
            <span style="margin-left:20px;">{{orderInfo.productInfo.title}}</span>
            <span style="font-size:14px;margin-left:20px;">已上传/总张数：{{orderImage.length}} / {{orderInfo.quantity}}</span>
            <span v-if="canUploadNum<0" style="font-size:14px;color:red;margin-left:10px">超出{{0-canUploadNum}}张</span>
            <el-button type="primary" v-if="canUploadNum>0" class="btn" @click="tip=[],dialogVisible=true,upLoadImg=[],addImage=[],num=0,maxNum=orderInfo.quantity-orderImage.length,chooseName=[]">上传图片</el-button>

            <el-button style="float:right;margin:20px;" v-if='canSubmit&&canUploadNum==0' type="warning" class="btn" @click="submit">确定</el-button>
        </div>

        <!-- <el-upload class="upload-demo" :file-list="upLoadImg" drag :limit="canUploadNum" :action="url" :before-upload="handleOn" multiple :on-success='handleSuccess' :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文件，当前已上传{{addImage.length}}张图片，还可以上传{{canUploadNum-addImage.length}}张</div>
        </el-upload> -->

        <el-dialog title="上传图片" class="uploadDialog" :class="{uploadSmall:(maxNum<15)}" :visible.sync="dialogVisible" :show-close='(orderInfo.quantity-maxNum+num)==orderImage.length' :width="maxNum>50?'80%':'50%'" :top="maxNum>50?'50px':'15vh'" :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" style="width:100%" :limit="maxNum" :file-list="upLoadImg" drag :action="url" :before-upload="handleOn" :on-progress='handleProgress' multiple :on-success='handleSuccess' :on-remove="handleRemove" :on-error='handleError'>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或
                    <em>点击上传</em>
                </div>
                <div class="el-upload__tip" slot="tip">只能上传RGB图片类型的jpg/png文件,已上传/总张数：{{orderImage.length}} / {{orderInfo.quantity}}&nbsp;&nbsp;&nbsp;还可以选择{{maxNum-num}}张</div>
            </el-upload>
        </el-dialog>

        <div class="content">
            <template v-if="orderImage.length>0">
                <div class="title">原片</div>
                <div class="imgList">
                    <img-item v-for="(item,index) in orderImage" @changeRemark="changeRemark" :canCancel='canSubmit' :storeType='true' :label='"originalImage"' :index='index' :img='item' :imgStyle='"upload"' @delImg='delImg' style="display:inline-block;margin:0 30px 30px 0;"></img-item>
                </div>
            </template>

            <div v-else class="nothing">
                <img src="../assetsPre/nothingImg.png" alt="">
                <p>还没有图片哦，快去上传吧～</p>
            </div>

        </div>

    </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.orderInfo.statusFlag != 1) {


                    this.canSubmit = false
                }

            }
        })

        this.getImage()





    },
    computed: {
        ...mapState(['userInfo']),
        url() {
            return baseUrl + '/orderImage/uploadFileForOrder?storeId=' + this.orderInfo.storeId + '&orderId=' + this.orderInfo.id + '&userId=' + this.userInfo.id + '&typeFlag=original'
        },
        allImage() {
            var list = []
            this.addImage.forEach(item => {
                list.push(item.url)
            })
            return list
        },
        canUploadNum() {
            var num = 0
            if (this.orderInfo.quantity) {
                num = this.orderInfo.quantity - this.orderImage.length
            }

            return num
        },
        orderImgId() {
            var list = []
            this.orderImage.forEach(item => {
                list.push(item.id)
            })
            return list
        },
        orderImgName() {
            var list = []
            this.orderImage.forEach(item => {
                list.push(item.imageName)
            })
            return list
        },
    },
    data() {
        return {
            orderInfo: {},
            dialogVisible: false,
            addImage: [],
            orderImage: [],
            canSubmit: true,
            upLoadImg: [],
            num: 0,
            loading: false,
            tip: [],
            realNum: 0,
            maxNum: 0,
            AddImageloading: false,
            chooseName: []
        }
    },
    methods: {
        getImage() {
            const loading = this.$loading({
                lock: true,
                text: '正在加载中',
            });

            this.orderImage = []
            this.$http.get({
                url: '/orderImage/all',
                data: {
                    orderId: this.$route.query.orderId
                }
            }).then(res => {
                if (res.success) {

                    res.data.forEach(item => {
                        item.isSuccess = true
                    })
                    this.orderImage = res.data
                    this.realNum = res.data.length
                    loading.close();


                }
            })
        },
        chooseImg(index) {
            // console.log(index)
        },
        changeRemark(json) {
            if (this.orderImgId.indexOf(json.id) != -1) {
                this.addImage[this.orderImgId.indexOf(json.id)].remark = json.remark
            }
        },
        handleRemove(file, fileList) {

        },
        handleSuccess(res) {
            // console.log(res)
            var tips = [...this.tip]
            tips.forEach((item, index) => {
                var list = item.split('文件正在压缩')
                if (list[0] === res.data[0].imageName) {
                    tips.splice(index, 1)
                }
            })
            tips.splice(0, 0, res.data[0].imageName + '文件上传成功')
            this.tip = tips
            setTimeout(() => {
                var tips = [...this.tip]
                tips.forEach((item, index) => {
                    if (item.indexOf('文件上传成功') != -1) {
                        tips.splice(index, 1)
                    }
                })
                this.tip = tips
            }, 1000)


            if (this.orderImgId.indexOf(res.data[0].id) == -1) {
                this.orderImage.splice(0, 0, res.data[0])
            }
            else {
                this.orderImage.splice(this.orderImgId.indexOf(res.data[0].id), 1, res.data[0])
            }

        },
        handleError(file, fileList) {
            this.num = fileList.length
        },
        handleProgress(e, file) {
            // console.log(e, file)
            if (e.percent == 100) {
                this.tip.splice(0, 0, file.name + '文件正在压缩')
            }

        },
        handleOn(file, fileList) {
            // console.log(fileList)
            const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
            if (!isJPG) {
                // this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            else {
                if (this.chooseName.indexOf(file.name) != -1) {
                    return false
                }
                else {
                    if (this.orderImgName.indexOf(file.name) != -1) {
                        return false
                    }

                    this.chooseName.push(file.name)
                }


                this.loading = true
                this.num++
            }




            return isJPG
        },
        delImg(id) {

            if (this.orderImgId.indexOf(id) != -1) {
                this.orderImage.splice(this.orderImgId.indexOf(id), 1)
            }

        },
        upload() {
            this.saveImage(0)
        },
        saveImage(i) {
            if (i == this.allImage.length) {
                this.$message.success('成功');
                this.dialogVisible = false
                this.getImage()
            }
            else {
                var data = {
                    originalImage: this.addImage[i].url,
                    orderId: this.orderInfo.id,
                    userId: this.userInfo.id,
                    storeId: this.orderInfo.storeId,
                    imageName: this.addImage[i].imageName,
                    originalSize: this.addImage[i].imageSize,
                    originalArtwork: this.addImage[i].artworkUrl

                }
                this.$http.post({
                    url: '/orderImage/save',
                    data: data
                }).then(res => {
                    if (res.success) {
                        this.saveImage(i + 1)
                    } else {
                        this.$message.warning('失败')
                    }
                });
            }
        },
        submit() {


            this.$http.get({
                url: '/orderImage/getTotalNum',
                data: {
                    orderId: this.orderInfo.id,
                }
            }).then(res => {
                if (res.data.totalNum != res.data.orderNum) {
                    this.$alert('图片数量有问题，不能上传哦！', '提示', {
                        confirmButtonText: '确定',
                        callback: action => {
                            this.getImage()
                        }
                    });
                }
                else {
                    this.$http.post({
                        url: '/userOrder/update',
                        data: {
                            id: this.orderInfo.id,
                            statusFlag: this.orderInfo.statusFlag + 1
                        }
                    }).then(res => {
                        if (res.success) {
                            this.$http.post({
                                url: '/orderImage/delOssImage',
                                data: {
                                    orderId: this.orderInfo.id
                                }
                            })
                            this.$message.success('上传图片成功');
                            history.back()

                        }
                    })
                }
            })


        }
    },
    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: 500px;
        .title {
            font-size: 14px;
            font-family: MicrosoftYaHei-Bold;
            font-weight: bold;
            color: rgba(11, 158, 192, 1);
            line-height: 19px;
            padding: 19px 0 10px;
        }

        .imgList {
        }
    }

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

    .nothing {
        margin-top: 136px;
        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;
        }
    }
}
</style>
