<!--系统字典，下级字典的添加查看，与删除-->
<template>
    <el-dialog
        top="6vh"
        title="下级字典项"
        width="1000px"
        :visible.sync="visible"
        append-to-body
        class="lower-dict"
        v-if="visible"
    >
        <el-row :gutter="10">
            <el-col :span="12">
                <div v-if="type == 'search'" class="head-content no-margin">
                    已选下级字典
                </div>
                <!-- @load="loadData" -->
                <ht-table
                    @load="loadData"
                    @row-click="rowClick"
                    :selectable="false"
                    highlight-current-row
                    :data="dictData"
                    :pageResult="pageResult"
                    :default-querys="defaultQuerys"
                    :default-sorter="[
                        {direction: 'DESC', property: 'code_'},
                        {direction: 'DESC', property: 'name_'},
                    ]"
                    :quick-search-props="type == 'search' ? '' : querySearch"
                    :show-custom-column="false"
                    :show-export="false"
                    :nopagination="type == 'search' ? true : false"
                    ref="htTable"
                >
                    <template>
                        <ht-table-column
                            prop="name"
                            label="名称"
                            :show-overflow-tooltip="true"
                        />
                        <ht-table-column
                            prop="code"
                            label="编码"
                            :show-overflow-tooltip="true"
                        />
                    </template>
                </ht-table>
            </el-col>
            <el-col :span="12">
                <div class="head-content">已选下级字典项</div>
                <!-- @selection-change="selectionChange" -->
                <el-table
                    ref="selectTable"
                    @select="selectionChange"
                    size="mini"
                    v-if="!load"
                    :data="selectItemData"
                    border
                    :height="selectItemTableHeight"
                    :max-height="selectItemTableHeight"
                >
                    <el-table-column
                        v-if="type == 'setting'"
                        header-align="center"
                        type="selection"
                        width="45"
                        align="center"
                        show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                        resizable
                        header-align="center"
                        align="center"
                        property="name"
                        label="成员名称"
                    ></el-table-column>
                    <el-table-column
                        resizable
                        property="value"
                        align="center"
                        header-align="center"
                        label="成员值"
                    ></el-table-column>
                    <el-table-column
                        v-if="type == 'search'"
                        align="center"
                        header-align="center"
                        label="操作"
                        resizable
                    >
                        <template slot-scope="scope">
                            <el-button
                                type="text"
                                @click="deleteDictItem(scope.row.id, 'search')"
                                >删除</el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>

        <div slot="footer" class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="saveLowerDict">确 定</el-button>
        </div>
    </el-dialog>
</template>
<script>
import portal from '@/api/portal'
export default {
    name: 'LowerDictModal',
    components: {},
    props: {
        lowerDictParams: {
            type: Object,
        },
    },
    data() {
        return {
            upperDictId: '', //设置级联的字典id
            dictItemId: '', // 设置级联的字典项id
            load: false,
            visible: false,
            type: '', // "setting" ,"search"
            defaultQuerys: [
                {
                    property: 'id_',
                    value: '',
                    operation: 'NOT_EQUAL',
                },
                {
                    property: 'flag_',
                    value: 1,
                    operation: 'EQUAL',
                },
            ],
            querySearch: [
                {
                    label: '名称',
                    prop: 'name_',
                },
                {
                    label: '编码',
                    prop: 'code_',
                },
            ],
            dictData: [],
            selectItemData: [],
            pageResult: {
                page: 1,
                pageSize: 20,
                total: 0,
            },
            selectItemTableHeight: 320,
            currentDictId: '', // 左侧当前选中字典的id值
            quickSearchPlaceholder: '请输入字典名称进行查询',
            sectionObj: {
                // key 是字典id 值是选中的字典项的id的数组
            },
        }
    },
    methods: {
        loadData(param, cb) {
            this.load = true
            if (this.type == 'search') {
                let param = this.qs.stringify({
                    detailId: this.dictItemId,
                })
                portal
                    .loadSetLowerDict(param)
                    .then((resp) => {
                        let response = resp
                        this.dictData = response
                        this.$nextTick(() => {
                            this.selectItemTableHeight = this.$refs.htTable.$refs.htTable.maxHeight
                        })
                        this.load = false
                    })
                    .finally(() => cb())
            } else {
                portal
                    .loadDictList(param)
                    .then((resp) => {
                        let response = resp
                        this.dictData = response.rows
                        this.$nextTick(() => {
                            this.selectItemTableHeight = this.$refs.htTable.$refs.htTable.maxHeight
                        })
                        this.load = false
                        this.pageResult = {
                            page: response.page,
                            pageSize: response.pageSize,
                            total: response.total,
                        }
                    })
                    .finally(() => cb())
            }
        },
        rowClick(row, column, event) {
            this.currentDictId = row.id
            console.log(row, column)
            this.$refs.htTable.$refs.htTable.toggleRowSelection(row)
            this.qs.stringify({id: row.id})

            if (this.type == 'search') {
                this.loadSetLowerDictItem()
            } else {
                let data = {
                    dictionaryId: row.id,
                    flag: 1,
                }
                portal.queryDictDetail(data).then((res) => {
                    console.log(res, 'res')
                    this.selectItemData = res
                    this.toggeRowSelection()
                })
            }
        },
        toggeRowSelection() {
            let selected = this.sectionObj[this.currentDictId]
            if (selected) {
                this.$nextTick(() => {
                    selected.forEach((row) => {
                        this.$refs.selectTable.toggleRowSelection(
                            this.selectItemData.find((item) => {
                                return row.id == item.id // 注意这里寻找的字段要唯一
                            }),
                            true
                        )
                    })
                })
            }
        },
        selectionChange(selection) {
            this.sectionObj[this.currentDictId] = selection
            console.log(selection, 'selection')
            console.log(this.sectionObj)
        },
        setCurrent(row) {
            this.$refs.singleTable.setCurrentRow(row)
        },
        quickSearch() {},
        open(row, type, upperDictId) {
            this.type = type
            this.defaultQuerys[0].value = upperDictId
            this.upperDictId = upperDictId
            this.dictItemId = row.id
            this.visible = true
            this.$nextTick(() => {
                this.$refs.htTable.load()
            })
        },
        close() {
            this.beforeClose()
            this.visible = false
        },
        handleClickRow(record) {
            return {
                on: {
                    click: async () => {
                        let keys = []
                        keys.push(record.id)
                        this.selectedRowKeys = keys
                        if (this.fromUpperDict.type == 'add') {
                            this.itemDataSource = await this.loadDictItem(
                                this.selectedRowKeys
                            )
                        } else {
                            this.itemDataSource = await this.loadAddedDictItem(
                                this.selectedRowKeys[0]
                            )
                        }
                    },
                },
            }
        },
        rowClassName() {
            return 'row-class-name'
        },
        beforeClose() {
            this.upperDictId = ''
            this.defaultQuerys[0].value = ''
            this.currentDictId = ''
            this.type = ''
            this.dictData = []
            this.selectItemData = []
            this.sectionObj = {}
        },
        // 保存下级字典
        saveLowerDict() {
            if (this.type == 'setting') {
                let ids = []
                Object.values(this.sectionObj).forEach((selections) => {
                    selections.forEach((item) => {
                        ids.push(item.id)
                    })
                })
                if(!ids.length){
                    this.$message.warning("请选择级联字典及对应字典项");
                    return
                }
                let params = this.qs.stringify({
                    detailId: this.dictItemId,
                    lowerDetailIds: ids.join(','),
                    lowerDictId: this.currentDictId,
                })
                portal
                    .saveDictLowerDetails(params)
                    .then(() => {
                        this.$message.success('字典级联设置成功')
                        this.beforeClose()
                        this.visible = false
                    })
                    .catch((err) => {
                        this.$message.success('字典级联设置失败')
                    })
            } else {
                this.close();
            }
        },
        // 查看
        loadSetLowerDictItem() {
            let data = this.qs.stringify({
                detailId: this.dictItemId,
                dictLowerId: this.currentDictId,
            })
            // 查看已设置下级字典项
            portal.loadSetLowerDictItem(data).then((res) => {
                console.log(res, 'res')
                this.selectItemData = res
            })
        },
        // 删除已设置的级联字典
        deleteDictItem(id) {
            let data = this.qs.stringify({
                detailId: this.dictItemId,
                lowerDetailIds: id,
            })
            // 查看已设置下级字典
            portal.delLowerDetails(data).then((res) => {
                this.loadSetLowerDictItem()
                this.$message.success('删除成功')
            })
        },
    },
}
</script>
<style lang="scss" scoped>
.lower-dict /deep/ .el-dialog__body {
    padding: 10px 20px;
}
.lower-dict /deep/ .el-table .el-table__row {
    cursor: pointer;
}
.head-content {
    margin-bottom: 15px;
    height: 32px;
    line-height: 32px;
    font-size: 14px;
    font-weight: bold;
}
.head-content.no-margin {
    margin-bottom: 0;
}
</style>