<template>
    <div class='add-form'>
        <div class='form2'>
            <div class='input-left'>
                <el-row :gutter='20'>
                    <el-col :span='12'>
                        <div>图例编码</div>
                        <el-input v-model='ruleForm.Id' style='width:200px;height:32px;' disabled></el-input>
                    </el-col>
                    <el-col :span='12'>
                        <div class='start'>图例名称</div>
                        <el-input v-model='ruleForm.Name' style='width:200px;height:32px;'></el-input>
                    </el-col>
                    <el-col :span='12' style='margin-top:20px'>
                        <div class>单位</div>
                        <el-input v-model='ruleForm.Unit' style='width:200px;height:32px;'></el-input>
                    </el-col>

                    <el-col :span='12' style='margin-top:20px'>
                        <div class='start'>图例类型</div>
                        <el-select v-model='ruleForm.Type' placeholder='请选择' style='width:200px;height:32px' @change='initGraph'>
                            <el-option v-for='item in options' :key='item.value' :label='item.label' :value='item.value'></el-option>
                        </el-select>
                    </el-col>
                </el-row>
            </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 :key='key' :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 start' v-if='ruleForm.Type=="Zone"'>填充色以及透明度</span>
                <span class='form3-span3 start'>边框颜色</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'
                    :on-remove='handleRemove'
                >
                    <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-span3'>铺位可视化typeid</span>
            </div>
            <div class='form3-bottom'>
                <span class='device-list'>
                    <TreeSelect
                        tipPlace='top'
                        width='200'
                        style=' margin-right:48px;'
                        :returnParentNode='true'
                        :isShowAllChoice='true'
                        :choseArea='true'
                        :data='deviceList'
                        @change='treeConfirmDevice'
                        :hideClear='true'
                        :lastStage='true'
                        :selectedIds='InfosList'
                        :notNull='true'
                    />
                </span>
                <TreeSelect
                    tipPlace='top'
                    width='200'
                    :notNull='true'
                    :returnParentNode='false'
                    :isShowAllChoice='true'
                    :choseArea='true'
                    :data='typeVisualization'
                    @change='treeConfirm'
                    @focusChange='focusChange'
                    :hideClear='true'
                    :selectedIds='InfoTypeIdList'
                    :lastStage='true'
                />
            </div>
        </div>
    </div>
</template>

<script>
import { queryDeviceAndPOsition, 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: '线条'
                }
            ],

            selectedIds: [],
            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: [],
            file: '',
            // 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: [],

            // majorList: [], //专业
            deviceList: [],
            key: 1,
            InfoLocals: undefined, //工程信息化
            // InfoSystems: undefined, //工程信息化专业/系统
            InfoTypeIds: undefined //铺位可视化typeid
        }
    },
    props: ['ruleForm', 'title', 'InfosList', 'InfoTypeIdList'],

    methods: {
        //业下设备分类和位置分类树形结构
        initQueryDeviceAndPOsition() {
            let postParams = {}
            queryDeviceAndPOsition({ postParams }).then(res => {
                this.deviceList = res.data
            })
        },
        handleRemove(file, fileList) {
            // console.log(file, fileList, 'file')
            this.ruleForm.Url = ''
        },
        getFile(file) {
            // let imgSrc = document.querySelector('.input-right>img')
            // console.log(imgSrc)
            this.file = file.file
            var formData = new FormData()
            formData.append('file', file.file)
            if (this.ruleForm.Url) {
                formData.append('uid', this.ruleForm.Url)
            }
            let postParams = formData
            uploadImg({ postParams }).then(res => {
                if (res.Result == 'success') {
                    this.key++
                    this.$set(this.ruleForm, 'Url', res.EntityList[0])
                    this.$message.success('图标上传成功！')
                }
            })
        },
        create() {
            //新增
            if (this.ruleForm.FillColor.indexOf('#') > -1) {
                this.ruleForm.FillColor = this.ruleForm.FillColor
            } else {
                this.ruleForm.FillColor = this.hexify(this.ruleForm.FillColor)
            }
            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() {
            //修改
            if (this.ruleForm.FillColor.indexOf('#') > -1) {
                this.ruleForm.FillColor = this.ruleForm.FillColor
            } else {
                this.ruleForm.FillColor = this.hexify(this.ruleForm.FillColor)
            }
            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) {
            if (color) {
                var opacity = ''
                var rgb = color.split(',')
                var r = parseInt(rgb[0].split('(')[1])
                var g = parseInt(rgb[1])
                var b = parseInt(rgb[2].split(')')[0])
                switch (parseFloat(rgb[3] || 1) + '') {
                    case '0':
                        opacity = '00'
                        break
                    case '0.05':
                        opacity = '0C'
                        break
                    case '0.1':
                        opacity = '19'
                        break
                    case '0.15':
                        opacity = '26'
                        break
                    case '0.2':
                        opacity = '33'
                        break
                    case '0.25':
                        opacity = '3F'
                        break
                    case '0.3':
                        opacity = '4C'
                        break
                    case '0.35':
                        opacity = '59'
                        break
                    case '0.4':
                        opacity = '66'
                        break
                    case '0.45':
                        opacity = '72'
                        break
                    case '0.5':
                        opacity = '7F'
                        break
                    case '0.55':
                        opacity = '8C'
                        break
                    case '0.6':
                        opacity = '99'
                        break
                    case '0.65':
                        opacity = 'A5'
                        break
                    case '0.7':
                        opacity = 'B2'
                        break
                    case '0.75':
                        opacity = 'BF'
                        break
                    case '0.8':
                        opacity = 'CC'
                        break
                    case '0.85':
                        opacity = 'D8'
                        break
                    case '0.9':
                        opacity = 'E5'
                        break
                    case '0.95':
                        opacity = 'F2'
                        break
                    case '1':
                        opacity = 'FF'
                        break
                }
                var hex = '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1) + opacity
                return hex
            } else {
                return
            }
        },
        // 背景颜色改变
        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)
            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() {
            let vm = this
            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(vm.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 {
                        }
                    }
                })
            }
        },
        // 铺位可视化
        treeConfirm(data) {
            //console.log(data, 'data')
            this.$set(this.ruleForm, 'InfoTypeId', data)
        },

        //位置/设备
        treeConfirmDevice(id, info) {
            console.log(id)
            // this.$set(this.ruleForm, 'InfoLocal', data)
            let InfoSystem = []
            let InfoLocal = []
            if (info && info.length > 0) {
                for (let i = 0; i < info.length; i++) {
                    let type = info[i]
                    if (type.name.includes('/')) {
                        InfoLocal.push(type)
                        //位置/设备
                        this.$set(this.ruleForm, 'InfoLocal', InfoLocal)
                    } else {
                        InfoSystem.push(type)
                        //专业
                        this.$set(this.ruleForm, 'InfoSystem', InfoSystem)
                    }
                }
            } else {
                this.$set(this.ruleForm, 'InfoLocal', [])
                this.$set(this.ruleForm, 'InfoSystem', [])
            }
        },
        focusChange(status) {
            // //console.log('focusChange', status)
        },
        visualization() {
            getVisualization({}).then(res => {
                this.typeVisualization =
                    res.Data &&
                    res.Data.map(i => {
                        return {
                            id: i.Id,
                            name: i.Name,
                            children: i.Children
                                ? i.Children.map(j => {
                                      return {
                                          id: j.Id,
                                          name: j.Id + '-' + j.Name
                                      }
                                  })
                                : []
                        }
                    })
            })
        },
        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.initQueryDeviceAndPOsition()
        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;
    .start::after {
        content: '*';
        color: #f56c6c;
        margin-left: 4px;
    }
    .ant-input-number {
        border-radius: 4px 0 0 4px;
    }

    .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;
            img {
                width: 28px;
                height: 28px;
            }
            .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;
            }
            .form4-span3 {
                margin-left: 75px;
            }
        }
    }
    .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;
        }
    }

    .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>

<style >
.p-select-area {
    width: 480px !important;
}
.p-select-area .p-transfer-left {
    width: 236px !important;
}
.p-tree-node-check .p-tree-node-title .p-tree-node-name {
    word-break: break-all !important;
    white-space: normal !important;
    word-break: break-all !important;
    word-wrap: break-word !important;
    height: auto !important;
    line-height: 25px;
}
.p-select-area .p-transfer-right {
    width: 245px !important;
}

.p-select-area .p-transfer-right .p-transfer-selected .p-transfer-selected-item > span {
    word-break: break-all !important;
    white-space: normal !important;
    word-break: break-all !important;
    word-wrap: break-word !important;
    height: auto !important;
    line-height: 25px;
    display: block;
    width: 225px;
    padding-right: 3px;
}
</style>