<template>
    <div>
        <div class="page">
            <div class="btn-wrap">
                <template v-if="sorting">
                    <el-button class="action-btn" type="primary" round @click="cancelSort">取消</el-button>
                    <el-button class="action-btn" type="primary" round @click="sortSubmit">保存</el-button>
                </template>
                <template v-if="!sorting">
                    <el-button v-auth="'栏目管理:更改排序'" class="action-btn" type="primary" round @click="openSort">更改排序
                    </el-button>
                    <el-button v-auth="'栏目管理:添加栏目'" class="action-btn" type="primary" round @click="handleColumn(false, 0, 0)">添加栏目
                    </el-button>
                </template>
            </div>
            <div class="page-content" style="padding-top: 24px; margin-top: 24px">
                <div class="el-table">
                    <div class="list">
                        <div class="thead">
                            <span>栏目名称</span>
                            <span><em :class="{hide: sorting}" style="font-style: normal">操作</em></span>
                        </div>
                    </div>
                    <el-tree :data="listData" node-key="id" default-expand-all :draggable="sorting" :allow-drop="allowDrop">
                        <span class="custom-tree-node" slot-scope="{ node, data }">
                            <span class="name">{{ data.name }}</span>
                            <span class="action" v-show="!sorting">
                                <el-button v-auth="'栏目管理:编辑'" type="text" @click.stop="handleColumn(data)">编辑</el-button>
                                <el-divider v-auth="'栏目管理:编辑'" direction="vertical"></el-divider>
                                <template v-if="node.level < 4">
                                    <el-button v-auth="'栏目管理:新增'" type="text" @click.stop="handleColumn(data, data.id, data.level + 1)">新增</el-button>
                                    <el-divider v-auth="'栏目管理:新增'" direction="vertical"></el-divider>
                                </template>
                                <el-button v-auth="'栏目管理:删除'" type="text" @click.stop="delData(data)">删除</el-button>
                            </span>
                        </span>
                    </el-tree>
                </div>
            </div>
        </div>

        <el-dialog :title="!curRow.id ? '添加栏目' : '编辑栏目'" :visible.sync="columnVisible" width="400px"
                   :close-on-click-modal="false" @close="closeColumn">
            <el-form>
                <el-form-item>
                    <el-input placeholder="栏目名称" v-model="curRow.name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="columnVisible = false">取 消</el-button>
                <el-button type="primary" @click="columnSubmit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import util from "@/libs/util";
import Setting from '@/setting'
export default {
    name: "columnManage",
    data() {
        return {
            activeName: "first",
            tabs: {
                first: "栏目管理"
            },
            name: this.$store.state.name,
            originalList: [],
            listData: [],
            multipleSelection: [],
            pageNo: 1,
            pageSize: 10,
            total: 0,
            columnVisible: false,
            curRow: {},
            sortObj: null,
            sorting: false,
            parentId: '',
            isAddType: false,
            defaultProps: {
                label: "name"
            },
            level: 0
        };
    },
    mounted() {
        this.getData();
    },
    beforeRouteLeave(to, from, next) {
        if (JSON.stringify(this.originalList) !== JSON.stringify(this.listData)) {
            this.$confirm("确定返回？排序尚未保存。", "提示", {
                type: "warning"
            })
                .then(() => {
                    next();
                })
                .catch(() => {
                });
        } else {
            next();
        }
    },
    methods: {
        getData() {
            this.$get(this.api.queryAllColumns, {
                platformId: Setting.platformId,
                page: this.pageNo,
                size: this.pageSize
            }).then(({ columnTree }) => {
                this.listData = columnTree
                this.originalList = JSON.parse(JSON.stringify(this.listData));
                this.total = columnTree.length
            }).catch(res => {
            });
        },
        delData(row) {
            this.$confirm("此删除操作不可逆，是否确认删除选中项？", "提示", {
                type: "warning"
            })
                .then(() => {
                    this.$del(`${this.api.deleteColumn}/${row.id}`).then(res => {
                        util.successMsg("删除成功");
                        this.getData();
                    }).catch(res => {
                    });
                })
                .catch(() => {
                });
        },
        handleColumn(row, parentId, level) {
          this.columnVisible = true
          if (row) {
            this.curRow = JSON.parse(JSON.stringify(row))
          }
          if (typeof parentId === 'number') {
            this.curRow = {
              parentId,
              level,
              name: '',
              platformId: Setting.platformId
            }
          }
        },
        // 递归处理list
        handleList(data, parent = {}) {
          data.map((n, i) => {
            n.parentId = parent.id || 0
            n.level = this.level
            n.sort = i
            if (n.children.length) {
              this.level++
              this.handleList(n.children, n)
            } else {
              this.level = 0
            }
          })
          this.level++
        },
        sortSubmit() {
            this.level = 0
            let list = JSON.parse(JSON.stringify(this.listData))
            this.handleList(list)
            this.$post(this.api.columnReorder, {
              columnTree: list
            }).then(res => {
                util.successMsg("保存成功");
                this.sorting = false;
                this.getData();
            }).catch(res => {
            });
        },
        columnSubmit() {
          const row = this.curRow
          if (!row.name) return util.warningMsg("请填写栏目名称");
          if (this.curRow.id) {
              this.$put(this.api.editColumn, row).then(res => {
                  util.successMsg("修改成功");
                  this.columnVisible = false;
                  this.getData();
              }).catch(res => {
              });
          } else {
              this.$post(this.api.addColumn, row).then(res => {
                  util.successMsg("添加成功");
                  this.columnVisible = false;
                  this.getData();
              }).catch(res => {
              });
          }
        },
        cancelSort() {
            this.sorting = false;
            this.listData = JSON.parse(JSON.stringify(this.originalList));
            this.sortObj.destroy();
        },
        openSort() {
            this.sorting = true;
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        handleCurrentChange(val) {
            this.pageNo = val;
            this.getData();
        },
        closeColumn() {
          this.curRow = {}
        },
        allowDrop(draggingNode, dropNode, type) {
            console.log("🚀 ~ file: index.vue ~ line 207 ~ allowDrop ~ draggingNode, dropNode, type", draggingNode, dropNode.level, type)
            if (dropNode.level == 4 && draggingNode.childNodes.length == 0) {
                return type !== "inner";
            } else if ((draggingNode.childNodes.length > 0 && dropNode.level == 4) || (draggingNode.childNodes.length > 0 && type == "inner")) {
                return false;
            } else {
                return true;
            }
        }
    }
};
</script>

<style lang="scss" scoped>
.btn-wrap {
    position: absolute;
    top: 15px;
    right: 15px;
}

.list {
    .thead {
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: rgba(0, 0, 0, 0.04) !important;

        span {
            padding: 0.75rem 0.625rem;
            text-align: center;
            font-size: 14px;
            color: rgba(0, 0, 0, 0.85);
            font-weight: normal;
            box-sizing: border-box;

            &:first-child {
                padding-left: 23.5vw;
                @media(max-width: 1270px) {
                    padding-left: 25.5%;
                }
            }

            &:last-child {
                width: 16%;
            }
        }
    }
}

/deep/ .el-tree {
    .el-tree-node__expand-icon {
        margin-left: 22.5vw;
        @media(max-width: 1270px) {
            margin-left: 23.5%;
        }
    }

    .el-tree-node__content {
        padding: 20px;
        border-bottom: 0.0625rem solid #EBEEF5;
    }
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;

    .name {
        line-height: 44px;
    }

    .action {
        width: 8.5vw;
        text-align: left;
        @media(max-width: 1270px) {
            width: 16%;
        }
    }
}

.hide {
    opacity: 0;
}
</style>