<template>
    <!-- 图纸管理 -->
		<el-row>
            <el-col :span="5">
                <div class="box">
                    <el-scrollbar>
                        <basic-container>
                            <avue-tree :option="treeOption"  :data="treeData" @node-click="nodeClick"/>
                            <!-- <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick"></avue-tree> -->
                        </basic-container>
                    </el-scrollbar>
                </div>
            </el-col>
			<el-col :span="19">
                <basic-container>
                    <avue-crud :option="option" :table-loading="loading" :data="data" ref="crud" v-model="form"
                        :permission="permissionList" @search-change="searchChange" @search-reset="searchReset"
                        @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange"
                        @on-load="onLoad" :page.sync="page">
                        <!-- <template slot-scope="scope" slot="areaSearch">
                            <el-select v-model="area" @change="areaSearch">
                                <el-option label="业务区" value="1"></el-option>
                                <el-option label="塔台" value="2"></el-option>
                            </el-select>
                        </template> -->
                        <!-- <template slot-scope="scope" slot="buildSearch">
                            <el-select v-model="build">
                                <el-option :key="'build' + index" v-for="(item, index) in buildings" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                        </template>
                        <template slot-scope="scope" slot="floorSearch">
                            <el-select :disabled="area == 2" v-model="floor">
                                <el-option :key="'floor' + index" v-for="(item, index) in floors" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                        </template> -->
                        <template slot-scope="scope" slot="equipNameSearch">
                            <el-input v-model="equipName" placeholder="分类名称" clearable />
                        </template>
                        <!-- <template slot-scope="scope" slot="cardNameSearch">
                            <el-input v-model="cardName" placeholder="通过人员" clearable />
                        </template>
                        <template slot-scope="scope" slot="dateRangeSearch">
                            <el-date-picker v-model="dateRange" type="datetimerange" placeholder="选择日期"
                                value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" start-placeholder="开始日期"
                                end-placeholder="结束日期">>
                            </el-date-picker>
                        </template> -->
                        <template slot="type" slot-scope="scope">
                            {{ scope.row.type == 1 ? '业务区' : '塔台' }}
                        </template>
                        <template slot="url" slot-scope="scope">
                            <div style="display:flex;flex-wrap:wrap;">
                                <img v-for="item in scope.row.url.split(',')" :key="item" :src="item" style="width:100px;height:100px;margin:0 3px;"></img>
                            </div>
                        </template>
                        <template slot="menuLeft" slot-scope="scope">
                            <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
                        </template>
                        <template slot-scope="{type,size,row}" slot="menu">
                            <el-button :size="size" type="text" icon="el-icon-view" @click="handleView(row)">预览</el-button>
                            <el-button :size="size" type="text" icon="el-icon-edit" @click="handleEdit(row)">编辑</el-button>
                            <el-button :size="size" type="text" icon="el-icon-delete" @click="handleDelete(row)">删除</el-button>
                        </template>
                    </avue-crud>
                    <el-dialog custom-class="drawClass" :title="dialogTitle" :visible.sync="dialogVisible" width="50%" :modal-append-to-body="false">
                        <el-form ref="form" :model="dataForm" label-width="120px" :rules="dataRules">
                            <el-form-item label="图纸分类:" style="width: 100%;display: inline-block;" prop="draweClassId">
                                <el-select size="small" v-model="dataForm.draweClassId" style="width:50%">
                                    <el-option v-for="item in classifyData" :key="item.id" :value="item.id" :label="item.name"></el-option>
                                </el-select>
                            </el-form-item> 
                            <el-form-item label="区域:" style="width: 100%;display: inline-block;" prop="type">
                                <el-select size="small" v-model="dataForm.type" style="width:50%" @change="changeArea">
                                    <el-option :value="1" label="业务区"></el-option>
                                    <el-option :value="2" label="塔台"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="楼号:" style="width: 100%;display: inline-block;" prop="build">
                                <el-tooltip class="item" v-if="!dataForm.type" effect="dark" content="请先选择区域" placement="top">
                                    <el-select disabled size="small" v-model="dataForm.build" style="width:50%" @change="changeBuild">
                                        <el-option v-for="item in buildData" :key="item.dictKey" :value="item.dictKey" :label="item.dictValue"></el-option>
                                    </el-select>
                                </el-tooltip>
                                <el-select v-else size="small" v-model="dataForm.build" style="width:50%" @change="changeBuild">
                                    <el-option v-for="item in buildData" :key="item.dictKey" :value="item.dictKey" :label="item.dictValue"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="楼层:" style="width: 100%;display: inline-block;" prop="floor">
                                <el-tooltip class="item" v-if="!dataForm.build" effect="dark" content="请先选择楼号" placement="top">
                                    <el-select disabled size="small" v-model="dataForm.floor" style="width:50%">
                                        <el-option v-for="item in floorData" :key="item.dictKey" :value="item.dictKey" :label="item.dictValue"></el-option>
                                    </el-select>
                                </el-tooltip>
                                <el-select v-else size="small" v-model="dataForm.floor" style="width:50%">
                                    <el-option v-for="item in floorData" :key="item.dictKey" :value="item.dictKey" :label="item.dictValue"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="图纸:" style="width:100%;display: inline-block;" prop="url">
                                <el-upload
                                    :class="imgList.length >= 5  ? 'hide' : ''"
                                    action="/api/blade-desk/oss/put-file"
                                    list-type="picture-card"
                                    :on-success="handleSuccess"
									:before-remove="beforeRemove"
									:on-remove="handleRemove"
                                    :file-list="fileList"
                                    :limit="5"
                                    accept=".png,.PNg,.jpg,.JPG,.jpeg,.JPEG,.bmp,.BMP" 
                                >
                                    <i class="el-icon-plus"></i>
                                </el-upload>
                            </el-form-item>
                            <el-form-item label="描述" style="width:100%;display:inline-block;" prop="remark">
                                <el-input v-model="dataForm.remark" size="small" style="width:50%"></el-input>
                            </el-form-item>
                        </el-form>
                        <span slot="footer" class="dialog-footer">
                            <el-button @click="warnClose">取 消</el-button>
                            <el-button type="primary" @click="sureAdd">确 定</el-button>
                        </span>
                    </el-dialog>
	            </basic-container>
                <el-image style="width: 0; height: 0;opacity: 0;" ref="preview" :src="url" :preview-src-list="srcList"></el-image>
			</el-col>
		</el-row>

</template>

<script>
import {getDrawList,getDict,deleteDraw,addDraw,editDraw,getTerrData} from '@/api/equipment/drawManage'
import {getList} from '@/api/equipment/drawClassify'
    export default{
        data(){
            return {
                area: "1",
                equipName:'',
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0,
                },
                dialogTitle:'',
                dialogVisible:false,
                url:'',
                srcList:[],
                classifyData:[], //图纸分类数组
                buildData:[],
                floorData:[],
                option: {
                    lazy: true,
                    tip: false,
                    searchLabelWidth: 80,
                    searchShow: true,
                    searchMenuSpan: 6,
                    tree: true,
                    border: true,
                    index: true,
                    dialogClickModal: false,
                    viewBtn: false,
                    menu: true,
                    addBtn:false,
                    editBtn:false,
                    delBtn:false,
                    column: [
                        // {
                        // 	label: "业务区",
                        // 	prop: "areaNumber",
                        // 	align: "center",
                        // },
                        // {
                        // 	label: "楼宇",
                        // 	prop: "buildNumber",
                        // 	align: "center",
                        // },
                        // {
                        // 	label: "楼层",
                        // 	prop: "floorNumber",
                        // 	align: "center",
                        // },
                        {
                            label: "图纸分类",
                            prop: "draweClassName",
                            align: "center",
                            addDisplay:false,
                            editDisplay:false,
                            width:120,
                        },
                        {
                            label: "区域",
                            prop: "type",
                            align: "center",
                            addDisplay:false,
                            editDisplay:false,
                            width:120,
                        },
                        {
                            label: "图纸分类",
                            prop: "draweClassId",
                            type:'select',
                            align: "center",
                            hide:true,
                            width:120,
                            // span:24
                        },
                        {
                        	label: "楼号",
                        	prop: "buildNo",
                            type:'select',
                        	align: "center",
                            width:120,
                        },
                        {
                        	label: "楼层",
                        	prop: "floorNo",
                            type:'select',
                        	align: "center",
                            width:120,
                        },
                        {
                        	label: "图纸",
                        	prop: "url",
                        	align: "center",
                            addDisplay:false,
                            editDisplay:false,
                            slot:true
                        },
                        {
                        	label: "描述",
                        	prop: "remark",
                        	align: "center",
                            overHidden:true,
                            width:120,
                        },
                        {
                            label: '图纸',
                            prop: 'string',
                            dataType: 'string',
                            type: 'upload',
                            hide:true,
                            propsHttp: {
                                home:'https://avuejs.com',
                                res: 'data'
                            },
                            span: 24,
                            listType: 'picture-card',
                            // tip: '只能上传jpg/png文件，且不超过500kb',
                            action: '/imgupload'
                        },
                        // {
                        //     label: "创建时间",
                        //     prop: "accessTime",
                        //     // type: "datetimerange",
                        //     align: "center",
                        //     addDisplay:false,
                        //     editDisplay:false
                        // },
                        // {
                        // 	label: "区域",
                        // 	prop: "area",
                        // 	searchslot: true,
                        // 	search: true,
                        // 	type: "select",
                        // 	hide: true,
                        // 	row: false,
                        // 	display: false,
                        // 	viewDisplay: false
                        // },
                        // {
                        //     label: "分类名称",
                        //     prop: "equipName",
                        //     searchslot: true,
                        //     search: true,
                        //     type: "input",
                        //     hide: true,
                        //     row: false,
                        //     display: false,
                        //     viewDisplay: false,
                        // },
                    ],
                },
                dataForm:{},
                data:[],
                loading:false,
                treeOption:{
                    filter:false
                },
                treeData:[
                    // {
                    //     label:'测试图纸分类001',
                    //     id:'1721418020917616641',
                    //     type:'classify',
                    //     children: [
                    //         {
                    //             label: '业务区',
                    //             type:'area',
                    //             id:'1',
                    //             children: [
                    //                 {
                    //                     label: '一号楼',
                    //                     type:'build',
                    //                     id:'001',
                    //                     children:[
                    //                         {
                    //                             label:'一层',
                    //                             type:'floor',
                    //                             id:'0001',
                    //                         }
                    //                     ]
                    //                 }
                    //             ]
                    //         },
                    //         {
                    //             label: '塔台',
                    //             type:'area',
                    //             id:'2',
                    //             children: [
                    //                 {
                    //                     label: '辅楼',
                    //                     children:[
                    //                         {
                    //                             label:'一楼'
                    //                         }
                    //                     ]
                    //                 }
                    //             ]
                    //         }
                    //     ]
                    // }
                ],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                draweClassId:'',//图纸分类id
                build:'',//楼号键值
                floor:'', //楼层键值
                type:'',//区域类型
                dataRules:{
                    draweClassId:[{
                        required:true,
                        message:'请选择图纸类型',
						trigger:'blur'
                    }],
                    type:[{
                        required:true,
                        message:'请选择区域',
						trigger:'blur'
                    }],
                    build:[{
                        required:true,
                        message:'请选择楼号',
						trigger:'blur'
                    }],
                },
                imgList:[],
                fileList:[],
                dialogType:'',
                editId:'',
            }
        },
        created(){
            this.getTypeList()
            this.gettree()
        },
        methods:{
            getTypeList(){
                getList({current:1,size:100}).then(res =>{
                    this.classifyData = res.data.data.records
                    console.log('data ======>',this.classifyData)
                })
            },
            gettree(){
                getTerrData().then(res =>{
                    console.log('res =====>',res)
                    this.treeData = res.data.data
                })
            },
            // 切换区域数据
            changeArea(val){
                this.dataForm.build = ''
                if(val == 1){
                    getDict({current:1,size:100,parentId: '1721347822365741058'}).then(res =>{
                        console.log('res ====>',res)
                        this.buildData = res.data.data
                    })
                }else if(val == 2){
                    getDict({current:1,size:100,parentId: '1721406335628627969'}).then(res =>{
                        console.log('res ====>',res)
                        this.buildData = res.data.data
                    })
                }
            },
            // 点击新增按钮
            handleAdd(){
                this.dialogTitle = '新增图纸'
                this.dialogType = 'add'
                this.dataForm = {
                    draweClassId:'',
                    type:'',
                    build:'',
                    floor:'',
                    url:''
                }
                this.imgList = []
                this.fileList = []
                setTimeout(() =>{
                    this.dialogVisible = true
                },200)
            },
            // 图片上传成功
			handleSuccess(response, file, fileList){
				console.log('response ===>',response)
				console.log('fileList ===>',fileList)
				if(response.code == 200){
					this.imgList.push({url:response.data.link,name:response.data.originalName})
				}
			},
            // 删除图片
            handleRemove(file,fileList){
				console.log(file)
					if(file.response){
						this.imgList = this.imgList.filter(item => item.url !== file.response.data.link)
					}else{
						this.imgList = this.imgList.filter(item => item.url !== file.url.slice(file.url))
					}
					console.log(this.imgList)
			},
            warnClose(){
                this.dialogVisible = false
            },
            // 新增/编辑保存按钮
            sureAdd() {
				this.$refs['form'].validate((valid) => {
                    console.log('form ====>',this.dataForm)
                    console.log('img ====>',this.imgList)
                    if(this.dialogType == 'add'){
                        if(this.imgList.length == 0){
                            this.$message.error('请上传图片')
                        }else{
                            let imgUrl = []
                            let nameArr = []
                            this.imgList.map(item =>{
                                imgUrl.push(item.url)
                                nameArr.push(item.name)
                            })
                            let params = {
                                draweClassId:this.dataForm.draweClassId,
                                type:this.dataForm.type,
                                build:this.dataForm.build,
                                floor:this.dataForm.floor,
                                url:imgUrl.join(','),
                                originalName:nameArr.join(','),
                                remark:this.dataForm.remark
                            }
                            console.log('params ===>',params)
                            addDraw(params).then(res =>{
                                console.log('res ====>',res)
                                if(res.data.code == 200){
                                    this.page.currentPage = 1;
                                    this.onLoad()
                                    this.$message.success('新增成功')
                                    this.dialogVisible = false
                                }else{
                                    this.onLoad()
                                    this.$message.error('新增失败')
                                    this.dialogVisible = false
                                }
                            }).catch(err =>{
                                this.onLoad()
                                this.$message({
                                    type: 'error',
                                    message: err
                                });
                                this.dialogVisible = false
                            })
                        }
                    }else if(this.dialogType == 'edit'){
                        if(this.imgList.length == 0){
                            this.$message.error('请上传图片')
                        }else{
                            let imgUrl = []
                            let nameArr = []
                            this.imgList.map(item =>{
                                imgUrl.push(item.url)
                                nameArr.push(item.name)
                            })
                            let params = {
                                id:this.dataForm.id,
                                draweClassId:this.dataForm.draweClassId,
                                type:this.dataForm.type,
                                build:this.dataForm.build,
                                floor:this.dataForm.floor,
                                url:imgUrl.join(','),
                                originalName:nameArr.join(','),
                                remark:this.dataForm.remark
                            }
                            console.log('params ===>',params)
                            editDraw(params).then(res =>{
                                if(res.data.code == 200){
                                    this.onLoad()
                                    this.$message.success('修改成功')
                                    this.dialogVisible = false
                                }else{
                                    this.onLoad()
                                    this.$message.error('修改失败')
                                    this.dialogVisible = false
                                } 
                            }).catch(err =>{
                                this.onLoad()
                                this.$message({
                                    type: 'error',
                                    message: err
                                });
                                this.dialogVisible = false
                            })
                        }
                    }
                    
                })
            },
            // 切换楼号
            changeBuild(val){
                this.dataForm.floor = ''
                let tmp = this.buildData.find(item => item.dictKey == val)
                this.floorData = tmp.children
            },
            searchChange(params, done) {
                this.page.currentPage = 1;
                this.onLoad();
                done();
            },
            searchReset() {
                this.equipName = ''
                this.page.currentPage = 1;
                this.onLoad(this.page);
            },
            currentChange(currentPage) {
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize) {
                this.page.pageSize = pageSize;
            },
            refreshChange() {
                this.onLoad();
            },
            onLoad() {
                this.loading = true;
                // this.data = [
                //     {name:'分类一',build:'1号楼',floor:'1层',img:'../../../img/cad/peidian/4DS001.png'},
                //     {name:'分类二',build:"1号楼",floor:'2层',img:'../../../img/cad/peidianxiang/6BS005.png'},
                // ];
                // this.page.total = this.data.length;
                // this.loading = false
                getDrawList({current:this.page.currentPage,size:this.page.pageSize,draweClassId:this.draweClassId,type:this.type,build:this.build,floor:this.floor}).then(res =>{
                    this.data = res.data.data.records;
                    this.page.total = res.data.data.total;
                    this.loading = false
                })
            },
            // 预览图片
            handleView(row){
                this.srcList = row.url.split(',')
                this.url = this.srcList[0];
                // 使用el-image
                setTimeout(() => {
                    this.$refs.preview.clickHandler();
                }, 500)
            },
            // 编辑按钮
            handleEdit(row){
                this.dataForm = JSON.parse(JSON.stringify(row));
                this.dialogTitle = '编辑图纸'
                this.dialogType = 'edit'
                this.fileList = []
                this.imgList = []
                if(this.dataForm.type == 1){
                    getDict({current:1,size:100,parentId: '1721347822365741058'}).then(res =>{
                        console.log('res ====>',res)
                        this.buildData = res.data.data
                        let tmp = this.buildData.find(item => item.dictKey == this.dataForm.build)
                        this.floorData = tmp.children;
                    })
                }else if(this.dataForm.type == 2){
                    getDict({current:1,size:100,parentId: '1721406335628627969'}).then(res =>{
                        console.log('res ====>',res)
                        this.buildData = res.data.data
                        let tmp = this.buildData.find(item => item.dictKey == this.dataForm.build)
                        this.floorData = tmp.children;
                    })
                }
                let imgData = this.dataForm.url.split(',')
                let nameData = this.dataForm.originalName.split(',')
                imgData.map(item =>{
                    this.fileList.push({url:item})
                    this.imgList.push({url:item})
                })
                nameData.map((item,index) =>{
                    this.imgList[index].name = nameData[index]
                })
                console.log('img ====>',this.imgList)
                setTimeout(() =>{
                    this.dialogVisible = true
                },200)
            },
            // 删除按钮
            handleDelete(row){
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    return deleteDraw(row.id);
                }).then(res =>{
                    if(res.data.code == 200){
                        this.onLoad();
                        this.$message.success('删除成功')
                    }
                })
            },
            // 树节点点击
            nodeClick(data,node){
                let result = this.findParent(this.treeData,data)
                this.draweClassId =  result.find(item => item.type == 'classify') ? result.find(item => item.type == 'classify').id : ''
                this.type =  result.find(item => item.type == 'area') ? result.find(item => item.type == 'area').id : ''
                this.build =  result.find(item => item.type == 'build') ? result.find(item => item.type == 'build').id : ''
                this.floor =  result.find(item => item.type == 'floor') ? result.find(item => item.type == 'floor').id : ''
                console.log('result ====>',result)
                this.onLoad()
            },
            // 根据子节点查找父节点
            findParent(data, val) {
                for (let i = 0; i < data.length; i++) {
                    if (data[i] && data[i] === val) {
                    return [data[i]]
                    }
                    if (data[i] && data[i].children) {
                    let d = this.findParent(data[i].children, val)
                    if (d) {
                        return d.concat(data[i])
                    }
                    }
                }
            }
        },
    }
</script>

<style lang="scss" scoped>
    .box {
        height: 800px;
        // padding:20px;
        // background:#fff;
    }

    .el-scrollbar {
        height: 100%;
    }

    .box .el-scrollbar__wrap {
        overflow: scroll;
    }
    /deep/ .avue-tree{
        .avue-tree__filter{
            .el-input{
                .el-input-group__append{
                    display:none;
                }
            }
        }
    }
</style>
<style>
.drawClass{
    .hide{
        .el-upload--picture-card{
            display:none;
        }
    }
}
</style>