<template>
    <view class="diy-form-uimage dir-top-nowrap" :style="[boxStyle]">
        <view class="_diy-form-label"
              :style="{ color: data.title_color}"
              :class="{required: data.is_required}">
            {{ data.title }}
        </view>
        <view v-if="data.type === 'ordinary'" class="dir-left-wrap cross-center"
              :style="[uploadStyle]">
            <view
                v-for="(image,index) of imageList" :key="index"
                @click="previewImage(index)"
                class="ordinary-pic img-list dir-left-nowrap cross-center main-center"
                :style="{backgroundColor: data.ordinary_bg_color}">
                <image :src="appImg.uimage_close" class="close" @click.stop="delImage"></image>
                <image :src="image" class="img"></image>
            </view>
            <view
                v-if="imageList.length < data.max_num"
                @click="chooseImage(-1)"
                class="ordinary-pic dir-left-nowrap cross-center main-center"
                :style="{backgroundColor: data.ordinary_bg_color}">
                <image :src="appImg.uimage_photo"></image>
            </view>
            <view class="ordinary-text" v-if="!imageList || !imageList.length"
                  :style="{color: data.place_color}">
                最多上传{{ data.max_num }}张
            </view>
        </view>
        <view v-if="data.type === 'idcard'" class="dir-left-nowrap cross-center main-between">
            <view class="f-idcard cross-center main-center box-grow-0"
                  :style="[uploadStyle]" @click="chooseImage(0)">
                <image mode="aspectFit" style="height:100%;width:100%" v-if="imageList && imageList[0]" :src="imageList[0]"></image>
                <image v-else class="idcard-box-pic" :src="appImg.uimage_idcard_l"></image>
                <view class="idcard-alone main-center cross-center"
                      :style="{background: data.icon_bg_color}"
                >
                    <image class="idcard-photo" :src="appImg.uimage_photo_white"></image>
                </view>
            </view>
            <view class="f-idcard cross-center main-center box-grow-0"
                  :style="[uploadStyle]" @click="chooseImage(1)">
                <image mode="aspectFit" style="height: 100%;width: 100%" v-if="imageList && imageList[1]" :src="imageList[1]"></image>
                <image v-else class="idcard-box-pic" :src="appImg.uimage_idcard_r"></image>
                <view class="idcard-alone main-center cross-center"
                      :style="{background: data.icon_bg_color}"
                >
                    <image class="idcard-photo" :src="appImg.uimage_photo_white"></image>
                </view>
            </view>
        </view>
        <view v-if="data.type === 'license'" class="dir-left-nowrap cross-center">
            <view class="f-idcard f-license cross-center main-center"
                  :style="[uploadStyle]" @click="chooseImage(0)">
                <image mode="aspectFit" style="height: 100%;width: 100%" v-if="imageList && imageList[0]" :src="imageList[0]"></image>
                <image v-else class="idcard-box-pic" :src="appImg.uimage_license"></image>
                <view class="idcard-alone main-center cross-center"
                      :style="{background: data.icon_bg_color}"
                >
                    <image class="idcard-photo" :src="appImg.uimage_photo_white"></image>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import {mapState} from "vuex";
import uploadFile from "@/core/upload";

export default {
    name: 'diy-form-uimage',
    props: {
        index: [Number, String],
        value: {
            type: Object
        }
    },
    computed: {
        ...mapState({
            appImg: state => state.mallConfig.plugin.diy.app_image,
        }),
        boxStyle() {
            let {
                bg_color,
                box_padding,
            } = this.data;
            return {
                backgroundColor: bg_color,
                padding: `20rpx ${box_padding}rpx`,
            }
        },
        uploadStyle() {
            let {
                border_color,
                pd_color,
                type,
            } = this.data;
            let style = {
                borderWidth: '1px',
                borderStyle: 'solid',
                borderColor: border_color ? border_color : pd_color,
                backgroundColor: pd_color,
                borderRadius: '12rpx',
            }
            if (type === 'ordinary') {
                Object.assign(style, {
                    padding: '16rpx 44rpx 0 3rpx',
                })
            }
            return style;
        },
    },
    data() {
        return {
            imageList: [],
            data: {
                is_required: 0,
                title: '上传图片',
                min_num: 1,
                max_num: 1,
                type: 'ordinary',//ordinary idcard license
                box_padding: 24,
                pd_color: '#F1F5F8',
                border_color: '#F1F5F8',
                title_color: '#545B60',
                place_color: '#545B60',
                icon_bg_color: '#99A1AA',
                ordinary_bg_color: '#FFFFFF',
                bg_color: '#FFFFFF',
            }
        }
    },
    created() {
        this.data = this.value
    },
    methods: {
        validateRules() {
            let {min_num, max_num, is_required} = this.data;
            let length = this.imageList;
            if (is_required == 0) {
                return true;
            }
            if (length < min_num) {
                throw new Error(`最少上传${min_num}张图片`);
            }
            if (length > max_num) {
                throw new Error('最多上传${max_num}张图片');
            }
            return true;
        },
        //todo imageList h5 会清空待测试
        previewImage(index) {
            let imageList = this.imageList;
            uni.previewImage({
                current: imageList[index],
                urls: imageList,
            })
        },
        imageEvent() {
            this.$emit('updateValue', {
                index: this.index,
                value: this.imageList,
            });
        },
        delImage(index) {
            this.imageList.splice(index, 1);
            this.imageEvent();
        },
        // 选择图片
        chooseImage(addIndex) {
            let self = this;
            let {
                imageList,
            } = self;
            // #ifdef MP
            uni.chooseImage({
                count: self.data.type === 'ordinary' ? Number(self.data.max_num) - imageList.length: 1,
                success: function (e) {
                    for (let i in e.tempFilePaths) {
                        // if (i >= (maxNum - imageList.length)) {
                        //     break;
                        // }
                        let fileName = '';
                        // #ifdef MP-BAIDU
                        fileName = e.tempFilePaths[i].substr(e.tempFilePaths[i].lastIndexOf('/') + 1);
                        // #endif
                        uni.uploadFile({
                            url: self.$api.upload.file,
                            filePath: e.tempFilePaths[i],
                            name: 'file',
                            fileType: 'image',
                            formData: {
                                file: e.tempFilePaths[i],
                                file_name: fileName,
                            },
                            success(res) {
                                const data = res.data;
                                let result = null;
                                if (typeof data === 'string') {
                                    result = JSON.parse(data);
                                } else {
                                    result = data;
                                }
                                if (result.code == 0) {
                                    let num = addIndex > self.imageList.length ? addIndex - self.imageList.length : 0;
                                    let paras = new Array(num).concat(result.data.url);
                                    self.imageList.splice(addIndex, self.imageList.hasOwnProperty(addIndex) ? 1 : 0, ...paras);
                                    self.imageEvent();
                                } else {
                                    uni.showModal({
                                        title: '',
                                        content: result.msg,
                                        showCancel: false,
                                    });
                                }
                            },
                            fail(e) {
                                if (e && e.errMsg) {
                                    uni.showModal({
                                        title: '错误',
                                        content: e.errMsg,
                                        showCancel: false,
                                    });
                                }
                            },
                        });
                    }
                },
                complete: function (e) {
                    self.imageEvent();
                }
            })
            // #endif

            // #ifdef H5
            uni.chooseImage({
                count: self.data.type === 'ordinary' ? Number(self.data.max_num) - imageList.length: 1,
                success: function (e) {
                    for (let i in e.tempFilePaths) {
                        // if (i >= (maxNum - imageList.length)) {
                        //     break;
                        // }
                        let image = new Image();
                        image.src = e.tempFilePaths[i];
                        image.onload = () => {
                            let canvas = document.createElement("canvas");
                            canvas.width = image.width;
                            canvas.height = image.height;
                            let ctx = canvas.getContext("2d");
                            ctx.drawImage(image, 0, 0, image.width, image.height);
                            let ext = image.src.substring(image.src.lastIndexOf(".") + 1).toLowerCase();
                            let dataURL = canvas.toDataURL("image/" + ext);
                            uploadFile({
                                url: self.$api.upload.file,
                                success: function ({res, header}) {
                                    self.$request({
                                        url: self.$api.upload.file + '&name=base64',
                                        header: header,
                                        method: 'post',
                                        data: {
                                            database: dataURL
                                        }
                                    }).then(res => {
                                        if (res.code === 0) {
                                            let num = addIndex > self.imageList.length ? addIndex - self.imageList.length : 0;
                                            let paras = new Array(num).concat(res.data.url);
                                            self.imageList.splice(addIndex, self.imageList.hasOwnProperty(addIndex) ? 1 : 0, ...paras);
                                            self.imageEvent();
                                        } else {
                                            uni.showModal({
                                                title: '',
                                                content: res.msg,
                                                showCancel: false,
                                            });
                                        }
                                    })
                                }
                            });
                        };
                    }
                },
                complete: function (e) {
                    self.imageEvent();
                }
            });
            // #endif
        },
    }
}
</script>

<style scoped lang="scss">
._diy-form-label {
    padding-left: #{20rpx};
    font-size: #{30rpx};
    white-space: nowrap;
    margin-bottom: #{18rpx};
}

._diy-form-label.required:after {
    content: '*';
    margin-left: 6#{rpx};
    color: #FF4544;
}

.diy-form-uimage {
    .idcard-photo {
        height: 60#{rpx};
        width: 60#{rpx};
        display: block;
    }

    .ordinary-pic {
        height: 100#{rpx};
        width: 100#{rpx};
        border-radius: 10#{rpx};
        margin: 10#{rpx} 17#{rpx} 28#{rpx};

        > image {
            height: 60#{rpx};
            width: 60#{rpx};
            display: block;
        }
    }

    .ordinary-pic.img-list {
        position: relative;

        .close {
            position: absolute;
            top: -18#{rpx};
            right: -18#{rpx};
            height: 36#{rpx};
            width: 36#{rpx};
            display: block;
            z-index: 1;
        }

        .img {
            height: 100%;
            width: 100%;
            border-radius: inherit;
        }
    }

    .ordinary-text {
        margin-left: auto;
        color: #545B60;
        margin-bottom: #{16rpx};
        font-size: 24#{rpx};
    }

    .f-idcard {
        overflow: hidden;
        height: 200#{rpx};
        width: 340#{rpx};
        position: relative;

        .idcard-box-pic {
            height: 134#{rpx};
            width: 214#{rpx};
            display: block;
        }

        .idcard-alone {
            opacity: 0.5;
            position: absolute;
            top: 50#{rpx};
            left: 115#{rpx};
            border-radius: 50%;
            height: 100#{rpx};
            width: 100#{rpx};
        }
    }

    .f-idcard.f-license {
        width: 340#{rpx};

        .idcard-box-pic {
            height: 174#{rpx};
            width: 214#{rpx};
            display: block;

            .idcard-alone {
                top: 36#{rpx};
            }
        }
    }
}
</style>