<template>
    <section>
        <!-- 机构信息 -->
        <el-col :span="24" class="agencyHead">
            <el-container>
                <el-container>
                    <el-aside width="335px;">
                        <div class="agencyHead_img">
                            <el-image class="agencyHead_imgbox" src="../../assets/image/userHead.png">
                                <img src="../../assets/image/userHead.png">
                            </el-image>
                        </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>{{detail.headIntroduction}}</el-footer>
                    </el-container>
                </el-container>
            </el-container>
        </el-col>
        
        <el-col :span="24" :style="allDetail">
            <!-- 轮播图 -->
            <el-col :span="24" class="agencyBody_title">轮播图</el-col>
            <el-col :span="24" class="agencyBody_main">
                <!-- <el-upload ref="upload" action="customize" :http-request="uploadFile" list-type="picture-card" :auto-upload="true"> -->
                <el-upload action="/api/projectfile/uploadFile/" accept="image/*" multiple :limit="5" :data="uploadMsg" list-type="picture-card" 
                    :on-preview="handlePictureCardPreview" 
                    :on-remove="handleRemove">
                    <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="handleDownload(file)">
                                <i class="el-icon-download"></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}}</span>
                </el-col>
                <el-col :span="24" class="agencyBody_detail">
                    机构位置：
                    <span class="info">{{detail.address==null?'暂无':detail.address}}</span>
                </el-col>
                <el-col :span="24" class="agencyBody_detail">
                    联系电话：
                    <span class="info">{{detail.projectNo==null?'暂无':detail.address}}</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="120px" :rules="formRules" ref="editForm">
                <el-col :span="24">
                    <el-form-item label="机构名称" prop="projectName">
                        <el-input v-model="editForm.projectName" autocomplete="off" placeholder="请输入项目名称" style="width:510px"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="机构简介">
                        <el-input type="textarea" :rows="5" placeholder="请输入机构简介" v-model="editForm.modelIds"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="机构图片">
                        <el-upload class="avatar-uploader" accept="image/*" :limit="1" action="action" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <i slot="default" class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                    </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>
    </section>
</template>

<script>
    import util from "../../common/js/util";

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


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

                uploadMsg: {
                    "projectId": this.$route.params.id,
                    "token": JSON.parse(sessionStorage.getItem('user')).headImgurl
                },
                
                //临时数据
                proDetail: {},
                files: [],
                opers: [],

                allDetail: {
                    overflow: 'auto',
                    padding: '0px 5px',
                    height: 0
                },

                listLoading: false,
                modelsLoading: false,
                upLoading: false,
                oplistLoading: false,
                activePage: 0,

                update: 0,
                download: 0,
                view: 0,
                approve: 0,

                company: [],

                staffComp: [],
                allUser: [],
                assets: [],
                produce: [],
                charger: [],
                general: [],

                formRules: {
					projectName: [
						{ required: true, message: '请输入项目名称', trigger: 'blur' }
                    ],
                    customerCompany: [
                        { required: true, message: '请选择客户公司', trigger: 'blur' }
                    ],
                    modelIds: [
                        { required: true, message: '请选择项目模具', trigger: ['blur','change'] }
                    ],
                    managerId: [
                        { required: true, message: '请选择项目经理', trigger: ['blur','change'] }
                    ],
                    ownerApproverId: [
                        { required: true, message: '请选择资产方审批人', trigger: ['blur','change'] }
                    ],
                    customerApproverId: [
                        { required: true, message: '请选择生产方审批人', trigger: ['blur','change'] }
                    ],
                    // 新建人员
                    username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    teamName: [
						{ required: true, message: '请选择人员类型', trigger: ["blur",'change'] }
					],
                    companyId: [
						{ required: true, message: '请选择所属公司', trigger: ["blur",'change'] }
					],
                },
                
                editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				//编辑界面数据
				editForm: {
					projectName: '',
                    customerCompany: [],
                    managerId: '',
                    ownerApproverId: '',
                    customerApproverId: '',
                    modelIds: [],
                    users: []
                },
                editType: 0,
            };
        },
        methods: {
            //返回
            backToList() {
                this.$router.go(-1);
            },

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

            getFileList() {
                this.listLoading = true;
                // 获取文档列表
                this.http.post(this.port.project.fileList, {
                    projectId: this.detailId
                }, res => {
                    this.listLoading = false;
                    if (res.code == "ok") {
                        this.files = res.data;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },

            getOperList() {
                this.oplistLoading = true;
                // 获取文档列表
                this.http.post(this.port.project.operList, {
                    projectId: this.detailId
                }, res => {
                    this.oplistLoading = false;
                    if (res.code == "ok") {
                        this.opers = res.data;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.oplistLoading = false;
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },

            //获取信息
            getMsg() {
                // 获取公司
                this.http.post(this.port.base.addCompanyListToProject, {
                    parentId: this.user.parentId,
                    id: this.user.id
                }, res => {
                    if (res.code == "ok") {
                        var list = res.data , array = [];
                        for(var i in list){
                            if(list[i].id != this.proDetail.ownerCompany){
                                array.push(list[i])
                            }
                        }
                        this.company = array;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })

                // 获取模具
                this.http.post(this.port.mold.chooseModelList, {
                    projectId: this.detailId
                }, res => {
                    if (res.code == "ok") {
                        this.molds = res.data;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })

                this.http.post(this.port.base.getProduceCompany, {
                    projectId: this.detailId
                }, res => {
                    if (res.code == "ok") {
                        this.staffComp = res.data;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },

            doSomething(e){
                e.stopPropagation();
            },

            //切换人员
            changeStaff(i) {
                if(i == 0){
                    var list = this.allUser , array = [];
                    for(var i in list){ 
                        if(list[i].id != this.editForm.customerApproverId && list[i].id != this.editForm.managerId.id && list[i].id != this.editForm.ownerApproverId){
                            array.push(list[i])
                        }
                    }
                    
                    this.general = array;
                } else if(i == 1) {
                    var list = this.allUser , str = this.editForm.users.toString() , array = [] , assets = [] , produce = [];
                    for(var i in list) {
                        if(str.indexOf(list[i].id) == -1) {
                            array.push(list[i]);
                        }
                    }

                    for(var i in list) {
                        if(str.indexOf(list[i].id) == -1) {
                            if(list[i].subordinateType == 0){
                                assets.push(list[i])
                            } else {
                                produce.push(list[i])
                            }
                        }
                    }

                    this.charger = array;
                    this.assets = assets;
                    this.produce = produce;
                }
            },

            //选择公司切换人员
            companyChange() {
                var param = {} ,
                    str = this.proDetail.ownerCompany;
                for(var i in this.editForm.modelIds){
                    str += "," + this.editForm.modelIds[i].produceCompanyId;
                }
                param.companyIds = str;
                param.id = this.user.id;
                param.projectId = this.detailId;
                this.http.post(this.port.project.getUserById, param , res => {
                    if (res.code == "ok") {
                        var list = res.data , assets = [] , produce = [];
                        var allUserId = [];
                        for(var i in list) {
                            allUserId.push(list[i].id); 
                            if(list[i].companyId == this.proDetail.ownerCompany){
                                if(list[i].id != this.user.id){
                                    if(list[i].id != this.proDetail.managerId){
                                        assets.push(list[i])
                                    }
                                }
                            } else {
                                produce.push(list[i])
                            }
                        }

                        var manager = allUserId.indexOf(this.editForm.managerId.id),
                            customerApprover = allUserId.indexOf(this.editForm.customerApproverId),
                            array = res.data , newAssets = [] , newProduce = [],newCharger = [];

                        this.allUser = res.data;

                        if(manager == -1) {
                            this.editForm.managerId = "";
                            this.charger = res.data;
                        } else {
                            for(var i in list) {
                                newCharger.push(list[i]);
                            }
                            this.charger = newCharger;
                        }

                        if(customerApprover == -1) {
                            this.editForm.customerApproverId = "";
                        } else {
                            for(var i in list) {
                                if(str.indexOf(list[i].id) == -1) {
                                    if(list[i].subordinateType == 0){
                                        newAssets.push(list[i])
                                    } else {
                                        newProduce.push(list[i])
                                    }
                                }
                            }
                            this.assets = newAssets;
                            this.produce = newAssets;
                        }

                        var oldUsers = [] , backUsers = this.proDetail.participateUsers;
                        for(var i in backUsers) {
                            oldUsers.push(backUsers[i]);
                        }
                        for(var i in oldUsers) {
                            var num = allUserId.indexOf(oldUsers[i].id);
                            if(num == -1) {
                                oldUsers.splice(num - 1, 1);
                            } else {
                                for(var j in list){
                                    if(oldUsers[i].id == list[j].id) {
                                        if(list[j].id == this.editForm.customerApproverId || list[j].id == this.editForm.managerId.id || list[j].id == this.editForm.ownerApproverId){
                                            array.splice(j,1)
                                        }
                                    }
                                }
                            }
                        }
                        var editUser = [];
                        for(var i in oldUsers) {
                            for(var j in this.editForm.users) {
                                if(this.editForm.users[j] == oldUsers[i].id) {
                                    editUser.push(oldUsers[i].id)
                                }
                            }
                        }
                        this.editForm.users = editUser;
                        this.general = array;
                        this.setMember();
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },

            //打开编辑页面
            edit() {
            },

            //提交
            addSubmit() {
                this.$refs.editForm.validate((valid) => {
					if (valid) {
                        var cId = "",
                            cName = "",
                            modelIds = "",
                            userIds = "";
                        for(var i in this.editForm.modelIds){
                            if(cId.indexOf(this.editForm.modelIds[i].produceCompanyId) == -1){
                                cId += this.editForm.modelIds[i].produceCompanyId + ",";
                                cName += this.editForm.modelIds[i].produceCompanyName + ",";
                            }
                            modelIds += this.editForm.modelIds[i].id + ","
                        }
                        cId = cId.substring(0,cId.length-1);
                        cName = cName.substring(0,cName.length-1);
                        modelIds = modelIds.substring(0,modelIds.length-1);

                        for(var i in this.editForm.users) {
                            if(i == this.editForm.users.length -1){
                                userIds += this.editForm.users[i]
                            } else {
                                userIds += this.editForm.users[i] + ","
                            }
                        }

                        this.editLoading = true;
                        this.http.post(this.port.project.addProject, {
                            id: this.editForm.id,
                            projectName: this.editForm.projectName,
                            customerCompanyIds: cId,
                            customerCompanyNames: cName,
                            manager: this.editForm.managerId.username,
                            managerId: this.editForm.managerId.id,
                            ownerApproverId: this.editForm.ownerApproverId,
                            customerApproverId: this.editForm.customerApproverId,
                            modelIds: modelIds,
                            userIds: userIds,
                            flag: 1
                        } , res => {
                            this.editLoading = false;
                            this.editFormVisible = false;
                            if (res.code == "ok") {
                                this.$message({
                                    message: '修改成功',
                                    type: 'success'
                                });
                                this.getDetail();
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: 'error'
                                });
                            }
                        }, error => {
                            this.editLoading = false;
                            this.editFormVisible = false;
                            this.$message({
                                message: error,
                                type: 'error'
                            });
                        })
					}
				});
            },

            //上传
            uploadFile(params) {
                this.upLoading = true;
                var fileObj = params.file;
                var form = new FormData();
                form.append("projectId", this.proDetail.id);
                form.append("file", fileObj);
                this.http.uploadFile(this.port.project.uploadFile, form , res => {
                    this.upLoading = false;
                    this.$refs.upload.clearFiles();
                    if (res.code == "ok") {
                        this.$message({
                            message: '上传成功',
                            type: 'success'
                        });
                        this.getFileList();
                        this.getOperList();
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.upLoading = false;
                    this.$refs.upload.clearFiles();
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },

            //删除上传文件
			fileDel(id) {
                this.$confirm('确认删除该文档吗?', '提示', {
					type: 'warning'
				}).then(() => {
                    this.http.post(this.port.project.delFile, {
                        id: id
                    }, res => {
                        if (res.code == "ok") {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getFileList();
                            this.getOperList();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    }, error => {
                        this.$message({
                            message: error,
                            type: 'error'
                        });
                    })
				});
            },

            // 在线预览
            viewFile(row) {
                this.http.post(this.port.file.view, {
                    fileId: row.id,
                    type: 1
                }, res => {
                    if (res.code == "ok") {
                        this.openWin(res.data);
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },

            openWin(url) {
                var el = document.createElement("a");
                document.body.appendChild(el);
                el.href = encodeURI(url); 
                el.target = '_blank'; 
                el.click();
                document.body.removeChild(el);
            },

            handleRemove(file) {
                console.log(file);
            },

            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },

            handleDownload(file) {
                console.log(file);
            },

            editDetail(type) {
                this.editType = type;
                this.editFormVisible = true;
            }
        },

        created() {
            let height = window.innerHeight;
            this.allDetail.height = height - 140 + "px";
            const that = this;
            window.onresize = function temp() {
                that.allDetail.height = window.innerHeight - 160;    
            };
        },

        mounted() {
            this.getDetail();
            this.getFileList();
            this.getOperList();
        }
    };
</script>

<style scoped lang="scss">
    .container .main .content-container {
        overflow: auto!important;
    }

    a {
        text-decoration:none;
        color: #333;
    }

    .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;
        padding: 0 20px;
    }

    .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;
    }
</style>