<template>
    <view class="new">
        <template v-if="type == 1">
            <view class="content">
                <uni-forms>
                    <uni-forms-item label="设备识别码">
                        <view style="display: flex">
                            <uni-easyinput type="text" v-model="formData.nDid" placeholder="请输入设备识别码"/>
                            <uni-icons
                                type="camera"
                                color="#007aff"
                                size="26"
                                class="ml20"
                                @click="scanCode"
                            ></uni-icons>
                        </view>
                    </uni-forms-item>
                </uni-forms>
            </view>
            <view class="btn-wrap">
                <view class="btn-wrap-item" @click="register"> 发起注册</view>
            </view>
        </template>
        <template v-else>
            <view class="content">
                <uni-forms>
                    <uni-forms-item label="项目">
                        <uni-data-select
                            v-model="formData.projectId"
                            :localdata="projectRange"
                            @change="queryTopologyDiagramPage"
                            disabled
                            :clearable="false"
                        ></uni-data-select>
                    </uni-forms-item>
                    <!-- <uni-forms-item label="型号">
                        <uni-data-select v-model="formData.type" :localdata="typeRange"
                            @change="typeChange(item)"></uni-data-select>
                    </uni-forms-item> -->
                    <uni-forms-item label="拓扑图" v-if="formData.projectId">
                        <view style="display: flex">
                            <view style="flex: 1">
                                <view v-if="formData.topologyDiagramUrl">
                                    <image :src="formData.topologyDiagramUrl" style="width: 100%" mode="widthFix"/>
                                </view>
                                <view v-else class="gplot gplot-empty center" @click="chooseGplot"> 选择拓扑图</view>
                            </view>
                            <uni-icons
                                type="image"
                                color="#007aff"
                                size="26"
                                class="ml20"
                                @click="chooseGplot"
                            ></uni-icons>
                        </view>
                    </uni-forms-item>
                    <uni-forms-item label="监测点" v-if="pointList.length && formData.topologyDiagramUrl">
                        <view
                            class="point-item"
                            v-for="(item2, index2) in pointList"
                            :key="index2"
                            @click="editPoint(item2, index2)"
                        >
                            <view style="flex: 1" v-if="item2.name">{{ item2.name }}</view>
                            <view style="flex: 1; color: #999" v-else>请选择监测点</view>
                            <uni-icons type="compose" color="#007aff" size="26" class="ml20"></uni-icons>
                        </view>
                    </uni-forms-item>
                </uni-forms>
            </view>
            <image class="gplot-image" ref="gplot-image" :src="formData.topologyDiagramUrl" mode="widthFix"/>
            <view class="btn-wrap">
                <!-- <view class="btn-wrap-item" @click="add"> 添加监测点 </view> -->
                <view class="btn-wrap-item" @click="submit"> 提交</view>
            </view>
            <uni-drawer ref="gplot" mode="right" :mask-click="false">
                <scroll-view style="height: 100%" scroll-y="true">
                    <view class="content">
                        <image
                            class="gplot gplot-box"
                            mode="aspectFill"
                            :class="{ 'gplot-active': key == activeGplot }"
                            :src="item.filePath"
                            @click="activeGplot = key"
                            v-for="(item, key) in imageList"
                            :key="key"
                        />
                        <view class="btn-wrap">
                            <view class="btn-wrap-item" @click="closeDrawer"> 取消</view>
                            <view class="btn-wrap-item ml20" @click="confirmGplot"> 确定</view>
                        </view>
                    </view>
                </scroll-view>
            </uni-drawer>
            <uni-drawer ref="point" mode="right" :mask-click="false">
                <scroll-view style="height: 100%" scroll-y="true">
                    <view style="background: #fff">
                        <view class="map-pin-box">
                            <image class="gplot" mode="widthFix" :src="formData.topologyDiagramUrl"/>

                            <movable-area class="map-pin-box-area">
                                <movable-view :x="point.lat" :y="point.lng" direction="all" @change="dragPoint">
                                    <view class="point">
                                        {{ point.alias || point.name }}
                                    </view>
                                </movable-view>
                            </movable-area>
                        </view>
                    </view>
                    <view class="content">
                        <view class="content-des">请拖动图中的文字选择监测点位置</view>
                        <uni-forms>
                            <uni-data-select
                                v-model="point.linePostion"
                                :localdata="positionList"
                                @change="positionChange"
                            ></uni-data-select>
                            <uni-easyinput
                                :clearable="false"
                                class="mt20"
                                type="text"
                                v-model="point.alias"
                                @change="aliasChange"
                                placeholder="别名（非必填）"
                            />
                        </uni-forms>
                        <view class="btn-wrap">
                            <view class="btn-wrap-item" @click="closeDrawer"> 取消</view>
                            <view class="btn-wrap-item ml20" @click="addPoint"> 确定</view>
                        </view>
                    </view>
                </scroll-view>
            </uni-drawer>
        </template>
    </view>
</template>
<script>
import {registerDevice, getModel, addDevice, queryByTopoId, updateDevice} from '@/common/api/device.js'
import {getProjectList, queryTopologyDiagramPage} from '@/common/api/project.js'

export default {
    data() {
        return {
            loading: false,
            type: 2,
            formData: {
                nDid: '',
                projectId: '',
                topologyDiagramUrl: '',
                topologyDiagram: '',
            },
            projectRange: [],
            point: {},
            pointList: [],
            activeGplot: 0,
            positionList: [],
            imageList: [],
            isAdaptive: false, // 是否适应当前项目
            deviceInfo: {},
        }
    },
    onLoad(options) {
        this.deviceInfo = JSON.parse(decodeURIComponent(options.deviceInfo))
        console.log(this.deviceInfo)
        this.formData.projectId = this.deviceInfo.projectId
        this.formData.topologyDiagramUrl = this.deviceInfo.filePath
        this.pointList = this.deviceInfo.appsLineTopologyDiagramPO.map((item) => {
            return {
                ...item,
                name: item.label,
            }
        })
        console.log(this.pointList, 'this.poinitList')
        this.queryTopologyDiagramPage()
    },
    created() {
        let engineering = uni.getStorageSync(this.$cacheKey.engineering)
        getProjectList({
            pageNum: 1,
            pageSize: 9999,
            engineeringId: engineering.id,
        }).then((res) => {
            console.log(res)
            let arr = [
                ...res.data.records.map((item) => {
                    return {
                        ...item,
                        text: item.name,
                        value: item.id,
                    }
                }),
            ]
            this.projectRange = arr
        })
        let dictData = uni.getStorageSync(this.$cacheKey.dictData)
        dictData.forEach((item) => {
            if (item.code == 'Line_Position') {
                this.positionList = item.children.map((item) => {
                    return {
                        ...item,
                        text: item.name,
                        value: item.id,
                    }
                })
            }
        })
    },
    methods: {
        resize() {
            console.log(this.$refs['gplot-image'])
        },
        confirmGplot() {
            this.formData.topologyDiagramUrl = this.imageList[this.activeGplot].filePath
            this.formData.topologyDiagram = this.imageList[this.activeGplot].id
            this.pointList.forEach((item) => {
                this.imageList[this.activeGplot].csLineTopologyTemplateVOList.forEach((item3) => {
                    console.log(item3.linePostion)
                    if (item3.linePostion === item.linePostion) {
                        item.lat = item3.lat
                        item.lng = item3.lng
                    }
                })
            })
            console.log(this.pointList)
            this.$forceUpdate()
            this.closeDrawer()
            this.$nextTick(() => {
                this.resize()
            })
        },
        queryTopologyDiagramPage() {
            setTimeout(() => {
                if (!this.formData.projectId) {
                    return
                }
                queryTopologyDiagramPage({
                    projectId: this.formData.projectId,
                }).then((res) => {
                    this.imageList = res.data.records.map(item=>{
                        return {
                            ...item,
                            filePath: this.$config.static + item.filePath
                        }
                    })
                    this.activeGplot = this.imageList.findIndex(item => {
                        return item.id === this.deviceInfo.id
                    })
                })
            }, 100)
        },
        aliasChange(e) {
            this.$forceUpdate()
        },
        positionChange(e) {
            this.point.name = this.positionList.find((item) => item.id == e).name
        },
        projectChange(e) {
        },
        scanCode() {
            uni.scanCode({
                success: function (res) {
                    console.log('条码类型：' + res.scanType)
                    console.log('条码内容：' + res.result)
                },
            })
        },
        register() {
            if (!this.formData.nDid) {
                return this.$util.toast('请输入设备识别码')
            }
            registerDevice(this.formData.nDid).then((res) => {
                getModel(this.formData.nDid).then((res) => {
                    console.log(res)
                    this.pointList = res.data.map((item) => {
                        return {
                            lat: 0,
                            lng: 0,
                            ...item,
                        }
                    })
                    this.type = 2
                })
            })
        },
        chooseLocation() {
            uni.chooseLocation({
                success: function (res) {
                    this.address = res.name
                    console.log('位置名称：' + res.name)
                    console.log('详细地址：' + res.address)
                    console.log('纬度：' + res.latitude)
                    console.log('经度：' + res.longitude)
                },
            })
        },
        chooseGplot() {
            this.$refs.gplot.open()
        },
        closeDrawer() {
            this.$refs.gplot.close()
            this.$refs.point.close()
        },
        add() {
            this.$refs.point.open()
        },
        addPoint() {
            if (!this.point.linePostion) {
                this.$util.toast('请选择监测点')
                return
            }
            if (this.point.alias) {
                this.point.name = this.point.alias
            } else {
                this.positionList.forEach((item) => {
                    if (item.id === this.point.linePostion) {
                        this.point.name = item.name
                    }
                })
            }
            if (this.point.coordinate) {
                this.point.lat = this.point.coordinate.x
                this.point.lng = this.point.coordinate.y
            }
            this.pointList[this.editIndex] = this.point
            console.log(this.pointList)
            this.closeDrawer()
        },
        deletePoint(index) {
            this.pointList.splice(index, 1)
        },
        editPoint(item, index) {
            console.log(item)
            this.point = item
            console.log(this.point)
            this.editIndex = index
            if (!this.point.alias) {
                let every = this.positionList.every((item) => item.name != this.point.name)
                console.log(every)
                if (every) {
                    this.point.alias = this.point.name
                } else {
                    this.point.alias = ''
                }
            }
            this.$refs.point.open()
            this.$forceUpdate()
        },
        dragPoint(e) {
            console.log(e)
            this.point.coordinate = {
                x: e.detail.x,
                y: e.detail.y,
            }
            // this.point.lat = e.detail.x
            // this.point.lng = e.detail.y
        },
        submit() {
            // 检查pointLlist监测点是否重复，并给出提示
            let arr = []
            this.pointList.forEach((item) => {
                arr.push(item.linePostion)
            })
            let set = new Set(arr)
            if (set.size !== arr.length) {
                this.$util.toast('监测点不能重复')
                return
            }
            updateDevice({
                pointList: this.pointList,
                id: this.imageList[this.activeGplot].id
            }).then((res) => {
                console.log(res)
                this.$util.toast('提交成功')
                let prePage = this.$util.prePage()
                console.log(prePage.$vm)
                prePage.$vm.init()
                setTimeout(() => {
                    uni.navigateBack({delta: 1})
                }, 1500)
            })
        },
    },
}
</script>
<style lang="scss">
.new {
    padding: 34rpx;

    .new-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 80rpx auto 0;
        width: 320rpx;
        background: $uni-theme-color;
        color: #fff;
        height: 80rpx;
        border-radius: 12rpx;
    }

    .content {
        .content-des {
            font-size: 28rpx;
            color: #666;
            margin-bottom: 20rpx;
        }

        margin-bottom: 20rpx;
        padding: 34rpx;
        background: $uni-theme-white;
        border-radius: 12rpx;
    }

    .gplot {
        position: relative;
        width: 100%;
        height: 188rpx;
    }

    .gplot-empty {
        margin: 0 auto;
        border: 1px dashed #dcdfe6;
        color: #999;
        height: 188rpx;
    }

    .gplot-box {
        height: 280rpx;
        margin: 0 auto;
    }

    .gplot-active::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        border: 8rpx solid $uni-theme-color;
        // background: rgba(3, 3, 3, .5);
    }

    .btn-wrap {
        margin-top: 40rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .btn-wrap-item {
            display: flex;
            align-items: center;
            justify-content: center;
            flex: 1;
            background: $uni-theme-color;
            color: #fff;
            height: 80rpx;
            border-radius: 12rpx;
        }
    }
}

.map-pin-box {
    position: relative;
    width: 375px;
    margin: 0 auto;

    .map-pin-box-area {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
    }

    .point {
        white-space: nowrap;
        font-size: 24rpx;
    }
}

/deep/ .uni-drawer__content {
    width: 100vw !important;
}

.point-item {
    height: 72rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-top: 2rpx solid #e5e5e5;
    border-color: rgb(229, 229, 229);
}

.point-item:first-of-type {
    border-top: none;
}

.gplot-image {
    position: absolute;
    left: -9999px;
    width: 375px;
}
</style>
