<template>
    <Cn-page :loading="loading">
        <view slot="body">
            <view class="new">
                <view class="content">
                    <uni-forms :label-width="80">
                        <uni-forms-item label="工程名称">
                            <uni-easyinput
                                v-model="formData.engineeringName"
                                placeholder="请输入项目名称"
                                @click.native="showDrawer"
                                :clearable="false"
                            />
                        </uni-forms-item>
                        <uni-forms-item label="项目名称">
                            <uni-easyinput v-model="formData.name" placeholder="请输入项目名称" />
                        </uni-forms-item>
                        <uni-forms-item label="区域">
                            <view style="display: flex">
                                <uni-easyinput
                                    :clearable="false"
                                    type="textarea"
                                    autoHeight
                                    v-model="formData.area"
                                    placeholder="请输入区域信息"
                                />
                                <uni-icons
                                    type="location"
                                    color="#007aff"
                                    size="26"
                                    class="ml20"
                                    @click="chooseLocation"
                                ></uni-icons>
                            </view>
                        </uni-forms-item>
                        <uni-forms-item label="描述">
                            <uni-easyinput
                                type="textarea"
                                autoHeight
                                v-model="formData.description"
                                placeholder="请输入项目描述"
                            />
                        </uni-forms-item>
                        <view class="temp-choose">
                            <view class="temp-choose-title">从模版库选择拓扑图</view>
                            <view class="temp-choose-content">
                                <view class="temp-choose-content-item" v-for="(item, index) in formData.tempFiles">
                                    <image
                                        class="temp-choose-content-item-img"
                                        :src="item.filePath"
                                        mode="aspectFill"
                                    />
                                    <view class="temp-choose-content-item-close" @click="deleteImg(index)">
                                        <uni-icons style="font-size: 18px" type="closeempty" color="#fff" size="20" />
                                    </view>
                                </view>
                                <view class="temp-choose-content-item" @click="openTemp">
                                    <uni-icons type="plusempty" size="70" color="#f1f1f1"></uni-icons>
                                </view>
                            </view>
                        </view>
                        <uni-file-picker
                            v-model="formData.files"
                            title="从本地上传拓扑图"
                            :sourceType="['album']"
                            @select="select"
                        ></uni-file-picker>
                    </uni-forms>
                </view>
                <view class="btn-wrap">
                    <view class="btn-wrap-item" @click="submit"> 提交 </view>
                </view>
                <uni-drawer ref="showRight" mode="right" :mask-click="false">
                    <uni-indexed-list
                        :options="engineeringListFilter"
                        :showSelect="false"
                        @click="closeDrawer"
                    ></uni-indexed-list>
                </uni-drawer>
                <uni-popup ref="showTemp" type="bottom" :mask-click="false">
                    <view class="popup-header">
                        <view class="popup-header-title">模版库</view>
                        <view class="popup-header-close" @click="closeTemp">
                            <uni-icons type="closeempty" color="#111" size="20" />
                        </view>
                    </view>
                    <view class="temp-list">
                        <view
                            class="temp-list-item"
                            :class="{
                                'temp-list-item-active': formData.tempFiles.some(
                                    (item2) => item2.id === item.id || item2.topoId === item.id,
                                ),
                            }"
                            v-for="(item, index) in tempList"
                            @click="chooseTempItem(item)"
                        >
                            <image class="temp-list-item-img" :src="item.filePath" mode="aspectFill" />
                            <view class="temp-list-item-name">{{ item.name }}</view>
                        </view>
                    </view>
                </uni-popup>
            </view>
        </view>
    </Cn-page>
</template>
<script>
import { pinyin } from 'pinyin-pro'
import { addAppProject, updateAppProject } from '../../common/api/project'
import { getTopoTemplate } from '../../common/api/device'
import { queryEngineering } from '@/common/api/engineering.js'
export default {
    data() {
        return {
            loading: false,
            formData: {
                engineeringId: '',
                engineeringName: '',
                area: '',
                files: [],
                tempFiles: [],
                topoIds: [],
                description: '',
                name: '',
                lat: '2',
                lng: '3',
            },
            engineeringList: [],
            tempList: [],
            project: null,
        }
    },
    computed: {
        engineeringListFilter() {
            let result = []
            this.engineeringList.forEach((item) => {
                let arr = pinyin(item.name[0], { toneType: 'none', type: 'array' })
                let letter = arr[0][0].toUpperCase()
                console.log(letter)
                let index = result.findIndex((item) => item.letter === letter)
                if (index === -1) {
                    result.push({
                        letter,
                        data: [item.name],
                    })
                } else {
                    result[index].data.push(item.name)
                }
            })
            return result
        },
    },
    onLoad(options) {
        if (options.project) {
            uni.setNavigationBarTitle({
                title: '编辑项目',
            })
            this.project = JSON.parse(decodeURIComponent(options.project))
            console.log(this.project)
            for (let key in this.formData) {
                if (this.project[key]) {
                    this.formData[key] = this.project[key]
                }
            }
        }
        uni.getLocation({
            type: 'wgs84',
            success: function (res) {
                console.log(res)
                console.log('当前位置的经度：' + res.longitude)
                console.log('当前位置的纬度：' + res.latitude)
            },
        })
        queryEngineering().then((res) => {
            this.engineeringList = res.data
        })
        getTopoTemplate().then((res) => {
            console.log(res)
            this.tempList = res.data
            if (this.project) {
                this.project.topologyDiagramPaths.forEach((item) => {
                    if (this.tempList.some((item2) => item2.id === item.topoId)) {
                        this.formData.tempFiles.push(item)
                    } else {
                        this.formData.files.push({
                            url: item.filePath,
                            extname: item.name.split('.')[1],
                            name: item.name,
                            ...item,
                        })
                    }
                })
            }
        })
    },
    methods: {
        deleteImg(index) {
            this.formData.tempFiles.splice(index, 1)
        },
        chooseTempItem(item) {
            if (this.formData.tempFiles.some((item2) => item2.id === item.id || item2.topoId === item.id)) {
                this.formData.tempFiles = this.formData.tempFiles.filter(
                    (item2) => item2.id !== item.id && item2.topoId !== item.id,
                )
            } else {
                this.formData.tempFiles.push(item)
            }
        },
        closeTemp() {
            this.$refs.showTemp.close()
        },
        openTemp() {
            this.$refs.showTemp.open()
        },
        showDrawer() {
            this.$refs.showRight.open()
        },
        closeDrawer(e) {
            console.log(e)
            this.formData.engineeringName = e.item.name
            this.formData.engineeringId = this.engineeringList.find((item) => item.name === e.item.name).id
            this.$refs.showRight.close()
        },
        select(e) {
            console.log(e)
            console.log(this.formData.files)
            this.formData.files = this.formData.files.concat(e.tempFiles)
        },
        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)
                },
            })
        },
        async submit() {
            console.log(this.formData)
            if (!this.formData.name) {
                this.$util.toast('请输入项目名称')
                return
            }
            if (!this.formData.area) {
                this.$util.toast('请输入区域信息')
                return
            }
            if (!this.formData.description) {
                this.$util.toast('请输入项目描述')
                return
            }
            if (!this.formData.files.length && !this.formData.tempFiles.length) {
                this.$util.toast('请至少选择一张拓扑图')
                return
            }
            let arr = []
            for (let i = 0; i < this.formData.files.length; i++) {
                let item = this.formData.files[i]
                console.log(item)
                arr.push({
                    name: 'files',
                    uri: item.url,
                })
            }
            this.formData.topoIds = this.formData.tempFiles.map((item) => (item.topoId ? item.topoId : item.id))
            let data = JSON.parse(JSON.stringify(this.formData))
            delete data.files
            let res = {}
            if (this.project) {
                data.id = this.project.id
                res = await updateAppProject(data, arr)
            } else {
                res = await addAppProject(data, arr)
            }
            console.log(res)
            if (res.length === 1) {
                this.$util.toast(res[0].message)
                return
            }
            let result = JSON.parse(res[1].data)
            if (result.code === 'A0000') {
                if (this.project) {
                    this.$util.toast('项目修改成功')
                    this.$util.refreshPrePage(2)
                } else {
                    this.$util.toast('项目创建成功')
                    this.$util.refreshPrePage()
                }
            } else {
                this.$util.toast(result.message)
            }
        },
    },
}
</script>
<style lang="scss">
.new {
    padding: 34rpx;

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

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

    .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-blue;
            color: #fff;
            height: 80rpx;
            border-radius: 12rpx;
        }
    }
    .temp-choose {
        margin-bottom: 44rpx;
        .temp-choose-title {
            font-size: 14px;
            color: #333;
        }
        .temp-choose-content {
            margin-top: 20rpx;
            display: grid;
            grid-template-columns: repeat(3, 198rpx);
            grid-gap: 10rpx;
            .temp-choose-content-item {
                box-sizing: border-box;
                border: 1px #eee solid;
                position: relative;
                display: flex;
                align-items: center;
                justify-content: center;
                height: 198rpx;
                .temp-choose-content-item-img {
                    height: 100%;
                    width: 100%;
                    background: skyblue;
                    display: block;
                }
                .temp-choose-content-item-close {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    position: absolute;
                    top: 3px;
                    right: 3px;
                    border-radius: 50%;
                    background-color: rgba(0, 0, 0, 0.5);
                    z-index: 2;
                    height: 52rpx;
                    width: 52rpx;
                    font-size: 24rpx;
                    color: #666;
                }
            }
        }
    }

    .temp-list {
        box-sizing: border-box;
        width: 750rpx;
        height: 80vh;
        padding: 20rpx;
        overflow-y: scroll;
        background: #fff;

        .temp-list-item {
            margin-bottom: 10rpx;
            position: relative;
            box-sizing: border-box;
            border: 4px solid #f1f1f1;
            .temp-list-item-img {
                height: 280rpx;
                width: 100%;
            }
            .temp-list-item-name {
                position: absolute;
                right: 0;
                top: 0;
                background: #fff;
                padding: 4rpx 8rpx;
            }
            &-active {
                border: 4rpx solid $uni-theme-blue;
            }
        }
    }
}

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