<template>
    <Page>
        <el-form :inline="true" class="demo-form-inline">
            <el-form-item style="float: right">
                <el-button type="primary" icon="el-icon-plus" @click="addType">新增</el-button>
            </el-form-item>
        </el-form>
        <el-table
            stripe
            header-cell-class-name="table_header"
            highlight-current-row
            :data="tableData"
            height="calc(100vh - 180px)"
            border
            style="width: 100%"
        >
            <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
            <el-table-column align="center" prop="name" label="统计类型"></el-table-column>
            <el-table-column label="操作" width="320px" align="center">
                <template slot-scope="scope">
                    <!-- <div class="table-operation"> -->
                    <el-button @click="handleClick(scope.row)" type="primary" size="mini" icon="el-icon-share">
                        绑定指标
                    </el-button>
                    <el-button size="mini" type="primary" @click="edit(scope.row)" icon="el-icon-edit">编辑</el-button>
                    <el-button @click="deleteStatistical(scope.row)" type="danger" size="mini" icon="el-icon-delete">
                        删除
                    </el-button>
                    <!-- </div> -->
                </template>
            </el-table-column>
        </el-table>
        <el-dialog
            title="统计指标配置"
            :visible.sync="dialogVisible"
            width="60%"
            :before-close="handleClose"
            class="hhgjk"
        >
            <div class="box">
                <div class="box-left">
                    <el-cascader-panel v-model="fromDataValue" :props="props" :options="fromData"></el-cascader-panel>
                </div>
                <div class="box-center">
                    <el-button type="primary" icon="el-icon-plus" @click="newGroup">新建分组</el-button>
                    <el-popover v-model="popoverVisible" placement="right" width="400" trigger="click">
                        <div class="button-group">
                            <el-button
                                type="primary"
                                style="margin-left: 0"
                                v-for="item in toData"
                                @click="leftCheckChange(item)"
                            >
                                {{ item.label }}
                            </el-button>
                            <div>请先创建分组</div>
                            <!--                                    <el-button type="primary" style="margin-left: 0" @click="leftCheckChange">不分组-->
                            <!--                                    </el-button>-->
                        </div>
                        <el-button
                            slot="reference"
                            style="margin-left: 0"
                            class="mt20"
                            type="primary"
                            icon="el-icon-arrow-right"
                        >
                            向右
                        </el-button>
                    </el-popover>
                    <el-button
                        style="margin-left: 0"
                        icon="el-icon-arrow-left"
                        class="mt20"
                        type="primary"
                        @click="rightCheckChange"
                    >
                        向左
                    </el-button>
                </div>
                <div class="box-right">
                    <el-cascader-panel v-model="toDataValue" :props="props" :options="toData">
                        <template slot-scope="{ node, data }">
                            <div style="display: flex; align-items: center">
                                <div class="hide-txt">{{ data.label }}</div>
                                <template v-if="!node.isLeaf">
                                    <div class="ml5">({{ data.children.length }})</div>
                                    <div style="flex: 1"></div>
                                    <i
                                        class="el-icon-delete ml10"
                                        style="cursor: pointer"
                                        @click="deleteStatistical2(data)"
                                    ></i>
                                </template>
                            </div>
                        </template>
                    </el-cascader-panel>
                </div>
                <!--                    <tree-transfer-->
                <!--                        ref="wl-tree-transfer"-->
                <!--                        filter-->
                <!--                        high-light-->
                <!--                        :mode="mode"-->
                <!--                        :title="title"-->
                <!--                        :button_text="['绑定', '解绑']"-->
                <!--                        :to_data="toData"-->
                <!--                        :from_data="fromData"-->
                <!--                        :filterNode="filterNode"-->
                <!--                        :defaultProps="defaultProps"-->
                <!--                        :defaultCheckedKeys="defaultCheckedKeys"-->
                <!--                        :defaultExpandedKeys="[2, 3]"-->
                <!--                        @right-check-change="rightCheckChange"-->
                <!--                        @left-check-change="leftCheckChange"-->
                <!--                        @render-content="renderContent"-->
                <!--                        @remove-btn="remove"-->
                <!--                        @add-btn="add"-->
                <!--                        node_key="id"-->
                <!--                    >-->
                <!--                    </tree-transfer>-->
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submint">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="30%" :before-close="closeDialog">
            <el-form :model="form" :label-width="formLabelWidth" ref="form" :rules="rules">
                <el-form-item label="名称:" prop="name">
                    <el-input v-model="form.name" autocomplete="off" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="编码:" prop="code">
                    <el-input v-model="form.code" autocomplete="off" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="备注:" prop="remark">
                    <el-input v-model="form.remark" autocomplete="off" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="排序:" prop="sort">
                    <el-input type="" v-model="form.sort" autocomplete="off" placeholder="请输入"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="addTypeSubmit">确 定</el-button>
            </div>
        </el-dialog>
    </Page>
</template>
<script>
import treeTransfer from 'el-tree-transfer'
import {
    queryCsDictTree,
    queryByCode,
    queryStatistical,
    addStatistical,
    addDictTree,
    deleteStatistical,
    updateStatistical
} from '@/api/app/setting'
import api from '@/api/energy/sysconfig'
import { deleteEquipmentDelivery } from '@/api/app/device'

export default {
    name: 'GovernDispositionType',

    computed: {
        title() {
            if (this.mode == 'transfer') {
                return ['未绑定指标', '已绑定指标']
            } else {
                return ['通讯录', '收件人', '抄送人', '密送人']
            }
        },
        vth() {
            return window.sessionStorage.getItem('appheight') - 55
        }
    },
    components: { treeTransfer },
    data() {
        return {
            popoverVisible: false,
            props: { multiple: true },
            dialogFormVisible: false,
            dialogTitle: '新增',
            formLabelWidth: '120px',
            form: {
                code: null,
                name: null,
                pid: null,
                remark: null,
                sort: null
            },
            mode: 'transfer', // transfer addressList
            defaultProps: {
                label: 'name',
                children: 'children'
            },
            fromData: [], // 穿梭框 - 源数据 - 树形
            fromDataValue: [],
            toData: [], // 穿梭框 - 目标数据 - 树形
            toDataValue: [],
            toArray: [],
            defaultCheckedKeys: [], // 左侧默认选中数据
            dialogVisible: false,
            tableData: [],
            zbdata: [],
            bindId: [],
            rowId: '',
            renderFunc(h, option) {
                return <span>{option.label}</span>
            },
            tabHeight: 'calc(100vh - 161px)',
            rules: {
                name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
                code: [{ required: true, message: '编码不能为空', trigger: 'blur' }],
                sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
            }
        }
    },
    created() {},
    mounted() {
        this.queryData()
    },
    methods: {
        resetForm() {
            if (this.$refs['form']) {
                this.$refs['form'].resetFields()
            }
        },
        closeDialog() {
            this.resetForm()
            this.dialogFormVisible = false
        },
        edit(row) {
            this.dialogFormVisible = true
            this.dialogTitle = '编辑'
            for (let key in this.form) {
                if (key != 'pid') {
                    this.form[key] = row[key]
                }
            }
            this.form.id = row.id
        },
        deleteStatistical(row) {
            this.$confirm('确定删除该统计类型吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteStatistical(row.id).then(res => {
                    if (res.code == 'A0000') {
                        this.$message.success('删除成功')
                        this.queryData()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            })
        },
        deleteStatistical2(data) {
            if (data.children.length) {
                return this.$message.warning('该分组下有指标，不能删除')
            }
            this.$confirm('确定删除该分组吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteStatistical(data.value).then(res => {
                    if (res.code == 'A0000') {
                        this.$message.success('删除成功')
                        this.toData = this.toData.filter(item => item.value !== data.value)
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            })
        },
        addTypeSubmit() {
            console.log(this.form)
            // 非空校验
            for (let key in this.form) {
                if (key != 'pid' && key != 'id' && key != 'sort') {
                    if (!this.form[key]) {
                        this.$message.error('请填写完整信息')
                        return
                    }
                }
            }
            if (this.dialogVisible) {
                let obj = JSON.parse(JSON.stringify(this.form))
                obj.pid = this.rowId
                // 新增二级分组
                addDictTree(obj).then(res => {
                    if (res.code == 'A0000') {
                        this.$message.success('新增成功')
                        this.dialogFormVisible = false
                        this.handleClick({ id: this.rowId })
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            } else {
                if (this.form.id) {
                    updateStatistical(this.form).then(res => {
                        if (res.code == 'A0000') {
                            this.$message.success('编辑成功')
                            this.dialogFormVisible = false
                            this.queryData()
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                } else {
                    addDictTree(this.form).then(res => {
                        if (res.code == 'A0000') {
                            this.$message.success('新增成功')
                            this.dialogFormVisible = false
                            this.queryData()
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                }
            }
        },
        addType() {
            for (let key in this.form) {
                if (key != 'pid') {
                    this.form[key] = null
                }
            }
            this.dialogFormVisible = true
            this.dialogTitle = '新增'
        },
        //获取指标树触发事件
        handleClick(row) {
            this.rowId = row.id

            queryStatistical(row.id).then(res => {
                if (res.code == 'A0000') {
                    this.dialogVisible = true
                    console.log(res)
                    this.fromData = []
                    this.fromDataValue = []
                    this.toData = []
                    this.toDataValue = []
                    res.data.unSelectedList.forEach(item => {
                        const obj = {
                            id: item.dataType,
                            value: item.dataType,
                            pid: 0,
                            label: item.dataTypeName,
                            children: []
                        }
                        item.eleEpdPqdVOS.forEach(item2 => {
                            const obj2 = {
                                id: item2.id,
                                pid: item.dataType,
                                value: item2.id,
                                label: item2.phase === 'M' ? item2.showName : item2.phase + '相' + item2.showName
                            }
                            if (item2.showName) {
                                obj.children.push(obj2)
                            }
                        })
                        this.fromData.push(obj)
                    })
                    res.data.selectedList.forEach(item => {
                        const obj = {
                            id: item.dataType,
                            value: item.dataType,
                            pid: 0,
                            label: item.dataTypeName,
                            children: []
                        }
                        item.eleEpdPqdVOS.forEach(item2 => {
                            const obj2 = {
                                id: item2.id,
                                pid: item2.dataType,
                                value: item2.id,
                                label: item2.phase === 'M' ? item2.showName : item2.phase + '相' + item2.showName
                            }
                            if (item2.showName) {
                                obj.children.push(obj2)
                            }
                        })
                        this.toData.push(obj)
                    })
                }
            })
        },
        handleChange(value, direction, movedKeys) {
            console.log(value, direction, movedKeys)
            console.log(movedKeys)
        },
        handleClose() {
            this.dialogVisible = false
        },
        //获取列表数据
        queryData() {
            queryByCode('Statistical_Type').then(res => {
                this.form.pid = res.data.id
                queryCsDictTree(res.data.id).then(res => {
                    if (res.code == 'A0000') {
                        this.tableData = res.data
                    }
                })
            })
        },
        //提交绑定
        submint() {
            this.dialogVisible = true
            console.log(this.toData)
            let ids = []
            let one = {
                id: this.rowId,
                ids: []
            }
            this.toData.forEach(item => {
                let obj = {
                    id: item.id,
                    ids: []
                }
                if (item.children) {
                    item.children.forEach(item2 => {
                        obj.ids.push(item2.value)
                    })
                    ids.push(obj)
                } else {
                    one.ids.push(item.value)
                }
            })
            if (one.ids.length) {
                ids.push(one)
            }

            // var data = {
            //     id: this.rowId,
            //     ids: this.bindId,
            // }
            addStatistical(ids).then(res => {
                if (res.code == 'A0000') {
                    this.$message.success('绑定指标成功')
                    this.dialogVisible = false
                }
            })
        },
        // 获取选中
        getChecked() {
            const checkeds = this.$refs['wl-tree-transfer'].getChecked()
            console.log('获取选中：', checkeds)
        },
        // 设置选中
        setChecked() {
            this.$refs['wl-tree-transfer'].setChecked([3], [2])
        },
        // 清除选中
        clearChecked() {
            this.$refs['wl-tree-transfer'].clearChecked()
        },
        // 自定义筛选函数
        filterNode(value, data, where) {
            console.log(value, data, where)
            if (!value) return true
            return data[this.defaultProps.label].indexOf(value) !== -1
        },
        // 懒加载回调
        lazyFn(node, resolve) {
            setTimeout(() => {
                resolve([
                    {
                        id: 71272,
                        pid: 7127,
                        name: 'debug22',
                        // disabled: true,
                        children: []
                    },
                    {
                        id: 71273,
                        pid: 7127,
                        name: 'debug11',
                        children: []
                    }
                ])
            }, 500)
        },
        // 切换模式 现有树形穿梭框模式transfer 和通讯录模式addressList
        changeMode() {
            if (this.mode == 'transfer') {
                this.mode = 'addressList'
            } else {
                this.mode = 'transfer'
            }
        },
        // 添加按钮
        add(fromData, toData, obj) {
            // 树形穿梭框模式transfer时，返回参数为左侧树移动后数据、右侧树移动后数据、移动的{keys,nodes,halfKeys,halfNodes}对象
            // 通讯录模式addressList时，返回参数为右侧收件人列表、右侧抄送人列表、右侧密送人列表
            console.log('fromData:', fromData)
            console.log('toData:', toData)
            console.log('obj:', obj)
        },
        // 移除按钮
        remove(fromData, toData, obj) {
            // 树形穿梭框模式transfer时，返回参数为左侧树移动后数据、右侧树移动后数据、移动的{keys,nodes,halfKeys,halfNodes}对象
            // 通讯录模式addressList时，返回参数为右侧收件人列表、右侧抄送人列表、右侧密送人列表
            console.log('fromData:', fromData)
            console.log('toData:', toData)
            console.log('obj:', obj)
        },
        newGroup() {
            this.addType()
        },
        // 左侧源数据选中事件
        leftCheckChange(e) {
            console.log(this.fromDataValue)
            if (this.fromDataValue.length === 0) {
                return this.$message.error('请先选择数据')
            }
            let arr = []
            this.fromDataValue.forEach(item1 => {
                this.fromData.forEach(item2 => {
                    if (item2.value === item1[0]) {
                        item2.children = item2.children.filter((item3, index) => {
                            if (item3.value === item1[1]) {
                                arr.push(item3)
                                return false
                            } else {
                                return true
                            }
                        })
                    }
                })
            })
            console.log(arr)
            console.log(this.fromData)
            if (e.value) {
                this.toData.forEach(item => {
                    if (item.value === e.value) {
                        item.children.push(...arr)
                    }
                })
            } else {
                this.toData.push(...arr)
            }
            // this.fromDataValue = []
            this.popoverVisible = false
        },
        // 右侧目标数据选中事件
        rightCheckChange() {
            console.log(this.toDataValue)
            if (this.toDataValue.length === 0) {
                return this.$message.error('请先选择数据')
            }
            let arr = []
            this.toDataValue.forEach(item1 => {
                if (item1.length === 1) {
                    this.toData = this.toData.filter(item2 => {
                        if (item2.value === item1[0]) {
                            arr.push(item2)
                            return false
                        } else {
                            return true
                        }
                    })
                } else {
                    this.toData.forEach(item2 => {
                        if (item2.value === item1[0]) {
                            item2.children = item2.children.filter((item3, index) => {
                                if (item3.value === item1[1]) {
                                    arr.push(item3)
                                    return false
                                } else {
                                    return true
                                }
                            })
                        }
                    })
                }
            })
            this.fromData.forEach(item1 => {
                arr.forEach(item2 => {
                    if (item2.pid === item1.value) {
                        item1.children.push(item2)
                    }
                })
            })
            // this.toDataValue = []
            this.$forceUpdate()
        },
        // 自定义节点 仅树形结构支持
        renderContent(h, { node, data, store }) {
            return (
                <span class="custom-tree-node">
                    <span>{node.label}</span>
                    <span>
                        <el-button size="mini" type="text" on-click={() => this.append(data)}>
                            Append
                        </el-button>
                        <el-button size="mini" type="text" on-click={() => this.remove(node, data)}>
                            Delete
                        </el-button>
                    </span>
                </span>
            )
        },
        // 标题自定义区点击事件
        handleTitleRight() {
            alert('标题自定义区点击事件')
        }
    }
}
</script>
<style lang="scss">
::v-deep .Cn-page .el-dialog__body .el-form {
    display: grid;
    padding-right: 30px;
    grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
    grid-gap: 10px 20px !important;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
}

::v-deep .hhgjk .el-dialog .el-dialog__body {
    max-height: 70vh !important;
    padding: 10px !important;
    // overflow-y: auto;
}

.title {
    padding: 40px 0;
}

.button-group {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 10px;
}

.hide-txt {
    overflow-x: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
    white-space: nowrap;
    -webkit-line-clamp: 1;
}

.box {
    display: flex;
    width: 1000px;
    height: 60vh;
    margin: 0 auto;
    text-align: left;

    .box-center {
        display: flex;
        align-items: center;
        width: 100px;
        padding-top: 20px;
        margin: 0 20px;
        flex-direction: column;
    }

    .box-right,
    .box-left {
        height: 100%;
        overflow: hidden;
        flex: 1;

        .el-cascader-menu__wrap {
            height: auto;
        }

        .el-cascader-panel {
            height: 100%;

            .el-cascader-menu__list {
                height: 100% !important;
            }
        }
    }

    .box-right {
        ::v-deep .el-cascader-node__label {
            padding-right: 0 !important;
        }

        ::v-deep .el-cascader-node {
            padding: 0 30px 0 20px;
        }
    }
}

.btn {
    padding: 5px 10px;
    background-color: #f5f7fa;
    border: 1px solid #ebeef5;
    outline: none;
}

.my-title-right {
    float: right;
    font-size: 12px;
    cursor: pointer;
}

wl-transfer .el-tree {
    // height: 50vh;
    display: inline-block !important;
    min-width: 100%;
    margin-bottom: 5px;
}

::v-deep .el-tree {
    position: relative;
    height: 22vh;
    overflow: auto;
    color: #000608;
    cursor: default;
    background: #f5f7fa;
}

::v-deep .wl-transfer .transfer-main {
    height: 50vh;
    padding: 0 10px 10px;
    overflow: auto;
    box-sizing: border-box;
}

::v-deep .wl-transfer .transfer-title {
    height: 40px;
    padding: 0 15px;
    margin-top: -2px;
    font-size: 16px;
    line-height: 40px;
    color: #333;
    background-color: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
}
</style>
