<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> -->
                        <Input v-model='ruleForm.Id' disabled placeholder style='width:200px' />
                    </el-col>
                    <el-col :span='12'>
                        <div class='start'>图例名称</div>
                        <!-- <el-input v-model='ruleForm.Name' style='width:200px;height:32px;'></el-input> -->
                        <Input v-model='ruleForm.Name' placeholder :maxlength='maxlength' style='width:200px' />
                    </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> -->
                        <Input v-model='ruleForm.Unit' placeholder style='width:200px' />
                    </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>-->
                        <span class='add-form-type'>
                            <Select
                                width='200'
                                height='40'
                                v-model='ruleForm.Type'
                                :isReadOnly='true'
                                @change='initGraph'
                                :hideClear='true'
                                :selectdata='options'
                                placeholder='请选择'
                            />
                        </span>
                    </el-col>
                </el-row>
            </div>
            <div v-show='ruleForm.Type=="Zone" || ruleForm.Type=="Image" || ruleForm.Type =="Line"'>
                <div style='color:#646C73'>展示预览</div>
                <div class='input-right' ref='graph' style='width:200px;height:114px;'>
                    <canvas id='canvas' :width='canvasWidth' :height='canvasHeight'></canvas>
                </div>
            </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' v-if='ruleForm.Type!="Line"'>铺位可视化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
                    v-if='ruleForm.Type!="Line"'
                    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 transparency from './../legendLibrary/transparency.js'
import { FloorView } from '@/lib/FloorView'
import { FloorScene } from '@/lib/FloorScene'
import { GraphView } from '@/lib/GraphView'
export default {
    data() {
        return {
            maxlength: 20,
            options: [
                {
                    id: 'None',
                    name: '非图例'
                },
                {
                    id: 'Zone',
                    name: '区域'
                },
                {
                    id: 'Image',
                    name: '图标'
                },
                {
                    id: 'Line',
                    name: '线条'
                }
            ],

            selectedIds: [],
            borderLineOption: [
                {
                    id: 'solid',
                    src: require('@/assets/imgs/1pxlines.png')
                    // src: require('@/assets/imgs/1pxline.jpg')
                },
                {
                    id: 'dashed',
                    src: require('@/assets/imgs/dashedLines.png')
                    // src: require('@/assets/imgs/dashedLine.jpg')
                },
                {
                    id: 'dotted',
                    src: require('@/assets/imgs/dotLines.png')
                    // 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: 28,
            canvasHeight: 28,
            view: null,
            scene: null,
            typeVisualization: [],
            // majorList: [], //专业
            deviceList: [],
            formData: [], //上传乳品的formdata
            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 = ''
        },
        //获取上传图片的信息 canvas得到图的url
        getFile(file) {
            this.file = file.file
            var reader = new FileReader()
            reader.readAsDataURL(this.file)
            reader.onload = e => {
                this.view.url = e.target.result
            }
        },
        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
            //修改的时候canvas的image可以预览
            if (this.ruleForm.Url && type == 2) {
                let url = `/serve/topology-wanda/Picture/query/${this.ruleForm.Url}`
                this.view.url = url
            } else {
                this.view.url = ''
            }
        },
        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) {
                let opacity = '',
                    rgb = color.split(','),
                    r = parseInt(rgb[0].split('(')[1]),
                    g = parseInt(rgb[1]),
                    b = parseInt(rgb[2].split(')')[0]),
                    a = Number(rgb[3].split(')')[0] || 1) * 100

                transparency.forEach((i, index) => {
                    if (index == a) {
                        opacity = i
                    }
                })

                var hex = '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1) + opacity
                console.log(hex)
                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:#ffffff url(' + this.borderLineOptionObject.src + ')  10px 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 })
        },
        // 把canvas图保存到图片服务器
        saveImg() {
            let vm = this
            if (!this.file) {
                //修改图片的时候没有重新上传图片
                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 {
                if (this.view) {
                    let data = this.view.canvasView.toDataURL('image/png')
                    var formData = new FormData()
                    if (this.ruleForm.Type == 'Zone' || this.ruleForm.Type == 'Line') {
                        formData.append('file', this.base64ToFile(data))
                    } else {
                        formData.append('file', this.file)
                    }
                    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)
                            }
                        }
                    })
                }
            }
        },
        // 铺位可视化
        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()
        }
    },
    watch: {
        'ruleForm.Id': {
            handler() {
                this.initQueryDeviceAndPOsition()
                this.visualization()
                if (this.title == '修改图例库') {
                    if (this.ruleForm.Type != 'Image') {
                        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;
    }
    // .add-form-type {
    //     /deep/ .p-select .p-select-header {
    //         height: 40px;
    //         line-height: 40px;
    //         border: 1px solid #dcdfe6;
    //     }
    //     /deep/ .p-select .p-select-header .p-select-selected-box .p-select-fakePlaceholder {
    //         line-height: 40px;
    //     }
    //     /deep/ .p-select .p-select-header .p-select-triangle{
    //         top: 12px;
    //     }
    // }
    .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;
        line-height: 26px;
    }
}
</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: 21px;
}
.p-select-area .p-transfer-right {
    width: 245px !important;
}
.p-select-area .p-transfer-right .p-transfer-selected .p-transfer-selected-item {
    height: 25px;
}
.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: 16px;
    display: block;
    width: 225px;
    padding-right: 3px;
}
.p-popover-tip-content .p-popover-tip-content-item {
    margin-left: 4px;
    margin-bottom: 8px;
    padding-left: 4px;
    padding-right: 4px;
    background-color: #f5f6f7 !important;
    border-radius: 2px;
    max-width: 100%;
    overflow: hidden;
    white-space: nowrap;
}
</style>