<template>
    <div>
        <div>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="left">
                <el-form-item label="门店名称" prop="shopName">
                    <el-input v-model="form.shopName" placeholder="请输入门店名称" style="width: 500px;"></el-input>
                </el-form-item>
                <el-form-item label="门店logo">
                    <el-image :src="form.logo || require('@/assets/images/upload.png')" fit="contain"
                        style="width: 80px;height: 80px;" @click="showUpload = true; uploadIndex = 1"></el-image>
                </el-form-item>
                <el-form-item label="门店照片">
                    <el-image :src="form.coverImg || require('@/assets/images/upload.png')" fit="contain"
                        style="width: 80px;height: 80px;" @click="showUpload = true; uploadIndex = 2"></el-image>
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="form.phone" placeholder="请输入联系电话" style="width: 500px;"></el-input>
                </el-form-item>
                <!-- <el-form-item label="外卖起送金额">
                    <el-input-number v-model="form.takeaway_money" placeholder="0.00" controls-position="right"
                        :min="0"></el-input-number>
                </el-form-item> -->
                <el-form-item label="店铺经度">
                    <el-row>
                        <el-col :span="4">
                            <el-input v-model="form.lng" placeholder="经度"></el-input>
                        </el-col>
                        <el-col :span="4">
                            <el-input v-model="form.lat" placeholder="纬度" style="margin-left: 10px;"></el-input>
                        </el-col>
                        <el-col :span="4">
                            <el-button type="primary" plain icon="el-icon-place" style="margin-left: 20px;"
                                @click="showLocation = true">选择坐标</el-button>
                        </el-col>
                    </el-row>
                    <div style="color: #999;">注：准确的定位便于用户导航到店铺</div>
                </el-form-item>
                <el-form-item label="门店详细地址">
                    <el-input type="textarea" v-model="form.address" placeholder="请输入门店详细地址"
                        style="width: 500px;"></el-input>
                </el-form-item>
                <el-form-item label="营业时间">
                    <el-time-picker placeholder="起始时间" v-model="startTime" :picker-options="{
                        selectableRange: '00:00:00 - 23:59:59',
                        format: 'HH:mm'
                    }" format="HH:mm" value-format="HH:mm">
                    </el-time-picker>
                    <el-time-picker placeholder="结束时间" v-model="endTime" :picker-options="{
                        selectableRange: `${startTime}:00 - 23:59:59`
                    }" format="HH:mm" value-format="HH:mm">
                    </el-time-picker>
                </el-form-item>
                <!-- <el-form-item label="结算类型">
                    <el-radio-group v-model="form.settleType">
                        <el-radio :label="0">今日</el-radio>
                        <el-radio :label="1">次日</el-radio>
                    </el-radio-group>
                </el-form-item> -->
                <el-form-item label="结算时间" prop="settleTime">
                    <el-time-picker placeholder="请选择结算时间" v-model="form.settleTime" :picker-options="{
                        selectableRange: '00:00:00 - 23:59:59',
                        format: 'HH:mm'
                    }" format="HH:mm" value-format="HH:mm">
                    </el-time-picker>
                </el-form-item>
                <el-form-item label="店铺简介">
                    <el-input type="textarea" v-model="form.detail" placeholder="请输入店铺简介" style="width: 500px;"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">营业中</el-radio>
                        <el-radio :label="2">休息中</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitHandle" :loading="formLoading">
                        <span v-if="!formLoading">保存</span>
                        <span v-else>保存中...</span>
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-dialog title="选择地址" :visible.sync="showLocation">
            <div class="map_box">
                <div class="map">
                    <el-amap :center="amapOptions.center">
                        <el-amap-marker :position="amapOptions.center"></el-amap-marker>
                    </el-amap>
                </div>
                <div class="search_box">
                    <el-amap-search-box :search-option="searchOption"
                        :on-search-result="onSearchResult"></el-amap-search-box>
                </div>

                <div class="search_wrap">
                    <div class="item" v-for="item in locationSearchList" :key="item.id">
                        <div class="left">
                            <div class="name">{{ item.name }}-{{ item.address }}</div>
                            <div class="location">
                                经纬度：{{ item.lng }},{{ item.lat }}
                            </div>
                        </div>
                        <div class="btn">
                            <el-button type="primary" @click="selectLocationHandle(item)">
                                选择
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
        <el-dialog :visible.sync="showUpload" :close-on-click-modal="false" append-to-body width="500px"
            @close="showUpload = false">
            <el-upload :before-remove="handleBeforeRemove" :on-success="handleSuccess" :on-error="handleError"
                :file-list="fileList" :headers="headers" :action="qiNiuUploadApi" class="upload-demo" multiple>
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" style="display: block;" class="el-upload__tip">请勿上传违法文件，且文件不超过15M</div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="doSubmit">确认</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import dayjs from 'dayjs'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import crudQiNiu from '@/api/tools/qiniu'
import { tbShopInfo, tbShopInfoPut } from '@/api/user'
export default {
    computed: {
        ...mapGetters([
            'qiNiuUploadApi'
        ])
    },
    data() {
        return {
            showLocation: false,
            showUpload: false,
            uploadIndex: 1,
            startTime: '',
            endTime: '',
            formLoading: false,
            form: {},
            rules: {
                shopName: [
                    {
                        required: true,
                        message: ' ',
                        trigger: 'blur'
                    }
                ],
                phone: [
                    {
                        required: true,
                        message: ' ',
                        trigger: 'blur'
                    }
                ],
                settleTime: [
                    {
                        required: true,
                        message: ' ',
                        trigger: 'blur'
                    }
                ]
            },
            fileList: [],
            files: [],
            headers: {
                'Authorization': getToken()
            },
            searchOption: {
                city: '西安',
                citylimit: false
            },
            locationSearchList: [],
            amapOptions: {
                center: [108.946465, 34.347984],
                position: []
            }
        }
    },
    mounted() {
        this.tbShopInfo()
    },
    methods: {
        onSearchResult(res) {
            this.locationSearchList = res
            this.amapOptions.center = [res[0].lng, res[0].lat]
        },
        // 确认地址选择
        selectLocationHandle(item) {
            this.form.lng = item.lng
            this.form.lat = item.lat
            this.showLocation = false
        },
        // 获取用户详情
        async tbShopInfo() {
            try {
                const shopId = localStorage.getItem('shopId')
                const res = await tbShopInfo(shopId)
                this.form = res
                if (res.businessTime) {
                    const businessTime = res.businessTime.split('-')
                    this.startTime = businessTime[0]
                    this.endTime = businessTime[1]
                }
            } catch (error) { }
        },
        // 保存
        submitHandle() {
            this.$refs.form.validate(async (valid) => {
                if (valid) {
                    this.formLoading = true
                    try {
                        if (this.startTime && this.endTime) {
                            this.form.businessTime = `${this.startTime}-${this.endTime}`
                        }
                        console.log(this.startTime, this.endTime);
                        const res = await tbShopInfoPut(this.form)
                        this.formLoading = false
                        this.$notify({
                            title: '成功',
                            message: '提交成功',
                            type: 'success'
                        });
                    } catch (error) { }
                }
            })
        },
        handleSuccess(response, file, fileList) {
            // const uid = file.uid
            // const id = response.id
            // this.files.push({ uid, id })
            console.log('上传成功', response)
            this.files = response.data
        },
        handleBeforeRemove(file, fileList) {
            for (let i = 0; i < this.files.length; i++) {
                if (this.files[i].uid === file.uid) {
                    crudQiNiu.del([this.files[i].id]).then(res => { })
                    return true
                }
            }
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url
            this.dialogVisible = true
        },
        // 监听上传失败
        handleError(e, file, fileList) {
            const msg = JSON.parse(e.message)
            this.crud.notify(msg.message, CRUD.NOTIFICATION_TYPE.ERROR)
        },
        // 刷新列表数据
        doSubmit() {
            this.fileList = []
            this.showUpload = false
            switch (this.uploadIndex) {
                case 1:
                    this.form.logo = this.files[0]
                    break;
                case 2:
                    this.form.coverImg = this.files[0]
                    break;
                default:
                    break;
            }
        },
    }
}
</script>

<style scoped lang="scss">
.map_box {
    width: 100%;
    position: relative;

    .map {
        height: 300px;
    }

    .search_box {
        position: absolute;
        top: 10px;
        left: 10px;
    }

    .search_wrap {
        padding: 6px 0;

        .item {
            display: flex;
            padding: 12px 0;

            .left {
                flex: 1;
                display: flex;
                flex-direction: column;
                padding-right: 20px;

                .location {
                    color: #999;
                    padding-top: 4px;
                }
            }
        }
    }
}
</style>