<template>
    <div id='top_toolbar'>
        <!-- 顶部编辑器 -->
        <div class='tit'>
            <!-- <a-icon type="left" /> -->
            {{this.urlMsg.floorName}}
        </div>
        <div class='tool'>
            <ul>
                <li @click='saveMsg'>
                    <img class='lock' :src='require(`./../../assets/images/t-save.png`)' alt />
                    <span>保存</span>
                </li>
                <!-- <li>
          <a-icon type="edit" />
          <span>撤销</span>
        </li>
        <li>
          <a-icon type="edit" />
          <span>重做</span>
                </li>-->
                <li class='zoom-window'>
                    <div>
                        <img class='lock' @click='handleScale(-1)' :src='require(`./../../assets/images/缩小.png`)' alt />
                        <span class='percentage'>{{scalePercent}}</span>
                        <img class='lock' @click='handleScale(1)' :src='require(`./../../assets/images/放大 amplification.png`)' alt />
                    </div>
                    <span>缩放窗口</span>
                </li>
                <li>
                    <a-dropdown :trigger='[`click`]'>
                        <div class='ant-dropdown-link dropdown-flex' @click='e => e.preventDefault()'>
                            <div>
                                <img class='lock' :src='require(`./../../assets/images/t-format.png`)' alt />
                                <div>对齐</div>
                            </div>
                            <a-icon type='caret-down' class='down-icon' />
                        </div>
                        <a-menu slot='overlay'>
                            <a-menu-item
                                :disabled='item.disable'
                                v-for='item in alignmentOptions'
                                :key='item.value'
                                @click='changeAlignItem(item.value)'
                            >
                                <img style='width: 16px;margin-right: 5px;' :src='require(`./../../assets/images/`+item.img+`.png`)' alt />
                                <span>{{item.label}}</span>
                            </a-menu-item>
                        </a-menu>
                    </a-dropdown>
                </li>
                <!-- <li>
          <a-icon type="edit" />
          <span>图层</span>
        </li>
        <li>
          <a-icon type="edit" />
          <span>组合</span>
        </li>
        <li>
          <a-icon type="edit" />
          <span>打散</span>
                </li>-->
                <li @click='lockItem'>
                    <Icon :name='!isLock?`lock`:`unlock`' />
                    <span>{{isLock?"解锁":"锁定"}}</span>
                </li>
                <li @click='deleteItem'>
                    <a-icon type='delete' />
                    <span>删除</span>
                </li>
                <li>
                    <a-upload
                        name='avatar'
                        class='avatar-uploader'
                        :show-upload-list='false'
                        :customRequest='customRequest'
                        action='https://jsonplaceholder.typicode.com/posts/'
                        :before-upload='beforeUpload'
                        @change='handleChange'
                    >
                        <img v-if='0' :src='imageUrl' alt='avatar' />
                        <div v-else>
                            <a-icon :type='loading ? `loading` : `edit`' />
                            <div class='ant-upload-text'>修改底图</div>
                        </div>
                    </a-upload>
                </li>
            </ul>
        </div>
        <div class='btn-list'>
            <div class='btn-list-item' @click='publishMap'>
                <Icon name='release' />
                <span>发布</span>
            </div>
        </div>
    </div>
</template>
<script>
import bus from '@/bus'
import { SGraphLayoutType } from '@saga-web/graph/lib'
import systym from './codeMapSystem.js'
import { MessageBox } from 'element-ui'
import { uploadImg } from '@/api/editer.js'

function getBase64(img, callback) {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
}
export default {
    data() {
        return {
            loading: false, //添加图片,是否显示loading
            imageUrl: '',
            isLock: false, //是否锁定
            focusItem: null,
            alignmentOptions: [
                //对齐数据
                {
                    value: SGraphLayoutType.Left,
                    label: '左对齐',
                    img: 't-left',
                    disable: true
                },
                {
                    value: SGraphLayoutType.Right,
                    label: '右对齐',
                    img: 't-right',
                    disable: true
                },
                {
                    value: SGraphLayoutType.Top,
                    label: '顶对齐',
                    img: 't-top',
                    disable: true
                },
                {
                    value: SGraphLayoutType.Bottom,
                    label: '底对齐',
                    img: 't-bottom',
                    disable: true
                },
                {
                    value: SGraphLayoutType.Center,
                    label: '水平居中对齐',
                    img: 't-center',
                    disable: true
                },
                {
                    value: SGraphLayoutType.Middle,
                    label: '垂直居中对齐',
                    img: 't-topandbottm',
                    disable: true
                },
                {
                    value: SGraphLayoutType.Vertical,
                    label: '垂直分布',
                    img: 't-vertical',
                    disable: true
                },
                {
                    value: SGraphLayoutType.Horizontal,
                    label: '水平分布',
                    img: 't-level',
                    disable: true
                }
            ],
            scale: 0.5, //底图缩放比例
            initScale: 0.5, //初始 底图缩放比例
            baseScale: 1.0, //底图基础缩放比例，由底图加载完成后，传入进来
            scaleStep: 0.05 // +-缩放步进
        }
    },
    computed: {
        // 缩放比例显示文本
        scalePercent() {
            return (this.scale * 100).toFixed(0) + '%'
        }
    },
    methods: {
        handleChange(info) {
            if (info.file.status === 'uploading') {
                this.loading = true
                return
            }
            if (info.file.status === 'done') {
                // Get this url from response in real world.
                getBase64(info.file.originFileObj, imageUrl => {
                    this.imageUrl = imageUrl
                    this.loading = false
                    console.log(imageUrl)
                    bus.$emit('changeImgUrl', imageUrl)
                })
            }
        },
        beforeUpload(file) {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
            if (!isJpgOrPng) {
                this.$message.error('You can only upload JPG file!')
            }
            const isLt2M = file.size / 1024 / 1024 < 2
            if (!isLt2M) {
                this.$message.error('Image must smaller than 2MB!')
            }
            return isJpgOrPng && isLt2M
        },
        // TODO: customRequest
        customRequest(info) {
            const formData = new FormData()
            formData.append('file', info.file)
            const postParams = formData
            uploadImg({ postParams }).then(res => {
                this.loading = false
                if (res.Result == 'success') {
                    this.$message.success(`${info.file.name} file uploaded successfully.`)
                    bus.$emit('changeImgUrl', res.EntityList[0])
                } else {
                    this.$message.error(`${info.file.name} file upload failed.`)
                }
            })
        },
        /**
         * @name getInitScale
         * @description 获取底图加载完成后的,初始化的缩放比例initScale,设置为baseScale
         */
        getInitScale() {
            bus.$on('initScale', baseScale => {
                this.baseScale = Number(baseScale || 1)
            })
        },
        /**
         * @name getMouseScale
         * @description 滚轮滚动，导致的底图缩放比例 逻辑处理
         */
        getMouseScale() {
            //  zoom 为缩放后改变的比例
            bus.$on('mouseScale', zoom => {
                this.scale = Number((zoom * this.initScale).toFixed(2))
            })
        },
        /**
         * @name handleScale
         * @param { Number } type  -1:点击 - 缩小底图; 1：点击 + 放大底图
         * @description 点击 -+ 缩放底图
         */
        handleScale(type) {
            // +-按钮禁用处理
            let flag = true
            // 设置缩放范围 0.05 ~ 100
            if ((type < 0 && this.scale <= 0.05) || (type > 0 && this.scale >= 100)) {
                flag = false
            } else {
                flag = true
            }
            if (!flag) {
                return false
            }
            // emit 缩放比例 this.scale / oldScale
            const oldScale = this.scale
            this.scale = Number((oldScale + type * this.scaleStep).toFixed(2))
            bus.$emit('changeScale', this.scale / oldScale)
        },
        FocusItemChanged(itemMsg) {
            this.focusItem = null
            this.alignmentOptions.forEach(el => {
                el.disable = true
            })
            if (itemMsg.itemList.length == 1) {
                this.isLock = itemMsg.itemList[0].moveable
                this.focusItem = itemMsg.itemList[0]
            } else if (itemMsg.itemList.length > 1) {
                this.alignmentOptions.forEach(el => {
                    el.disable = false
                })
            }
        },
        lockItem() {
            if (this.focusItem) {
                this.isLock = !this.isLock
                this.focusItem.moveable = this.isLock
            } else {
                this.$message.error('请选择指定对象！', 1)
            }
        },
        saveMsg() {
            // this.$message.success("保存成功！", 1);
            bus.$emit('saveMsgItem')
        },
        // 删除item
        deleteItem() {
            console.log(this.focusItem)
            if (this.focusItem) {
                bus.$emit('deleiteItem')
                // this.focusItem = null;
                this.$message.success('删除成功', 1)
            } else {
                this.$message.error('请选择指定对象！', 1)
            }
        },
        // 发布图例
        publishMap() {
            MessageBox.confirm('确认后即发布到平台?', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    bus.$emit('publishMap')
                })
                .catch(() => {})
        },
        // 对齐item
        changeAlignItem(val) {
            bus.$emit('changeAlignItem', val)
        }
    },
    async mounted() {
        bus.$on('FocusItemChanged', itemMsg => {
            console.log('itemMsg', itemMsg)
            this.FocusItemChanged(itemMsg)
        })
        // 获取底图加载完成后的初始sacle
        await this.getInitScale()
        // 监听滚轮 底图缩放比例
        this.getMouseScale()
    },
    created() {
        const href = window.location.href
        // 路由
        // const route = href.split("?")[0];
        // 参数处理
        let params = href.split('?')[1]
        if (!params) {
            // 参数有问题
            return false
        }
        params = decodeURIComponent(params)
        // params = "categoryId=NTXT&ProjectID=5&BuildingID=1&FloorID=1"; // mock 参数
        const paramsArr = params.split('&')
        console.log('paramsArr', paramsArr)
        const obj = {}
        paramsArr.map(item => {
            const arr = item.split('=')
            obj[arr[0]] = arr[1]
        })
        this.urlMsg = obj
        const FloorName = this.urlMsg.FloorName ? this.urlMsg.FloorName : ''
        this.urlMsg.floorName = systym[this.urlMsg.categoryId] + '-' + FloorName
    }
}
</script>
<style lang="less" scoped>
ul,
li {
    /*margin: 0;*/
    /*padding: 0;*/
    list-style: none;
}
#top_toolbar {
    width: 100%;
    height: 60px;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 24px 0 24px;
    .tit {
        // flex: 1;
        font-size: 18px;
        font-weight: bold;
        color: #1f2429;
    }
    .tool {
        ul {
            display: flex;
            li {
                display: flex;
                justify-content: center;
                flex-direction: column;
                /*width: 62px;*/
                padding: 0 7px;
                margin-left: 7px;
                font-size: 12px;
                align-items: center;
                text-align: center;
                cursor: pointer;
                img {
                    width: 16px;
                    height: 16px;
                }
                .percentage {
                    display: inline-block;
                    width: 35px;
                    border-bottom: 1px solid #c3c7cb;
                    margin: 0 13px;
                    font-size: 14px;
                }
                .dropdown-flex {
                    display: flex;
                    align-items: center;
                    .down-icon {
                        margin-left: 12px;
                    }
                }
            }
            li:hover {
                background: #f5f6f7;
            }
            .zoom-window {
                border-left: 1px solid #8d9399;
                border-right: 1px solid #8d9399;
            }
        }
    }
    .btn-list {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 72px;
        .btn-list-item {
            display: flex;
            justify-content: center;
            flex-direction: column;
            span {
                font-size: 12px;
            }
            cursor: pointer;
        }
    }
}
/deep/ .ant-dropdown-menu-item {
    display: flex;
    align-items: center;
}
</style>