<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">
                <button class="btn-wrap-item" :loading="isLoading" :disabled="isLoading" @click="register">
                    {{ isLoading ? '注册中...' : '发起注册' }}
                </button>
            </view>
        </template>
        <template v-else>
            <view class="content">
                <uni-forms>
                    <uni-forms-item label="工程">
                        <view style="display: flex; align-items: center">
                            <uni-data-select v-model="formData.engineeringId" :localdata="engineeringList"
                                @change="engineeringChang($event, true)" :clear="false"></uni-data-select>
                            <uni-icons type="plusempty" color="#007aff" size="26" class="ml20"
                                @click="createEngineering"></uni-icons>
                        </view>
                    </uni-forms-item>
                    <uni-forms-item label="项目">
                        <view style="display: flex; align-items: center">
                            <uni-data-select v-model="formData.projectId" :localdata="projectRange"
                                @change="queryTopologyDiagramPage" :clear="false"></uni-data-select>
                            <uni-icons type="plusempty" color="#007aff" size="26" class="ml20"
                                @click="createProject"></uni-icons>
                        </view>
                    </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 && formData.projectId">
                        <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> -->
                <button class="btn-wrap-item" :loading="isLoading1" :disabled="isLoading1" @click="submit">
                    {{ isLoading1 ? '提交中...' : '提交' }}
                </button>
            </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 v-if="imageList.length === 0" style="text-align: center" class="mt50 mb50">暂无拓扑图
                        </view>
                        <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 labelWidth="70px">
                            <uni-forms-item label="位置">
                                <uni-data-select v-model="point.position" :localdata="positionList"
                                    @change="positionChange" disabled :clear="false"></uni-data-select>
                            </uni-forms-item>
                            <uni-forms-item label="别名">
                                <uni-easyinput :clearable="false" maxlength="24" type="text" v-model="point.alias"
                                    @change="aliasChange" placeholder="别名（非必填）" />
                            </uni-forms-item>
                            <uni-forms-item label="绑定指标">
                                <uni-data-select v-model="point.target" :localdata="targetList"></uni-data-select>
                            </uni-forms-item>
                        </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>
        <yk-authpup ref="authpup" type="top" @changeAuth="changeAuth" permissionID="CAMERA"></yk-authpup>
    </view>
</template>
<script>
import {
    registerDevice,
    getModel,
    addDevice,
    queryByTopoId,
    queryEngineeringPage,
    queryEquipmentByndid,
} from '@/common/api/device.js'
import { getProjectList, queryTopologyDiagramPage } from '@/common/api/project.js'
import ykAuthpup from '@/components/yk-authpup/yk-authpup'
import { queryByCode, queryStatistical } from '@/common/api/dictionary'
export default {
    components: {
        ykAuthpup,
    },
    data() {
        return {
            loading: false,
            type: 1,
            formData: {
                engineeringId: '',
                nDid: '',
                projectId: '',
                topologyDiagramUrl: '',
                topologyDiagram: '',
            },
            projectRange: [],
            point: {},
            isLoading: false,
            isLoading1: false,
            pointList: [],
            activeGplot: 0,
            positionList: [],
            imageList: [],
            targetLists: [],//总数据
            targetList: [],//根据位置切换数据
            isAdaptive: false, // 是否适应当前项目
            dialogOpen: false,
            options: {},
            engineeringList: [],
        }
    },
    onBackPress() {
        if (this.dialogOpen) {
            this.closeDrawer()
            return true
        } else if (this.type === 3) {
            return false
        } else if (this.type === 2) {
            this.type = 1
            return true
        } else {
            return false
        }
    },
    onLoad(o) {
        this.options = o
        let dictData = uni.getStorageSync(this.$cacheKey.dictData)
        queryByCode('app_harmonic_code').then((res) => {
            queryStatistical({ id: res.data.id }).then((resp) => {
                this.targetLists = resp.data.selectedList.map((item) => {
                    return {
                        ...item,
                        text: item.dataTypeName,
                        value: item.dataType,
                    }
                })
            })
        })
        dictData.forEach((item) => {
            if (item.code == 'Line_Position') {
                this.positionList = item.children.filter((child) => child.name !== 'PCC公共点').map((item) => {
                    return {
                        ...item,
                        text: item.name,
                        value: item.id,
                    }
                })
            }
        })
    },
    onShow() {
        this.getEngineering()
        if (this.formData.engineeringId) {
            this.engineeringChang(this.formData.engineeringId, false)
            // this.queryTopologyDiagramPage()
        }
        // 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
        //     })
    },
    methods: {
        // 设置绑定指标
        settarget(e) {
            let pointName = this.positionList.find((item) => item.id == this.point.position).name

            this.targetList = this.targetLists.filter(item => item.dataTypeName.includes(pointName)).map((item) => {
                return {
                    ...item,
                    text: item.dataTypeName.split('-')[1],
                    value: item.dataType,
                }
            })

        },
        getEngineering() {
            queryEngineeringPage({ pageNum: 1, pageSize: 9999 }).then((res) => {
                let arr = [
                    ...res.data.records.map((item) => {
                        return {
                            ...item,
                            text: item.name,
                            value: item.id,
                        }
                    }),
                ]
                this.engineeringList = arr
            })
        },

        engineeringChang(e, key) {
            if (e == '') {
                return (this.projectRange = [])
            }
            if (key) {
                this.formData.projectId = ''
            }
            uni.setStorageSync('engineering', this.engineeringList.filter((item) => item.id == e)[0])

            getProjectList({
                pageNum: 1,
                pageSize: 9999,
                engineeringId: e,
            }).then((res) => {
                let arr = [
                    ...res.data.records.map((item) => {
                        return {
                            ...item,
                            text: item.name,
                            value: item.id,
                        }
                    }),
                ]
                this.projectRange = arr
            })
        },

        createProject() {
            if (this.formData.engineeringId == '') {
                return uni.showToast({
                    title: '请选择工程',
                    icon: 'none',
                })
            }
            uni.navigateTo({
                url: '/pages/project/new?from=newDevice',
            })
        },
        createEngineering() {
            uni.navigateTo({
                url: '/pages/engineering/new',
            })
        },
        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) => {
                console.log(item.position)
                this.imageList[this.activeGplot].csLineTopologyTemplateVOList.forEach((item3) => {
                    // console.log(item3.linePostion)
                    if (item3.linePostion === item.position) {
                        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 = 0
                    if (this.imageList.length) {
                        this.confirmGplot()
                    } else {
                        this.formData.topologyDiagramUrl = ''
                        this.formData.topologyDiagram = ''
                    }
                })
            }, 100)
        },
        aliasChange(e) {
            this.$forceUpdate()
        },

        positionChange(e) {
            console.log(e)
        },

        projectChange(e) { },
        scanCode() {
            if (plus.os.name == 'Android') {
                this.$refs['authpup'].open()
            } else {
                this.changeAuth()
            }
        },
        changeAuth() {
            uni.scanCode({
                onlyFromCamera: false,
                success: (res) => {
                    console.log('条码类型：' + res.scanType)
                    console.log('条码内容：' + res.result)
                    let content = JSON.parse(res.result)
                    console.log(content)
                    if (content.type === 'NDID') {
                        this.formData.nDid = content.data
                        this.register()
                    }
                },
            })
        },
        register() {
            if (!this.formData.nDid) {
                return this.$util.toast('请输入设备识别码')
            }
            this.isLoading = true
            registerDevice(this.formData.nDid, Number(this.options.type))
                .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
                            this.getNdin()
                            this.isLoading = false
                        })
                        .catch(() => {
                            this.isLoading = false
                        })
                })
                .catch(() => {
                    this.isLoading = false
                })
        },
        // 默认回显工程项目
        getNdin() {
            queryEquipmentByndid({ ndid: this.formData.nDid }).then((res) => {
                this.formData.engineeringId = res.data.associatedEngineering || ''
                this.formData.projectId = res.data.associatedProject || ''
                if (this.formData.engineeringId) {
                    this.engineeringChang(this.formData.engineeringId, false)
                    this.queryTopologyDiagramPage()
                    let flag = this.engineeringList.some((item) => item.id === this.formData.engineeringId)
                    if (!flag) {
                        this.engineeringList.unshift({
                            text: res.data.associatedEngineeringName,
                            value: res.data.associatedEngineering,
                        })
                    }
                }
            })
        },

        // 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()
            this.dialogOpen = true
        },
        closeDrawer() {
            this.$refs.gplot.close()
            this.$refs.point.close()
            this.dialogOpen = false
        },
        add() {
            this.$refs.point.open()
        },
        addPoint() {
            if (!this.point.position) {
                this.$util.toast('请选择监测点')
                return
            }
            if (this.point.alias) {
                this.point.name = this.point.alias
            } else {
                this.positionList.forEach((item) => {
                    if (item.id == this.point.position) {
                        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) {
            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.settarget()
            this.dialogOpen = true
            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() {
            if (!this.formData.projectId) {
                return this.$util.toast('请选择项目')
            }
            if (!this.formData.topologyDiagram) {
                return this.$util.toast('请选择拓扑图')
            }
            // 检查pointLlist监测点是否重复，并给出提示
            let arr = []
            this.pointList.forEach((item) => {
                arr.push(item.position)
            })
            let set = new Set(arr)
            if (set.size !== arr.length) {
                this.$util.toast('监测点不能重复')
                return
            }
            this.isLoading1 = true
            addDevice({
                ...this.formData,
                list: this.pointList,
                ndid: this.formData.nDid,
                process: Number(this.options.type),
            })
                .then((res) => {
                    console.log(res)
                    this.$util.toast('提交成功')
                    this.isLoading1 = false
                    setTimeout(() => {
                        this.type = 3
                        uni.navigateBack({ delta: 1 })
                    }, 1500)
                })
                .catch(() => {
                    this.isLoading1 = false
                })
        },
    },
}
</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>
