<template>
    <Cn-page :loading="loading">
        <view slot="body">
            <view class="new" :class="{ 'project-new': !this.options.project }">
                <view class="content">
                    <uni-forms :label-width="80">
                        <uni-forms-item label="工程名称">
                            <view class="engineering-select" @click="selectEngineering">
                                <uni-easyinput
                                    v-model="formData.engineeringName"
                                    disabled
                                    maxlength="50"
                                    placeholder="请选择工程"
                                    :clearable="false"
                                />
                            </view>
                        </uni-forms-item>
                        <uni-forms-item label="项目名称">
                            <uni-easyinput v-model="formData.name" maxlength="50" placeholder="请输入项目名称" />
                        </uni-forms-item>
                        <uni-forms-item label="区域">
                            <view style="display: flex">
                                <uni-easyinput :clearable="false" type="textarea" maxlength="250" 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 maxlength="999" 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']"
                            :before-remove="beforeRemove" @select="select"></uni-file-picker>
                    </uni-forms>
                </view>
                <view class="btn-wrap">
                    <view class="btn-wrap-item" @click="submit"> 提交</view>
                </view>
                <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, checkCanDelete } 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: '',
                lng: '',
            },
            tempList: [],
            project: null,
            options: {}
        }
    },
    onShow() {
        if (!this.options.project) {
            let engineering = uni.getStorageSync('onceSelectEngineering')
            if (engineering) {
                uni.removeStorageSync('onceSelectEngineering')
                this.formData.engineeringId = engineering.id
                this.formData.engineeringName = engineering.name
            }
        }
    },
    onLoad(options) {
        this.options = 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]
                }
            }
        } else {
            let engineering = uni.getStorageSync('engineering')
            this.formData.engineeringId = engineering.id
            this.formData.engineeringName = engineering.name
        }
      
        getTopoTemplate().then((res) => {
            console.log(res)
            this.tempList = res.data.map((item) => {
                return {
                    ...item,
                    filePath: this.$config.static + item.filePath
                }
            })
            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: {
        selectEngineering() {
            console.log(123)
            if (this.options.project) return this.$util.toast('项目已经创建，不能修改工程')
            uni.navigateTo({
                url: '/pages/home/selectEngineering?from=once',
            })
        },
        beforeRemove(e) {
            console.log(e)
            if (!e.tempFile.id) {
                return true
            }
            return new Promise((resolve, reject) => {
                checkCanDelete(e.tempFile.id).then((res) => {
                    console.log(res)
                    if (res.data) {
                        resolve(true)
                    } else {
                        reject()
                    }
                })
            })
        },
        async deleteImg(index) {
            await this.beforeRemove({
                tempFile: this.formData.tempFiles[index],
            })
            this.formData.tempFiles.splice(index, 1)
        },
        async chooseTempItem(item) {
            console.log(item)
            console.log(this.formData.tempFiles)
            // 编辑的时候，如果已经存在就要验证topoId
            let index = this.formData.tempFiles.findIndex((item2) => item2.id === item.id || item2.topoId === item.id)
            if (index > -1) {
                await this.beforeRemove({
                    tempFile: this.formData.tempFiles[index],
                })
                this.formData.tempFiles.splice(index, 1)
            } else {
                this.formData.tempFiles.push(item)
            }
        },
        closeTemp() {
            this.$refs.showTemp.close()
        },
        openTemp() {
            this.$refs.showTemp.open()
        },
        select(e) {
            console.log(e)
            this.formData.files.push(...e.tempFiles)
            console.log(this.formData.files)
        },
        // chooseLocation() {
        //     uni.chooseLocation({
        //         success: (res) => {
        //             this.formData.area = res.name
        //             this.formData.lat = res.latitudeame
        //             this.formData.lng = res.longitude
        //             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({
                    ...item,
                    name: 'files',
                    uri: item.url,
                })
            }
            console.log(arr)
            this.formData.topoIds = this.formData.tempFiles.map((item) => (item.id))
            let data = JSON.parse(JSON.stringify(this.formData))
            let res = {}
            console.warn(data, arr)
            if (this.project) {
                data.id = this.project.id
                data.newTopoIds = data.files.filter(item => item.id).map((item) => item.id)
                data.newTopoIds.push(...data.tempFiles.filter(item => item.id && item.topoId).map((item) => item.id))
                data.topoIds = data.tempFiles.filter(item => item.id && !item.topoId).map((item) => item.id)
                delete data.tempFiles
                delete data.files
                arr = arr.filter(item => !item.id)
                res = await updateAppProject(data, arr)
            } else {
                delete data.tempFiles
                delete data.files
                res = await addAppProject(data, arr)
            }
            let result = {}
            if (res.code === 'A0000') {
                result = res
            } else {
                console.warn(res)
                if (res.length === 1) {
                    this.$util.toast(res[0].message)
                    return
                }
                result = JSON.parse(res[1].data)
            }
            if (result.code === 'A0000') {
                if (this.project) {
                    this.$util.toast('项目修改成功')
                    this.$util.refreshPrePage(2)
                } else {
                    if (this.options.from === 'newDevice') {
                        uni.navigateBack()
                    } else {
                        this.$util.toast('项目创建成功')
                        this.$util.refreshPrePage()
                    }
                }
            } else {
                this.$util.toast(result.message)
            }
        },
    },
}
</script>
<style lang="scss" scoped>
.project-new /deep/ .is-disabled {
    background: #fff !important;
    color: #111;
}

.engineering-select {
    width: 100%;

    /deep/ .uni-easyinput,
    /deep/ .uni-easyinput__content {
        pointer-events: none;
    }
}

.new {
    padding: 34rpx;

    .project-new {}

    .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-color;
            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-color;
            }
        }
    }
}

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