<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>
        <div class="north">
            <img src="../../assets/imgs/north.png" alt="">
        </div>
        <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,'border':(item.type == 'thorough'? 'none !important':'')}"
            >
                <span class="text" :class="item.w>(item.h*5) ? '': 'rowText'">{{item.name}}</span>
                <span class="remove" @click="removeItem(item.i)" v-if="showHeader">x</span>
                <!-- <span class="remove" @click="removeItem(item.i)" v-if="item.i && isEdit">x</span> -->
            </grid-item>
        </grid-layout>
        <div class="setBtns">
            <van-button @click="addItem" type="info" size="mini" v-if="!isViews">添加房间</van-button>
            <van-button @click="addOther" type="info" size="mini" v-if="!isViews">添加其他</van-button>
            <van-button @click="addBase" type="info" size="mini" v-if="!isViews">添加基础设施</van-button>
            <!-- <van-button @click="editItem" 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="title" show-cancel-button @confirm="saveRoomName" @cancel = "cancelDialog">
            <van-cell-group v-if="isRoom">
               <van-field v-model="roomName" label="房间名称" placeholder="请输入房间名称" />
               <van-field
                readonly
                clickable
                label="房间类型"
                :value="roomType"
                placeholder="选择房间类型"
                @click="showPicker = true"
                />
                
            </van-cell-group>
            <van-cell-group v-else-if="isBase">
               <van-field
                readonly
                clickable
                label="房间名称"
                :value="roomName"
                placeholder="选择房间名称"
                @click="showPicker = true"
                />
                
            </van-cell-group>
            <van-cell-group v-else>
                <van-field v-model="roomName" label="名称" placeholder="请输入名称" />
            </van-cell-group>
        </van-dialog>
        <van-popup v-model="showPicker" round position="bottom">
            <van-picker
                show-toolbar
                :columns="isRoom?roomArr:baseArr"
                @cancel="showPicker = false"
                @confirm="onConfirm"
                value-key="dictLabel"
            />
        </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,
            title:'',
            showPicker: false,
            roomType:'',
            roomName:'',
            roomArr: [],
            colorList:['#FF4433','#FF9800','#FFFF00','#0091EA'],
            isViews:false,// true:查看页面；  false: 添加页面
            showHeader:true,
            isRoom:true,//是否为添加房间
            isBase:false,
            baseName:'',
            baseArr:[],
            layoutData:[]
        }
    },
    props:{
        isView: {
            type: Boolean,
            default: false,
        },
    },
    mounted() {
        // screenfull.toggle(this.$refs.mapbox);
        // this.$nextTick(() => {
            // this.rotateBox();
        // });
        console.log('floorId==>>',this.$route.params.floorId )
        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 = []
                this.layoutData = res.data
                res.data.forEach((item) => {
                   item.position = JSON.parse(item.position)
                   item.position.i = item.id
                   item.position.id = item.id
                   if (!this.showHeader) {
                       item.position.isDraggable = false
                       item.position.isResizable = false
                   }
                   if (!this.isViews || item.position.type == 'thorough') { //添加页面不显示颜色
                        item.position.c = '#e6e5e5'
                    }else{
                         /** 
                         *  根据风险评分来匹配相应的颜色
                         *  score 风险评分字段
                         */
                        // item.score = Number(item.score)
                        // if (item.score>=21 && item.score <= 27) { //优
                        //     item.position.c = this.colorList[3]
                        // }else if(item.score>=14 && item.score <=20){ //良
                        //     item.position.c = this.colorList[2]
                        // }else if (item.score>=7&& item.score <= 13) { //中
                        //     item.position.c = this.colorList[1]
                        // }else if (item.score>=0 && item.score <= 6) { //差
                        //     item.position.c = this.colorList[0]
                        // }
                        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)
            })

            getFun('/risk/plan/dict/data/list',{
                dictType:'risk_plan_room_type'
            }).then(res=>{
                this.roomArr = res.data
            })
             getFun('/risk/plan/dict/data/list',{
                dictType:'risk_plan_base_room'
            }).then(res=>{
                this.baseArr = res.data
            })

        },
        // 增加
        addItem () {
            if (this.layout.find((item) => item.i == '')) {
                Toast.fail({
                    title: '提示',
                    forbidClick: true,
                    message: '请先点击确定，保存当前房间信息',
                })
                return
            }
            this.roomType = ''
            this.roomName = ''
            this.title = '创建房间'
            this.isRoom = true
            this.show = true
            this.isBase = false;
        },
        // 添加其他
        addOther(){
            if (this.layout.find((item) => item.i == '')) {
                Toast.fail({
                    title: '提示',
                    forbidClick: true,
                    message: '请先点击确定，保存当前房间信息',
                })
                return
            }
            this.isRoom = false;
            this.isBase = false;
            this.roomType = ''
            this.roomName = ''
            this.title = '创建其他'
            this.show = true
        },
        // 删除
        removeItem (val) {
            if (val == '') {
                const index = this.layout.map(item => item.i).indexOf(val);
                this.layout.splice(index, 1);
                return
            }
            this.$dialog.confirm({
                    title: '提示',
                    message: '是否删除',
            })
            .then(() => {
                postFun('/ledger/room/delete/'+val).then((res) => {
                    if (res.code == 200) {
                        Toast.success('删除成功');
                        this.getRoomInfo()
                    }
                    }).catch((err) => {
                        console.log('err==>>',err)
                    })
            })
            .catch(() => {
            // on cancel
            });
        },
        //添加基础设施
        addBase(){
             if (this.layout.find((item) => item.i == '')) {
                Toast.fail({
                    title: '提示',
                    forbidClick: true,
                    message: '请先点击确定，保存当前房间信息',
                })
                return
            }
            this.roomType = ''
            this.roomName = ''
            this.title = '添加基础设备'
            this.isRoom = false;
            this.isBase = true;
            this.show = true
        },
        // 移动后的事件
        movedEvent(i, newX, newY){
            this.layOutItem.x = newX
            this.layOutItem.y = newY
            // console.log('layOutItem==>>',this.layOutItem)
            // console.log('this.layout==>>',this.layout)
        },
        // 调整大小后的事件
        resizedEvent: function(i, newH, newW){
            this.layOutItem.w = newW
            this.layOutItem.h = newH
            // console.log('layOutItem==>>',this.layOutItem)
            // console.log('this.layout==>>',this.layout)
        },
        //关闭
        close(){
            history.go(-1)
        },
        //edger/room/update/batch
        // 确定 执行批量编辑保存
        confim(){
            // if (this.roomName == '') {
            //      Toast.fail({
            //         title: '提示',
            //         forbidClick: true,
            //         message: '请先添加房间！',
            //     })
            //     return
            // }
           let data = this.layoutData
           this.layoutData.forEach((item) => {
              item.position = JSON.stringify(item.position)
           })
            console.log('data==>>',data)
           postFun('/ledger/room/update/batch', data).then((res) => {
                if (res.code == 200) {
                    Toast.success('保存成功');
                    this.getRoomInfo()
                }
            }).catch((err) => {
               console.log('err==>>',err)
            })
        },
        //保存房间名称
        saveRoomName(){

            if (this.roomName == '') {
                 Toast.fail({
                    title: '提示',
                    forbidClick: true,
                    message: '请输入名称！',
                })
                return
            }



             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: '#e6e5e5',
                type:this.isRoom ? this.roomType :(this.isBase? '基础设施':'thorough'),
                isDraggable:true,
                isResizable:true
            }
            this.layout.push(this.layOutItem)
            // console.log('layOutItem==>>',this.layOutItem)
            let data = {
                floorId: this.$route.params.floorId ? this.$route.params.floorId : '18',
                name:this.roomName,
                position: JSON.stringify(this.layOutItem),
                roomType: this.isRoom ? this.roomType : (this.isBase? '基础设施':'9999'),
            }
            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)
            })
        },
        cancelDialog(){
            this.roomType = ''
            this.roomName = ''
        },
        onConfirm(value) {
            if(this.isRoom){
                this.roomType = value.dictValue;
            }else{
                this.roomName = value.dictValue
            }
            this.showPicker = false;
        },
    }
}
</script>

<style scoped >
.router-view{
    padding-bottom: 0px !important;
}
.wrap{
    /* height: 100vh; */
    width: 100vw;
   position: relative;
}
.north{
    position: absolute;
    display: inline-block;
    top: 1.5rem;
    right: 0.5rem;
    z-index: 999;
}
.north img{
    width: 15px;
    height: 30px;
}
.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;
}
::v-deep .van-dialog__header{
    padding-top: 15px !important;
    padding-bottom: 15px !important;
}
.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 {
    /* font-size: 6cqw; */
    display: flex;
    align-items: center;
    justify-content: center;
    /* position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0; */
    margin: auto;
    height: 100%;
    width: 100%;
}
.rowText{
    writing-mode:vertical-rl;
    -webkit-writing-mode: vertical-rl;
}
.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>