<template>
    <section>
        <!-- 机构信息 -->
        <el-col :span="24" class="agencyHead">
            <el-container>
                <el-container>
                    <el-aside width="335px;">
                        <div class="agencyHead_img">
                            <img class="agencyHead_imgbox" :src="detail.briefIntroductionPic">
                        </div>
                    </el-aside>
                    <el-container>
                        <el-header height="90px;">
                            {{detail.name}}
                            <el-button type="text" @click="editDetail(0)" icon="el-icon-edit" class="agencyHead_edit"></el-button>
                            <el-button type="text" @click="backToList" class="agencyHead_back"><i class="iconfont iconfanhui1"></i></el-button>
                        </el-header>
                        <el-footer>
                            <span class="info">{{detail.headIntroduction==null?"暂无简介":detail.headIntroduction}}</span>
                        </el-footer>
                    </el-container>
                </el-container>
            </el-container>
        </el-col>
        
        <el-col :span="24" class="agencyDeail">
            <!-- 轮播图 -->
            <el-col :span="24" class="agencyBody_title">轮播图</el-col>
            <el-col :span="24" class="agencyBody_main">
                <el-upload action="/api/institutional/updatePics/" accept="image/*" multiple :limit="5" :data="uploadMsg" list-type="picture-card" 
                    :file-list="detail.pics"
                    :on-preview="handlePictureCardPreview" 
                    :on-remove="handleRemove"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError">
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{file}">
                        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                <i class="el-icon-zoom-in"></i>
                            </span>
                            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                                <i class="el-icon-delete"></i>
                            </span>
                        </span>
                    </div>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </el-col>

            <!-- 基本信息 -->
            <el-col :span="24" class="agencyBody_title">
                基本信息
                <el-button type="text" @click="editDetail(1)" icon="el-icon-edit" class="agencyHead_edit"></el-button>
            </el-col>
            <el-col :span="24" class="agencyBody_main">
                <el-col :span="24" class="agencyBody_detail">
                    上课时间：
                    <span class="info" v-if="detail.amTime != null || detail.pmTime != null">{{detail.amTime}} - {{detail.pmTime}}</span>
                    <span class="info" v-else>暂无</span>
                </el-col>
                <el-col :span="24" class="agencyBody_detail">
                    收费标准：
                    <span class="info">{{detail.chargingStandard==null||detail.chargingStandard==''?'暂无':detail.chargingStandard}}</span>
                </el-col>
                <el-col :span="24" class="agencyBody_detail">
                    机构位置：
                    <span class="info">{{detail.address==null||detail.address==''?'暂无':detail.address}}</span>
                </el-col>
                <el-col :span="24" class="agencyBody_detail">
                    联系方式：
                    <span class="info">{{detail.phone==null||detail.phone==''?'暂无':detail.phone}}</span>
                </el-col>
            </el-col>

            <!-- 机构简介 -->
            <el-col :span="24" class="agencyBody_title">
                机构介绍
                <el-button type="text" @click="editDetail(2)" icon="el-icon-edit" class="agencyHead_edit"></el-button>
            </el-col>
            <el-col :span="24" class="agencyBody_main">
                <el-col :span="24" class="agencyBody_detail">
                    <span class="info">{{detail.briefIntroduction==null?'暂无':detail.briefIntroduction}}</span>
                </el-col>
            </el-col>

            <!-- 课程特色 -->
            <el-col :span="24" class="agencyBody_title">
                课程特色
                <el-button type="text" @click="editDetail(3)" icon="el-icon-edit" class="agencyHead_edit"></el-button>
            </el-col>
            <el-col :span="24" class="agencyBody_main">
                <el-col :span="24" class="agencyBody_detail">
                    <span class="info">{{detail.classAdvantages==null?'暂无':detail.classAdvantages}}</span>
                </el-col>
            </el-col>
        </el-col>

        <!--编辑基础信息-->
		<el-dialog title="编辑机构信息" v-if="editFormVisible" :visible.sync="editFormVisible" :close-on-click-modal="false" customClass='customWidth'>
			<el-form :model="editForm" label-width="100px" :rules="formRules" ref="editForm">
                <el-col :span="24">
                    <el-form-item label="机构名称" prop="name">
                        <el-input v-model="editForm.name" autocomplete="off" placeholder="请输入项目名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="机构简介">
                        <el-input v-model="editForm.headIntroduction" type="textarea" :rows="5" placeholder="请输入机构简介"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="机构图片">
                        <el-upload class="avatar-uploader" ref="upload" accept="image/*" list-type="picture-card"
                          :limit="1" action="action" :auto-upload="false" :http-request="uploadDiscardFile" :file-list='editForm.headPic'>
                            <i slot="default" class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                </el-col>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

        <el-dialog title="编辑机构信息" v-if="editFormVisibleOther" :visible.sync="editFormVisibleOther" :close-on-click-modal="false" customClass='customWidth'>
			<el-form :model="editFormOther" label-width="70px" :rules="formRules" ref="editFormOther">
                <el-form-item label="上课时间" v-if="editType == 1">
                    <el-time-picker is-range v-model="editFormOther.time" format="HH:mm:ss" value-format="HH:mm:ss"
                    range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围" style=width:565px;></el-time-picker>
                </el-form-item>
                <el-form-item label="收费标准" v-if="editType == 1">
                    <el-input v-model="editFormOther.chargingStandard" autocomplete="off" placeholder="请输入收费标准"></el-input>
                </el-form-item>
                <el-form-item label="联系方式" v-if="editType == 1">
                    <el-input v-model="editFormOther.phone" autocomplete="off" placeholder="请输入联系方式"></el-input>
                </el-form-item>
                <el-form-item label="机构位置" v-if="editType == 1">
                    <el-input v-model="editFormOther.address" :change="changeFactoryArea('editContainer')" autocomplete="off" placeholder="请输入机构位置"></el-input>
                </el-form-item>
                <div id="editContainer" v-if="editType == 1" class="formMap"></div>
                <el-form-item label="机构介绍" v-if="editType == 2">
                    <el-input v-model="editFormOther.briefIntroduction" type="textarea" :rows="5" placeholder="请输入机构介绍"></el-input>
                </el-form-item>
                <el-form-item label="课程特色" v-if="editType == 3">
                    <el-input v-model="editFormOther.classAdvantages" type="textarea" :rows="5" placeholder="请输入课程特色"></el-input>
                </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisibleOther = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmitOther" :loading="editOtherLoading">提交</el-button>
			</div>
		</el-dialog>
    </section>
</template>

<script>
    export default {
        data() {
            return {
                //基础信息
                detailId: this.$route.params.id==null?JSON.parse(sessionStorage.getItem('user')).ageId:this.$route.params.id,
                user: JSON.parse(sessionStorage.getItem('user')),
                detail: {},

                dialogImageUrl: '',
                dialogVisible: false,
                disabled: false,

                uploadMsg: {
                    "id": this.$route.params.id
                },

                formRules: {
                    name: [
						{ required: true, message: '请输入机构名称', trigger: 'blur' }
                    ],
                },

                // 地图
                map: '',
                marker: '',
                
                //编辑
                editType: 0,
                editFormVisible: false,
                editLoading: false,
				editForm: {
					name: '',
                    headIntroduction: '',
                    headPic: [{url:""}],
                },

                editFormVisibleOther: false,
                editOtherLoading: false,
                editFormOther: {
					time: ['09:00:00','18:00:00'],
                    chargingStandard: '',
                    phone: '',
                    address: '',
                    yLng: '',
                    xLat: '',
                    briefIntroduction: '',
                    classAdvantages: '',
                },
            };
        },
        methods: {
            //返回
            backToList() {
                this.$router.go(-1);
            },

            //获取详情
            getDetail() {
                this.http.post(this.port.agency.detail, {
                    id: this.detailId
                }, res => {
                    if (res.code == "ok") {
                        this.detail = res.data;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },

            //图片上传
            handleUploadSuccess(response, file, fileList) {
                if(response.code == "ok") {
                    this.$message({
                        message: "上传成功",
                        type: "success"
                    });
                } else {
                    this.$message({
                        message: err,
                        type: "error"
                    });
                }
            },

            handleUploadError(err, file, fileList) {
                this.$message({
                    message: err,
                    type: "error"
                });
            },

            //预览图片
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.picUrl;
                this.dialogVisible = true;
            },

            //删除图片
            handleRemove(file) {
                this.$confirm('确认删除该图片吗?', '提示', {
					type: 'warning'
				}).then(() => {
                    this.http.post(this.port.agency.deletePic, {
                        id: file.id
                    }, res => {
                        if (res.code == "ok") {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getDetail();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    }, error => {
                        this.$message({
                            message: error,
                            type: 'error'
                        });
                    })
				});
            },

            //打开编辑页面
            editDetail(type) {
                this.editType = type;
                this.editLoading = false;
                this.editOtherLoading = false;
                if(type == 0) {
                    this.editFormVisible = true;
                    this.editForm = {
                        "name": this.detail.name,
                        "headIntroduction": this.detail.headIntroduction,
                        "headPic": [{url:this.detail.briefIntroductionPic}]
                    }
                } else {
                    this.editFormVisibleOther = true;
                    const time = this.editFormOther.time;
                    if(this.detail.amTime != null) {
                        time[0] = this.detail.amTime;
                    }
                    if(this.detail.pmTime != null) {
                        time[1] = this.detail.pmTime;
                    }
                    this.editFormOther = {
                        "time": time,
                        "chargingStandard": this.detail.chargingStandard,
                        "phone": this.detail.phone,
                        "address": this.detail.address,
                        "yLng": this.detail.lng,
                        "xLat": this.detail.lat,
                        "briefIntroduction": this.detail.briefIntroduction,
                        "classAdvantages": this.detail.classAdvantages,
                    }
                }
            },

            //提交
            addSubmit() {
                this.$refs.editForm.validate(valid => {
                    if (valid) {
                        if(this.$refs.upload.uploadFiles.length == 1 && this.$refs.upload.uploadFiles[0].url != this.detail.briefIntroductionPic) {
                            this.$refs.upload.submit();
                        } else {
                            this.http.post( this.port.agency.edit, {
                                id: this.detail.id,
                                name: this.editForm.name,
                                headIntroduction: this.editForm.headIntroduction,
                            },
                            res => {
                                if (res.code == "ok") {
                                    this.editFormVisible = false;
                                    this.$message({
                                        message: "修改成功",
                                        type: "success"
                                    });
                                    this.getDetail();
                                } else {
                                    this.$message({
                                        message: res.msg,
                                        type: "error"
                                    });
                                }
                            },
                            error => {
                                this.editFormVisible = false;
                                this.$message({
                                    message: error,
                                    type: "error"
                                });
                            });
                        }
                    }
                })
            },

            addSubmitOther() {
                var form = {};
                if(this.editType == 1) {
                    form = {
                        id: this.detail.id,
                        amTime: this.editFormOther.time[0],
                        pmTime: this.editFormOther.time[1],
                        chargingStandard: this.editFormOther.chargingStandard,
                        phone: this.editFormOther.phone,
                        address: this.editFormOther.address,
                    };
                } else if(this.editType == 2) {
                    form = {
                        id: this.detail.id,
                        briefIntroduction: this.editFormOther.briefIntroduction,
                    };
                } else if(this.editType == 3) {
                    form = {
                        id: this.detail.id,
                        classAdvantages: this.editFormOther.classAdvantages,
                    };
                }
                this.http.post( this.port.agency.edit, form ,
                res => {
                    if (res.code == "ok") {
                        this.editFormVisibleOther = false;
                        this.$message({
                            message: "修改成功",
                            type: "success"
                        });
                        this.getDetail();
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.editFormVisibleOther = false;
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },

            uploadDiscardFile(params){
                var fileObj = params.file;
                var form = new FormData();
                form.append("file", fileObj);
                form.append("id", this.detail.id);
                form.append("name", this.editForm.name);
                form.append("headIntroduction", this.editForm.headIntroduction);
                this.http.uploadFile( this.port.agency.edit, form,
                res => {
                    if (res.code == "ok") {
                        this.$message({
                            message: "修改成功",
                            type: "success"
                        });
                        this.editFormVisible = false;
                        this.$refs.upload.clearFiles();
                        this.getDetail();
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.editFormVisible = false;
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },

            //地址输入切换
            changeFactoryArea(mapId) {
                if(mapId == "addContainer"){
                    this.markLocation(this.addForm.address, mapId);
                } else {
                    this.markLocation(this.editFormOther.address, mapId);
                }
            },
            
            //获取地图
            setMap(mapId) {
                if(mapId == 'addContainer') {
                    this.map = new AMap.Map('addContainer', {
                        resizeEnable: true, // 允许缩放
                        center:[ this.addForm.yLng , this.addForm.xLat ],
                        zoom:10
                    })

                    this.marker = new AMap.Marker({
                        map: this.map,
                        position: new AMap.LngLat(this.addForm.yLng , this.addForm.xLat),   // 经纬度
                    });
                } else {
                    this.map = new AMap.Map('editContainer', {
                        resizeEnable: true, // 允许缩放
                        center:[this.editFormOther.yLng , this.editFormOther.xLat],
                        zoom:10
                    })

                    this.marker = new AMap.Marker({
                        map: this.map,
                        position: new AMap.LngLat(this.editFormOther.yLng , this.editFormOther.xLat),   // 经纬度
                    });
                }
                
                var _this = this;
                this.map.on('click', function(e) {
                    if(_this.map){
                        _this.map.remove(_this.marker);
                    }
                    var Lng = e.lnglat.getLng(),
                    Lat = e.lnglat.getLat();
                    if(mapId == 'addContainer') {
                        _this.addForm.yLng = Lng;
                        _this.addForm.xLat = Lat;
                    } else {
                        _this.editFormOther.yLng = Lng;
                        _this.editFormOther.xLat = Lat;
                    }
                    _this.marker = new AMap.Marker({
                        map: _this.map,
                        position: new AMap.LngLat(Lng , Lat),   // 经纬度
                    });
                });
            },

            // 获取经纬度
            markLocation(address,mapId) {
                var _this = this;
                AMap.plugin('AMap.Geocoder', function() {
                    var geocoder = new AMap.Geocoder();            
                    geocoder.getLocation(address, function(status, result) {
                        if (status === 'complete' && result.info === 'OK') {
                            // 经纬度                      
                            var lng = result.geocodes[0].location.lng;
                            var lat = result.geocodes[0].location.lat;
                            
                            _this.noSub = false;
                            if(mapId == "addContainer") {
                                _this.addForm.yLng = lng;
                                _this.addForm.xLat = lat;
                            } else {
                                _this.editFormOther.yLng = lng;
                                _this.editFormOther.xLat = lat;
                            }
                            
                            // 添加标记
                            if(_this.map){
                                _this.map.remove(_this.marker);
                                _this.map.setZoomAndCenter(10, [lng, lat]);
                                _this.marker = new AMap.Marker({
                                    map: _this.map,
                                    position: new AMap.LngLat(lng, lat),   // 经纬度
                                });
                            }

                        } else {
                            //console.log('定位失败！');
                        }
                    });
                });
            }
        },
        watch: {
            addFormVisible(val) {
                if(val){
                    var _this = this
                    setTimeout(function(){ _this.setMap('addContainer'); }, 300);
                }
            },
            editFormVisibleOther(val) {
                if(val){
                    var _this = this
                    setTimeout(function(){ _this.setMap('editContainer'); }, 300);
                }
            }
        },
        mounted() {
            this.getDetail();
        }
    };
</script>

<style scoped lang="scss">
    a {
        text-decoration:none;
        color: #333;
    }

    .agencyDeail {
        margin-bottom: 45px;
    }

    .el-header {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        line-height: 40px;
    }

    .el-footer {
        font-size: 16px;
        color: #333;
        line-height: 30px;
    }

    .el-container.is-vertical {
        overflow: hidden;
    }

    .agencyHead {
        margin: 20px 0 0 0;
    }

    .agencyHead_img {
        width:335px;
        height:160px;
        overflow:hidden;
        .agencyHead_imgbox {
            width:335px;
            height:160px;
        }
    }

    .agencyHead_edit {
        font-size:16px;
        margin: 0 0 0 15px;
        padding: 0;
    }
    
    .agencyHead_back {
        float: right;
        margin: 0;
        position: relative;
        .iconfont {
            font-size: 25px;
            position: absolute;
            right: -10px;
            top: 0px;
        }
    }

    .allDetail {
        overflow-y: auto;
    }

    .agencyBody_title {
        padding-left: 10px;
        padding-bottom: 0px;
        margin: 20px 0;
        font-size: 16px;
        line-height: 20px;
        border-left: 1px #20a0ff solid;
        position: relative;
    }
    
    .agencyBody_main {
        padding-left: 40px;
    }

    .agencyBody_detail {
        margin-bottom: 20px;
    }

    .toolbar .el-form-item {
        font-size: 14px;
        vertical-align: middle;
    }

    .divLine {
        width: 2px;
        background: #c3c3c3;
        height: 100%;
    }

    .projectTitle {
        font-size: 18px;
        color: #333;
    }

    .upload-demo {
        position: absolute;
        right: 0;
        top: -5px;
    }

    .editDetail {
        margin-left: 10px;
        color:#20a0ff;
        cursor: pointer;
    }

    .info {
        color: grey;
    }

    .model {
        cursor: pointer;
        color:#20a0ff;
    }

    .el-collapse {
        border: none;
    }

    .formMap {
        height: 400px;
    }
</style>