<template>
    <div class="wrap" ref="mapmidbox">
        <van-sticky v-if="showHeader">
            <header class="header">
                <span @click="close" class="iconLeft"> 关闭</span>
                <span>{{text}}</span>
                <span  @click="confim" class="iconRight" v-show="!isViews">确定</span>
                <span  class="iconRight" v-show="isViews"></span>
            </header>
        </van-sticky>
        <grid-layout :layout.sync="layout"
                     :col-num="colNum"
                     :row-height="30"
                     :vertical-compact="false"
                     :use-css-transforms="true"
                     :prevent-collision="false"
                     :preventCollision="true"
        >
            <grid-item v-for="item in layout"
                       :static="item.static"
                       :x="item.x"
                       :y="item.y"
                       :w="item.w"
                       :h="item.h"
                       :i="item.i"
                       :key="item.i"
                       :isDraggable="item.isDraggable"
                       :isResizable="item.isResizable"
                       @resized="resizedEvent"
                       @moved="movedEvent"
                       :style="{'backgroundColor':item.c,}"
            >
                <span class="text">{{item.name}}</span>
                <span class="remove" @click="removeItem(item.i)" v-if="!item.i">x</span>
            </grid-item>
        </grid-layout>
        <div class="setBtns">
            <van-button @click="addItem" type="info" size="mini" v-if="!isViews">添加房间</van-button>
            <van-grid direction="horizontal" :column-num="2" class="footer" v-if="isViews">
                风险等级图例:
                <span class="riskTab type1"></span>重大风险
                <span class="riskTab type2"></span>较大风险
                <span class="riskTab type3"></span>一般风险
                <span class="riskTab type4"></span>较小风险
            </van-grid>
        </div>
        <van-dialog v-model="show" title="创建房间" show-cancel-button @confirm="saveRoomName">
            <van-cell-group>
               <van-field v-model="roomName" label="房间名称" placeholder="请输入房间名称" />
               <van-field
                readonly
                clickable
                label="房间类型"
                :value="roomType"
                placeholder="选择房间类型"
                @click="showPicker = true"
                />
                
            </van-cell-group>
        </van-dialog>
        <van-popup v-model="showPicker" round position="bottom">
            <van-picker
                show-toolbar
                :columns="columns"
                @cancel="showPicker = false"
                @confirm="onConfirm"
            />
        </van-popup>
    </div>
</template>

<script>
import { GridLayout, GridItem } from "vue-grid-layout"
import screenfull from "screenfull";
import { Toast } from 'vant';
import { getFun, postFun } from "@/service/table.js";
// 动态添加/删除
export default {
    name:'riskView',
    components: {
        GridLayout,
        GridItem
    },
    data() {
        return {
            text:'房间位置绘制工具',
            layout: [
                // { x: 0, y: 0, w: 2, h: 3, i: "1",name: "办公室1",c:'#FF4433',isDraggable:false,isResizable:false,},
                // { x: 2, y: 0, w: 2, h: 3, i: "2",name: "办公室2",c:'#FF9800',isDraggable:false,isResizable:false},
                // { x: 4, y: 0, w: 2, h: 3, i: "3",name: "办公室2",c:'#FFFF00',isDraggable:false,isResizable:false},
                // { x: 6, y: 0, w: 2, h: 3, i: "4",name: "办公室2",c:'#0091EA',isDraggable:false,isResizable:false},
                // { x: 0, y: 3, w: 2, h: 3, i: "5",name: "办公室2",c:'#FF4433',isDraggable:false,isResizable:false},
            ],
            draggable: false,
            resizable: true,
            colNum: 12,
            isScreenFull :null,
            layOutItem:{},//新增的房间对象
            show:false,
            showPicker: false,
            roomType:'',
            roomName:'',
            columns: ['办公', '餐饮', '住宅', '超市'],
            colorList:['#FF4433','#FF9800','#FFFF00','#0091EA'],
            isViews:false,// true:查看页面；  false: 添加页面
            showHeader:true
        }
    },
    props:{
        isView: {
            type: Boolean,
            default: false,
        },
    },
    mounted() {
        // screenfull.toggle(this.$refs.mapbox);
        // this.$nextTick(() => {
            // this.rotateBox();
        // });
        if (this._props.isView) {
            console.log('作为组件传值==>>',)
            this.isViews = true
            this.showHeader = false
        }
        if (this.$route.params.isView) {
            this.isViews =  true
            this.initRotate();
           window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", this.orientationChange, false);   
        }
        this.getRoomInfo()
    },
    methods: {
        orientationChange(){
            if (window.orientation === 180 || window.orientation === 0) {   
               console.log('竖屏状态！');  
            }   
            if (window.orientation === 90 || window.orientation === -90 ){   
                console.log('横屏状态！');  
            }    
            // let width = document.documentElement.clientWidth//页面宽度
            //    let  height = document.documentElement.clientHeight//页面高度
            //     console.log('width==>>',width)
            //     console.log('height==>>',height)
                  this.rotateBox()
        },
        initRotate(){
            let width = document.documentElement.clientWidth,//页面宽度
                height = document.documentElement.clientHeight,//页面高度
                wrapper = this.$refs.mapmidbox,//需要横屏的块，与全屏的块要区分开，不区分全屏的块无法显示横屏效果
                style = "";//样式
                console.log('width==>>',width)
                console.log('height==>>',height)
                 style += "width:" + height + "px;";
                style += "height:" + width + "px;";
                style += "-webkit-transform: rotate(90deg); transform: rotate(90deg);";
                // 注意旋转中点的处理
                style +=
                "-webkit-transform-origin: " + width / 2 + "px " + width / 2 + "px;";
                style += "transform-origin: " + width / 2 + "px " + width / 2 + "px;";
                wrapper.style.cssText = style;
        },
        rotateBox() {
            this.isScreenFull = !this.isScreenFull;//是否全屏状态
            let width = document.documentElement.clientWidth,//页面宽度
                height = document.documentElement.clientHeight,//页面高度
                wrapper = this.$refs.mapmidbox,//需要横屏的块，与全屏的块要区分开，不区分全屏的块无法显示横屏效果
                style = "";//样式
                console.log('width==>>',width)
                console.log('height==>>',height)
            // if (height < width) {//注意原来就是宽屏时不用横屏
            //     return;
            // }
            if (height < width) {
                // 横屏
                style += "width:" + height + "px;";
                style += "height:" + width + "px;";
                style += "-webkit-transform: rotate(0deg); transform: rotate(0deg);";
                // 注意旋转中点的处理
                style +=
                "-webkit-transform-origin: " + width / 2 + "px " + width / 2 + "px;";
                style += "transform-origin: " + width / 2 + "px " + width / 2 + "px;";
            } else {
                // 竖屏
                // style += "width:" + height + "px;";
                // style += "height:" + width + "px;";
                // style += "-webkit-transform: rotate(90deg); transform: rotate(90deg);";
                // // 注意旋转中点的处理
                // style +=
                // "-webkit-transform-origin: " + width / 2 + "px " + width / 2 + "px;";
                // style += "transform-origin: " + width / 2 + "px " + width / 2 + "px;";
                style += "width:100%";
                style += "height:100%;";
                style += "-webkit-transform: rotate(0); transform: rotate(0);";
                style += "-webkit-transform-origin: 0 0;";
                style += "transform-origin: 0 0;";
            }
            console.log('style==>>',style)
            wrapper.style.cssText = style;
            },
        getRoomInfo(){
            let data = {
                floorId: this.$route.params.floorId ? this.$route.params.floorId : '18'
            }
            getFun('/ledger/room/list',data).then((res) => {
              if (res.code == 200) {
                this.layout = []
                res.rows.forEach((item) => {
                   item.position = JSON.parse(item.position)
                   item.position.i = item.id
                   item.position.isDraggable = false
                   item.position.isResizable = false
                   if (!this.isViews) { //添加页面不显示颜色
                        item.position.c = '#eee'
                    }else{
                        item.position.c = this.colorList[Math.floor(Math.random()*4)]
                    }
                   this.layout.push(item.position)
                })
                // console.log('layout==>>',this.layout)
              }
            }).catch((err) => {
               console.log('err==>>',err)
            })
        },
        // 增加
        addItem: function () {
            if (this.layout.find((item) => item.i == '')) {
                Toast.fail({
                    title: '提示',
                    forbidClick: true,
                    message: '一次只能增加一个房间',
                })
                return
            }
            this.roomType = ''
            this.roomName = ''
            this.show = true
        },
        // 删除
        removeItem: function (val) {
            if (val == '') {
                const index = this.layout.map(item => item.i).indexOf(val);
                this.layout.splice(index, 1);
                return
            }
            postFun('/ledger/room/delete/'+val).then((res) => {
              if (res.code == 200) {
                Toast.success('删除成功');
                this.getRoomInfo()
              }
            }).catch((err) => {
               console.log('err==>>',err)
            })
        },
        // 移动后的事件
        movedEvent(i, newX, newY){
            this.layOutItem.x = newX
            this.layOutItem.y = newY
            console.log('layOutItem==>>',this.layOutItem)
        },
        // 调整大小后的事件
        resizedEvent: function(i, newH, newW){
            this.layOutItem.w = newW
            this.layOutItem.h = newH
            console.log('layOutItem==>>',this.layOutItem)
        },
        //关闭
        close(){
            history.go(-1)
        },
        // 确定  保存房间信息
        confim(){
            if (this.roomName == '') {
                 Toast.fail({
                    title: '提示',
                    forbidClick: true,
                    message: '请先添加房间！',
                })
                return
            }
            let data = {
                floorId: this.$route.params.floorId ? this.$route.params.floorId : '18',
                name:this.roomName,
                position: JSON.stringify(this.layOutItem),
                roomType: this.roomType
            }
            postFun('/ledger/room/save', data).then((res) => {
                if (res.code == 200) {
                    Toast.success('提交成功');
                    this.getRoomInfo()
                    this.roomType = ''
                    this.roomName = ''
                }
            }).catch((err) => {
               console.log('err==>>',err)
            })
        },
        //保存房间名称
        saveRoomName(){
             this.layOutItem = {
                x: (this.layout.length * 2) % (this.colNum || 12),
                y: this.layout.length + (this.colNum/2 || 12),
                w: 2,
                h: 3,
                i: '',
                name: this.roomName,
                c: '#0091EA',
                type:this.roomType,
                isDraggable:true,
                isResizable:true
            }
            this.layout.push(this.layOutItem)
            // console.log('layOutItem==>>',this.layOutItem)
        },
        onConfirm(value) {
            this.roomType = value;
            this.showPicker = false;
        },
    }
}
</script>

<style scoped >
.router-view{
    padding-bottom: 0px !important;
}
.wrap{
    height: 100vh;
    width: 100vw;
    /* transform: rotate(90deg);
   transform-origin: bottom left; */
   position: relative;
}
.footer{
    /* position: fixed; */
    /* left: 0; */
    /* bottom: 0; */
    font-size: 0.3rem;
    font-weight: 600;
}
.riskTab{
    display: inline-block;
    width: 50px;
    height: 20px;
    margin: 0 10px 0px 15px;
    border-radius: 5px;
}
.type1{
    background-color: #FF4433;
}
.type2{
    background-color: #FF9800;
}
.type3{
    background-color: #FFFF00;
}
.type4{
    background-color: #0091EA;
}
.layoutJSON {
    background: #ddd;
    border: 1px solid black;
    padding: 10px;
}

.columns {
    -moz-columns: 120px;
    -webkit-columns: 120px;
    columns: 120px;
}

/*************************************/
.setBtns{
    /* position: fixed;
    top:auto;
    right: auto;
    left: 0;
    bottom: 0; */
    margin-top: 10px;
    font-size: 0.3rem;
    padding: 10px;
    vertical-align: middle;
    display: flex;
    align-items: flex-start;
    flex-direction: column;
}
.setBtns .van-button--mini{
    padding: 0 10px;
}
.remove {
    position: absolute;
    right: 2px;
    top: 0;
    cursor: pointer;
}
.vue-grid-item {
    -ms-touch-action: none;
    touch-action: none;
    box-sizing: border-box;
    container-type: inline-size;
}
.vue-grid-layout {
    background: #f0f1f5;
}

.vue-grid-item:not(.vue-grid-placeholder) {
    background: #ccc;
    border: 1px solid black;
}

.vue-grid-item .resizing {
    opacity: 0.9;
}

.vue-grid-item .static {
    background: #cce;
}

.vue-grid-item .text {
    writing-mode:vertical-rl;
    -webkit-writing-mode: vertical-rl;
    font-size: 10cqw;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    height: 100%;
    width: 100%;
}

.vue-grid-item .no-drag {
    height: 100%;
    width: 100%;
}

.vue-grid-item .minMax {
    font-size: 12px;
}

.vue-grid-item .add {
    cursor: pointer;
}

.vue-draggable-handle {
    position: absolute;
    width: 20px;
    height: 20px;
    top: 0;
    left: 0;
    background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><circle cx='5' cy='5' r='5' fill='#999999'/></svg>") no-repeat;
    background-position: bottom right;
    padding: 0 8px 8px 0;
    background-repeat: no-repeat;
    background-origin: content-box;
    box-sizing: border-box;
    cursor: pointer;
}
.header{
    width:100%;
    height:1.2rem;
    background:#2980F7;
    text-align: center;
    line-height: 1.5rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.iconLeft{
    color: white;
    font-size: 12px;
    transform: scale(0.8);
}
.header span{
    color: white;
    font-size: 16px;
    line-height: 1.2rem;
    margin: auto;
    font-family: 'Microsoft YaHei';
}
.iconRight{
    color: white;
    font-size: 12px;
    transform: scale(0.8);
}
</style>