<template>
    <div class='add-form'>
        <div class='form1'>
            <span class='span1'>图例编码</span>
            <span class='span2'>图例名称</span>
            <span class='span3' v-if='ruleForm.Type=="Zone" || ruleForm.Type=="Image"'>展示预览</span>
        </div>
        <div class='form2'>
            <div class='input-left'>
                <el-input v-model='ruleForm.Code' disabled style='width:200px;height:32px;margin-right:48px;'></el-input>
                <el-input v-model='ruleForm.Name' style='width:200px;height:32px;'></el-input>
                <div class='title'>单位</div>
                <div class='type'>图例类型</div>
                <el-input v-model='ruleForm.Unit' style='width:200px;height:32px;'></el-input>
                <el-select v-model='ruleForm.Type' placeholder='请选择' style='width:200px;height:32px;margin-left:46px' @change='initGraph'>
                    <el-option v-for='item in options' :key='item.value' :label='item.label' :value='item.value'></el-option>
                </el-select>
            </div>
            <div class='input-right' ref='graph' v-show='ruleForm.Type=="Zone" || ruleForm.Type=="Image" || ruleForm.Type =="Line"'>
                <div v-show=' ruleForm.Type=="Image" && ruleForm.Url' class='input-right'>
                    <img :src='`/serve/topology-wanda/Picture/query/${ruleForm.Url}`' alt />
                    <!-- {{ruleForm.Url}} -->
                </div>
                <canvas id='canvas' :width='canvasWidth' :height='canvasHeight' v-show='!(ruleForm.Type=="Image" && ruleForm.Url)'></canvas>
            </div>
        </div>
        <div v-if='ruleForm.Type=="Zone" || ruleForm.Type=="Line"' class='form3'>
            <div class='form3-top'>
                <span class='form3-span1' v-if='ruleForm.Type=="Zone"'>填充色以及透明度</span>
                <span class='form3-span3'>边框颜色</span>
                <span class='form3-span4'>边框线型</span>
                <span class='form3-span5'>边框粗细</span>
            </div>
            <div class='form3-bottom'>
                <el-color-picker
                    v-if='ruleForm.Type=="Zone"'
                    v-model='ruleForm.FillColor'
                    style='margin:0 172px 0 10px'
                    show-alpha
                    @change='changBgColor'
                    :color-format='"hex"'
                ></el-color-picker>
                <el-color-picker v-model='ruleForm.Color' style='margin:0 90px 0 10px' @change='changLineColor'></el-color-picker>

                <el-select
                    v-model='ruleForm.LineDash'
                    placeholder='请选择'
                    size='small'
                    style='width:160px;margin-right:24px'
                    ref='select1'
                    @change='changeLineType'
                >
                    <el-option v-for='item in borderLineOption' :key='item.id' :label='item.src' :value='item.id'>
                        <img :src='item.src' alt />
                    </el-option>
                </el-select>

                <div style='position:relative'>
                    <a-input-number id='inputNumber' v-model='ruleForm.LineWidth' :min='1' :max='10' ref='select' @change='changeLineWidth' />
                    <span class='line-width'>px</span>
                </div>
            </div>
        </div>
        <div v-if='ruleForm.Type=="Image"' class='form5'>
            <div class='form5-top'>上传新图标</div>
            <div>
                <el-upload
                    class='upload-demo'
                    action='https://jsonplaceholder.typicode.com/posts/'
                    :http-request='getFile'
                    :file-list='fileList'
                    :on-change='handleChange'
                >
                    <el-button size='small' style='color:#1F2329;'>点击上传</el-button>
                </el-upload>
            </div>
        </div>
        <div v-if='ruleForm.Type!="None"' class='form4'>
            <div class='form4-top'>
                <span class='form4-span1'>对应工程信息化中的位置/设备分类</span>
                <span class='form4-span2'>工程信息化的专业</span>
                <span class='form4-span3'>铺位可视化typeid</span>
            </div>
            <div class='form3-bottom'>
                <!-- <el-select v-model='value' placeholder='请选择' size='small' style='width:200px;margin-right:48px;'>
                    <el-option v-for='item in options1' :key='item.value' :label='item.label' :value='item.value'></el-option>
                </el-select>
                <el-select v-model='value' placeholder='请选择' size='small' style='width:200px;margin-right:48px'>
                    <el-option v-for='item in options2' :key='item.value' :label='item.label' :value='item.value'></el-option>
                </el-select>-->

                <TreeSelect
                    tipPlace='top'
                    width='200'
                    style=' margin-right:48px;'
                    :notNull='true'
                    :returnParentNode='false'
                    :isShowAllChoice='true'
                    :choseArea='true'
                    :data='deviceList'
                    @change='treeConfirmDevice'
                />

                <TreeSelect
                    tipPlace='top'
                    width='200'
                    style=' margin-right:48px;'
                    :notNull='true'
                    :returnParentNode='false'
                    :isShowAllChoice='true'
                    :choseArea='true'
                    :data='majorList'
                    @change='treeConfirmMajor'
                />

                <TreeSelect
                    tipPlace='top'
                    width='200'
                    :notNull='true'
                    :returnParentNode='false'
                    :isShowAllChoice='true'
                    :choseArea='true'
                    :data='typeVisualization'
                    @change='treeConfirm'
                    @focusChange='focusChange'
                />
            </div>
        </div>
    </div>
</template>

<script>
import { createLegend, updateLegend, uploadImg, getVisualization } from '@/api/legendLibrary.js'
import { FloorView } from '@/lib/FloorView'
import { FloorScene } from '@/lib/FloorScene'
import { GraphView } from '@/lib/GraphView'
export default {
    data() {
        return {
            options: [
                {
                    value: 'None',
                    label: '非图例'
                },
                {
                    value: 'Zone',
                    label: '区域'
                },
                {
                    value: 'Image',
                    label: '图标'
                },
                {
                    value: 'Line',
                    label: '线条'
                }
            ],
            options1: [],
            options2: [],
            options3: [],
            borderLineOption: [
                {
                    id: 'solid',
                    src: require('@/assets/imgs/1pxline.jpg')
                },
                {
                    id: 'dashed',
                    src: require('@/assets/imgs/dashedLine.jpg')
                },
                {
                    id: 'dotted',
                    src: require('@/assets/imgs/dotLine.jpg')
                }
            ],
            linepxOption: [
                {
                    id: 1,
                    src: require('@/assets/imgs/1pxline.jpg')
                },
                {
                    id: 2,
                    src: require('@/assets/imgs/2pxline.jpg')
                },
                {
                    id: 3,
                    src: require('@/assets/imgs/3pxline.jpg')
                }
            ],
            fileList: [],
            // this.ruleForm.Url 图标的key,/serve/topology-wanda/Picture/query/${this.ruleForm.Url}
            value: '',
            linepxObject: {
                src: ''
            },
            borderLineOptionObject: {
                src: ''
            },
            canvasWidth: 200,
            canvasHeight: 114,
            view: null,
            scene: null,
            typeVisualization: [],
            visualizationList: [], //已选铺位可视化
            majorList: [], //专业
            deviceList: []
        }
    },
    props: ['ruleForm', 'title'],
    methods: {
        getFile(file) {
            var formData = new FormData()
            formData.append('file', file.file)
            formData.append('uid', this.ruleForm.Url)
            let postParams = formData
            uploadImg({ postParams }).then(res => {
                if (res.Result == 'success') {
                    this.$set(this.ruleForm, 'Url', res.EntityList[0])
                    this.$message.success('图标上传成功！')
                }
            })
        },
        create() {
            //新增
            let postParams = {
                Content: [this.ruleForm]
            }
            createLegend({ postParams }).then(res => {
                if (res.Result == 'success') {
                    this.$message.success('添加图例成功！')
                    this.$emit('addSuccess')
                    this.fileList = []
                } else {
                    this.$message.error(res.Message)
                }
            })
        },
        update() {
            //修改
            let postParams = {
                Content: [this.ruleForm]
            }
            updateLegend({ postParams }).then(res => {
                if (res.Result == 'success') {
                    this.$message.success('图例修改成功！')
                    this.$emit('updateSuccess')
                    this.fileList = []
                } else {
                    this.$message.error(res.Message)
                }
            })
        },
        handleChange(file, fileList) {
            this.fileList = fileList.slice(-1)
        },
        clearGraphy(type) {
            if (!(this.view instanceof GraphView)) {
                this.view = new GraphView('canvas')
            }
            this.view.type = type
            if (this.ruleForm.FillColor.indexOf('#') > -1) {
                this.view.bgcolor = this.ruleForm.FillColor
            } else {
                this.view.bgcolor = this.hexify(this.ruleForm.FillColor)
            }
            this.view.strokecolor = this.ruleForm.Color
            this.view.lineType = this.ruleForm.LineDash
            this.view.lineWidth = this.ruleForm.LineWidth
        },
        initGraph() {
            if (this.ruleForm.Type == 'Zone' || this.ruleForm.Type == 'Line' || this.ruleForm.Type == 'Image') {
                //1是区域 0是线条
                this.clearGraphy(this.ruleForm.Type == 'Zone' ? 1 : this.ruleForm.Type == 'Line' ? 0 : 2)
            }
        },
        //rgba转成16进制
        hexify(color) {
            var values = color
                .replace(/rgba?\(/, '')
                .replace(/\)/, '')
                .replace(/[\s+]/g, '')
                .split(',')
            var a = parseFloat(values[3] || 1),
                r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
                g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
                b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255)
            return '#' + ('0' + r.toString(16)).slice(-2) + ('0' + g.toString(16)).slice(-2) + ('0' + b.toString(16)).slice(-2)
        },
        // 背景颜色改变
        changBgColor(val) {
            if (this.view) {
                this.view.bgcolor = this.hexify(val)
            }
        },
        // 线条颜色改变
        changLineColor(val) {
            if (this.view) {
                this.view.strokecolor = val
            }
        },
        //线条类型改变
        changeLineType(val) {
            this.$set(this.ruleForm, 'LineDash', val)
            this.borderLineOptionObject = val && this.borderLineOption.find(item => item.id == val)
            if (this.$refs.select1 && this.$refs.select1.$el) {
                this.$refs.select1.$el.children[0].children[0].setAttribute(
                    'style',
                    'background:url(' + this.borderLineOptionObject.src + ')  center center no-repeat;color:transparent;'
                )
            }
            if (this.view) {
                this.view.lineType = val
            }
        },
        //线条宽度
        changeLineWidth(val) {
            this.$set(this.ruleForm, 'LineWidth', val)
            // this.linepxObject = val && this.linepxOption.find(item => item.id == val)
            // if (this.$refs.select && this.$refs.select.$el) {
            //     this.$refs.select.$el.children[0].children[0].setAttribute(
            //         'style',
            //         'background:url(' + this.linepxObject.src + ') center center no-repeat;color:transparent;'
            //     )
            // }

            if (this.view) {
                this.view.lineWidth = Number(val)
            }
        },
        base64ToFile(dataurl, filename) {
            console.log(dataurl, 'url')
            let arr = dataurl.split(',')
            let mime = arr[0].match(/:(.*?);/)[1]
            if (!filename) {
                filename = `${new Date().getTime()}.${mime.substr(mime.indexOf('/') + 1)}`
            }
            let bstr = atob(arr[1])
            let n = bstr.length
            let u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new File([u8arr], filename, { type: mime })
        },
        saveImg() {
            if (this.view) {
                let data = this.view.canvasView.toDataURL('image/png')
                var formData = new FormData()
                formData.append('file', this.base64ToFile(data))
                let postParams = formData
                uploadImg({ postParams }).then(res => {
                    if (res.Result == 'success') {
                        this.$set(this.ruleForm, 'Url', res.EntityList[0])
                        this.$message.success('图标上传成功！')
                        if (this.title == '添加图例库') {
                            this.create()
                            this.$emit('addSuccess')
                            this.view.canvas.clearRect(0, 0, this.width, this.height)
                        } else if (this.title == '修改图例库') {
                            this.update()
                            this.$emit('updateSuccess')
                            this.view.canvas.clearRect(0, 0, this.width, this.height)
                        } else {
                        }
                    }
                })
            }
        },
        // 多选返回的id组
        treeConfirm(data) {
            console.log(data, 'data')
            this.visualizationList = data
        },
        //专业
        treeConfirmMajor(id, info) {
            console.log(id)
        },
        //位置/设备
        treeConfirmDevice(id, info) {
            console.log(id)
        },
        focusChange(status) {
            // console.log('focusChange', status)
        },
        visualization() {
            getVisualization({}).then(res => {
                this.typeVisualization = res.Data && res.Data.map(i => this.getTree(i))
                console.log(this.typeVisualization)
            })
        },
        getTree(data) {
            return {
                id: data.Id,
                name: data.Name,
                children: data.Children ? data.Children.map(i => this.getTree(i)) : []
            }
        },
        focusChange(status) {
            console.log('focusChange', status)
        }
    },
    mounted() {
        this.visualization()

        if (this.title == '修改图例库') {
            this.changeLineWidth(this.ruleForm.LineWidth)
            this.changeLineType(this.ruleForm.LineDash)
            this.initGraph()
        }
    },
    updated() {
        if (this.title == '修改图例库') {
            this.changeLineWidth(this.ruleForm.LineWidth)
            this.changeLineType(this.ruleForm.LineDash)
            this.initGraph()
        }
    }
}
</script>

<style lang='less' scoped>
.add-form {
    color: #646c73;
    margin: 16px 0 0 72px;
    font-size: 14px;
    .ant-input-number {
        border-radius: 4px 0 0 4px;
    }
    .form1 {
        margin-bottom: 8px;
        .span1 {
            margin-right: 192px;
        }
        .span2 {
            margin-right: 220px;
        }
    }
    .form2 {
        display: flex;
        .input-left {
            width: 500px;
            .title {
                margin-right: 100px;
                margin: 20px 0 8px 0;
                display: inline-block;
                width: 250px;
            }
            .type {
                margin-right: 100px;
                margin: 20px 0 8px 0;
                display: inline-block;
                width: 250px;
            }
        }
        .input-right {
            width: 200px;
            height: 114px;
            background: rgba(245, 246, 247, 1);
            display: inline-block;
            display: flex;
            align-items: center;
            justify-content: center;
            .model1 {
                width: 56px;
                height: 6px;
            }
            .model {
                width: 56px;
                height: 40px;
            }
        }
    }
    .form3 {
        width: 720px;
        height: 86px;
        background: rgba(245, 246, 247, 1);
        border-radius: 4px;
        margin-top: 20px;
        .form3-top {
            padding: 12px 0 8px 12px;
            .form3-span1 {
                margin-right: 102px;
            }
            .form3-span2 {
                margin-right: 78px;
            }
            .form3-span3 {
                margin-right: 64px;
            }
            .form3-span4 {
                margin-right: 130px;
            }
        }
        .form3-bottom {
            display: flex;
        }
    }
    .form4 {
        .form4-top {
            padding: 20px 0 8px 0;
            .form4-span1 {
                margin-right: 32px;
            }
            .form4-span2 {
                margin-right: 102px;
            }
        }
    }
    .form5 {
        width: 720px;
        height: 86px;
        background: rgba(245, 246, 247, 1);
        border-radius: 4px;
        margin-top: 20px;
        padding-left: 12px;
        .form5-top {
            padding: 12px 0 8px 0;
        }
    }

    .span2::after,
    .type::after,
    .form3-span1::after,
    .form3-span3::after {
        content: '*';
        color: #f56c6c;
        margin-left: 4px;
    }
    .upload-demo {
        display: flex;
    }
    .line-width {
        display: inline-block;
        width: 35px;
        height: 32px;
        background: rgba(239, 240, 241, 1);
        border-radius: 0 4px 4px 0;
        border-right: 1px solid rgba(195, 198, 203, 1);
        border-top: 1px solid rgba(195, 198, 203, 1);
        border-bottom: 1px solid rgba(195, 198, 203, 1);
        position: absolute;
        text-align: center;
    }
}
</style>