<template>
    <!-- 查看平面图页面 -->
    <div id='repetitionGraphy'>
        <div class='buttons'>
            <el-button icon='el-icon-back' size='mini' @click='backRouter'></el-button>
            <template v-if="!hasModel">
                <el-upload class='upload-demo' action='string' :http-request='uploadAndSubmit' :show-file-list='false' v-if="step==-1">
                    <el-button size="mini">{{hasGraph?'替换平面图图片':'上传平面图图片'}}</el-button>
                </el-upload>
                <el-button style='float:right;' size='mini' type='primary' v-if="step==0" @click="nextStep">下一步</el-button>
                <el-button style='float:right;' size='mini' type='primary' v-if="step==1" @click="nextStep">保存</el-button>
                <el-button style='float:right;' size='mini' v-if="step==1" @click="lastStep">上一步</el-button>
            </template>
            <template v-else>
                <el-button v-if='!isEdit' size='mini' @click='changeGraphy'>{{hasGraph?'替换模型文件':'关联模型文件'}}</el-button>
                <el-button v-if='(sign||otherSign)&&!isEdit' size='mini' @click='editGraphy'>编辑平面图</el-button>
                <el-button v-if='isEdit' size='mini' @click='cancel'>取消</el-button>
                <el-button v-if='isEdit' size='mini' @click='confirm' type='primary'>确认</el-button>
            </template>
            <span style='float:right;' v-if='file.FolderName'>当前对应的模型文件：{{file.FolderName}} - {{file.FloorName}}</span>
        </div>
        <!-- 展示图片 -->
        <div class='drawImg'>
            <div style="width: 100%;height: 100%;position: relative;" v-if="hasGraph">
                <drawFloor ref='drawFloor' :isEdit='isEdit' :showTools='true' :id='1' @changeSign='changeSign' @getGraphSuc="getGraphSuc"></drawFloor>
                <div class="stepContainer" v-if="step>-1">
                    <el-steps :active="step" align-center finish-status="success" process-status="process">
                        <el-step title="设定比例尺" :description="stepDes[0]"></el-step>
                        <el-step title="楼层对齐" :description="stepDes[1]"></el-step>
                    </el-steps>
                </div>
                <ul class="floorList" v-if="step==1">
                    <li style="border-bottom:1px solid #ccc;text-align: center;padding: 0">选择对齐楼层</li>
                    <li v-for="t in floorList" :key="t.FloorID">
                        <el-radio v-model="floorRadio" :label="t" @change="changeFloor" :disabled="t.FloorID == FloorID">{{t.FloorLocalID || t.FloorLocalName}}</el-radio>
                    </li>
                </ul>
            </div>
            <div style="width: 100%;height: 100%" v-else>
                <div class="center" style="padding-top: 300px">
                    <i class="icon-wushuju iconfont"></i>暂无平面图
                </div>
            </div>
        </div>
        <!-- 查看图片弹窗 -->
        <checkGraphy ref='checkGraphy' @refresh='refresh' :alreadyRelatedModel='alreadyRelatedModel'></checkGraphy>
        <!-- 设定比例尺弹窗 -->
        <setScaleDialog ref="setScaleDialog"></setScaleDialog>
    </div>
</template>
<script>
import drawFloor from './drawGraphy/drawFloor'
import checkGraphy from './drawGraphy/checkGraphy' //查看图片
import setScaleDialog from '@/components/ready/buildfloor/setScaleDialog'
import { floorUpdateOutline, floorQueryAndSign, manageUpdateFloor } from '@/api/scan/request'
import { getFileNameById, countModel } from '@/api/model/file'
import { EditLineItem, SItemStatus, SImageShowType, IconTextItem} from "@saga-web/cad-engine"
import { SColor } from "@saga-web/draw"
import { SImageItem } from '@saga-web/graph/lib'
export default {
    components: {
        drawFloor,
        checkGraphy,
        setScaleDialog
    },
    data() {
        return {
            modelId: '', //
            isEdit: false, // 是否编辑模式
            FloorID: '',
            file: {},
            alreadyRelatedModel: [],
            sign: false,
            otherSign: false,
            hasGraph: false, // 当前楼层是否有平面图
            hasModel: false, // 项目中时候有模型文件
            step: -1, // 当前处于第几步 同时为比例尺item判断是否创建的可编辑的依据
            key: '', // 当楼层图为图片时图的key
            stepDes: [
                '请在图上点击两点绘制线段并标记实际长度',
                '请移动图片与其他楼层对齐'
            ], // 描述文字
            floorList: [], // 当前建筑下所有楼层
            floorRadio: '', // 
            imgService: `/image-service/common/image_get?systemId=dataPlatform&key=`,
            curImgItem: null, // 对齐的楼层图片
            scaleItem: null, // 比例尺item
            baseImgItem: null, // 当前楼层图的图片
        }
    },
    created() {
        this.modelId = this.$route.query.modelId
        this.FloorID = this.$route.query.FloorID
        this.BuildID = this.$route.query.BuildID
        this.BuildName = this.$route.query.BuildName
        if (this.modelId != '') {
            this.hasGraph = true;
            const temp = this.modelId.split('.');
            if (temp[1] == 'png' || temp[1] == 'jpg') {
                // return
            } else {
                this.init()
            }
        }
        this.getCountModel()
    },
    mounted() {},
    methods: {
        init() {
            this.getFileName(this.modelId)
            this.getFloorData()
        },
        // 返回路由
        backRouter() {
            this.$router.push({ name: 'buildFloor' })
        },
        // 替换模型文件
        changeGraphy() {
            this.$refs.checkGraphy.showDialog({ FloorID: this.FloorID, BuildID: this.BuildID }) 
        },
        // 确认保存
        confirm() {
            let sceneMark = this.$refs.drawFloor.drawMainScene.sceneMark,
                Outline = null
            if (sceneMark) {
                if (sceneMark.outLine.length < 3) {
                    this.$message.warning('请添加轮廓线')
                    return
                }
                if (!sceneMark.closeFlag) {
                    this.$message.warning('请按回车闭合轮廓线')
                    this.$refs.drawFloor.focus()
                    return
                }
                Outline = this.$refs.drawFloor.drawMainScene.sceneMark.outLine
                Outline = Outline.map((t) => {
                    return {
                        x: t.x.toFixed(2),
                        y: -t.y.toFixed(2),
                    }
                })
            }
            let pa = {
                Content: [{ FloorID: this.FloorID, Outline: Outline }],
                Projection: ['Outline'],
            }
            floorUpdateOutline(pa, (res) => {
                this.isEdit = false
                this.$message.success('更新成功')
            })
        },
        // 取消
        cancel() {
            this.isEdit = false
            this.$refs.drawFloor.init()
        },
        // 编辑平面图
        editGraphy() {
            this.isEdit = true
        },
        // 替换模型文件成功
        refresh(modelId) {
            this.modelId = modelId
            this.hasGraph = true;
            const temp = this.modelId.split('.');
            if (temp[1] && temp[1] != 'png' && temp[1] != 'jpg') {
                this.key = '';
                this.getFileName(this.modelId)
            }
        },
        // 获取文件夹名称
        getFileName(modelId) {
            if (!modelId) return
            let pa = {
                Id: modelId,
            }
            getFileNameById(pa, (res) => {
                this.file = res
            })
        },
        // 获取楼层
        getFloorData() {
            let floorParam = {
                PageSize: 1000,
                Filters: `BuildID='${this.BuildID}'`,
                Orders: 'FloorSequenceID desc'
            }
            floorQueryAndSign(floorParam, (res) => {
                this.floorList = res.Content;
                // todo
                this.floorRadio = res.Content[0];
                this.alreadyRelatedModel = res.Content.map((t) => {
                    if (t.FloorID != this.FloorID) return t.ModelId
                    this.sign = t.Sign > 0
                    this.FloorName = t.FloorLocalName || t.FloorName
                    this.$refs.drawFloor.buildFloorName = `${this.BuildName}-${this.FloorName}`
                }).filter((t) => t)
            })
        },
        changeSign(flag) {
            this.otherSign = flag
        },
        // 统计项目下是否有模型文件
        getCountModel(){
            countModel({}, res => {
                this.hasModel = res.Count > 0
            })
        },
        //上传图片
        uploadAndSubmit(item) {
            let file = item.file
            let reader = new FileReader()
            let vm = this
            let fileType = file.name.split('.')
            let type = fileType[fileType.length - 1]
            let uploadKey = file.uid
            reader.onloadend = function () {
                // 这个事件在读取结束后，无论成功或者失败都会触发
                if (reader.error) {
                } else {
                    // document.getElementById("bytesRead").textContent = file.size;
                    // 构造 XMLHttpRequest 对象，发送文件 Binary 数据
                    var xhr = new XMLHttpRequest()
                    xhr.open(
                        /* method */ 'POST',
                        /* target url */
                        '/image-service/common/image_upload?systemId=dataPlatform&secret=9e0891a7a8c8e885&overwrite=true&key=' + uploadKey + '.' + type
                        /*, async, default to true */
                    )
                    //xhr.overrideMimeType("application/octet-stream");
                    xhr.send(reader.result)
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4) {
                            if (xhr.status == 200) {
                                vm.key = uploadKey + '.' + type
                                // 将图片展示
                                vm.refresh(uploadKey + '.' + type)
                                // 设置步骤为第一步
                                vm.step = 0;
                            }
                        }
                    }
                }
            }
            reader.readAsArrayBuffer(file)
        },
        // 更新楼层key 为图片,同时更新比例尺
        updateFloorKey(){
            const scaleItem = this.$refs.drawFloor.scaleItem;
            // 比例尺坐标处理,当底图被对齐操作后,需要跟随底图改变坐标
            const line = scaleItem.line.map(t => {
                return { x: t.x + this.baseImgItem.x, y: t.y + this.baseImgItem.y }
            })
            let Param = {
                Content: [{
                    FloorId: this.FloorID,
                    StructureInfo: { FloorMap: this.key },
                    Properties: {
                        X: this.baseImgItem.x, 
                        Y: this.baseImgItem.y,
                        Line: line,
                        Text: scaleItem.text
                    }
                }],
                Projection: ['StructureInfo', 'Properties'],
            }
            manageUpdateFloor(Param, (res) => {
                this.$message.success('更新成功')
                this.step = -1;
                this.baseImgItem.globalAlpha = 1
                this.removeLast()
                this.$refs.drawFloor.fit()
            })
        },
        // 根据modelid初始化
        initFromModelId(id){
            if (id.split('.')[1] == 'png' || id.split('.')[1] == 'jpg') {
                this.$refs.drawFloor.initGraphy(id, 3)
            } else {
                this.$refs.drawFloor.initGraphy(id, 1)
            }
        },
        // 上一步
        lastStep() {
            this.step = 0;
            this.$refs.drawFloor.scaleItem.show()
            this.baseImgItem.globalAlpha = 1
            this.removeLast()
        },
        // 下一步||保存
        nextStep() {
            this.baseImgItem = this.$refs.drawFloor.drawMainScene.imgList[0]
            this.baseImgItem.globalAlpha = 0.2
            this.baseImgItem.moveable = true;
            // 下一步
            if (this.step == 0) {
                this.step = 1;
                this.$refs.drawFloor.scaleItem.hide();
                // 获取楼层列表
                this.getFloorData()
            } else if (this.step == 1) {
                // 保存
                this.updateFloorKey();
            }
        },
        // 加载图成功 仅在底图为图片时返回成功
        getGraphSuc() {
            const scaleItem = this.$refs.drawFloor.scaleItem
            if (this.step == 0) {
                scaleItem.status = SItemStatus.Create;
                this.$refs.drawFloor.drawMainScene.grabItem = scaleItem;
                scaleItem.connect('changText', this, this.changeText)
                scaleItem.moveable = true;
            } else if (this.step == -1) {
                scaleItem.status = SItemStatus.Normal;
            }
        },
        // 修改比例尺文字
        changeText(t, e) {
            this.$refs.setScaleDialog.showDialog(t)
        },
        // 第二部楼层修改
        changeFloor(v) {
            this.removeLast();
            if (v.StructureInfo && v.StructureInfo.FloorMap) {
                const url = this.imgService + v.StructureInfo.FloorMap
                this.curImgItem = new SImageItem(null, url);
                this.curImgItem.globalAlpha = 0.2;
                this.curImgItem.showType = SImageShowType.AutoFit;
                if (v.Properties) {
                    try {
                        // 计算比例尺- todo
                        this.curImgItem.showType == SImageShowType.Full;
                        this.curImgItem.moveTo(v.Properties.x, v.Properties.y);
                        this.curImgItem.width = v.Properties.width;
                        this.curImgItem.height = v.Properties.height;
                    } catch (err) {
                        console.log(err);
                    }
                }
                this.$refs.drawFloor.drawMainScene.addItem(this.curImgItem);
                this.$refs.drawFloor.fit()
            }
        },
        // 清除上一张底图
        removeLast() {
            if (this.curImgItem) {
                this.$refs.drawFloor.drawMainScene.removeItem(this.curImgItem);
                this.curImgItem = null;
            }
        }
    },
    watch: {
        modelId(n, o) {
            if (n != o) {
                if (n) {
                    this.$nextTick(()=>{
                        this.initFromModelId(n)
                    })
                }
            }
        },
    },
}
</script>
<style lang="less">
#repetitionGraphy {
    width: 100%;
    height: 100%;
    background: #fff;
    position: relative;
    padding: 10px;
    box-sizing: border-box;
    .drawImg {
        width: 100%;
        margin-top: 10px;
        height: calc(100% - 40px);
    }
    .upload-demo {
        display: inline-block;
    }
    .stepContainer {
        width: 100%;
        position: absolute;
        top: 0;
        left: 50%;
        margin-left: -50%;
        z-index: 9;
        background-color: #fff;
    }
    .floorList {
        position: absolute;
        width: 100px;
        max-height: 250px;
        overflow-x: hidden;
        overflow-y: auto;
        left: 40px;
        top: 200px;
        z-index: 10;
        background: #fff;
        border: 1px solid #ccc;
        li {
            box-sizing: border-box;
            padding: 0 10px;
            width: 100%;
        }
    }
}
</style>
