<template>
    <el-container id="commonRepository">
        <el-header :height="headerHeight">
            <el-col :span="24" style="position: relative;top: 10px;">
                <div style="display:inline-block;float:left;">
                    <awsui-button style="width: 100px;" class="button-general-color" type="primary" @click="add">添加流程</awsui-button>
                </div>
                <div style="display:inline-block;float:right;width:320px;padding-right: 20px;">
                    <el-input
                            placeholder="搜索"
                            prefix-icon="el-icon-search"
                            v-model="searchInput"
                            @input="searchRepository"
                            size="small"
                            clearable>
                    </el-input>
                </div>
            </el-col>
            <el-dialog
                    v-loading="dlgLoading"
                    title="添加常用流程"
                    :visible.sync="dialog.visible"
                    :modal-append-to-body=false
                    :close-on-click-modal=false
                    :close-on-press-escape=true
                    :before-close="handleCloseDlg"
                    @close="clearDlgData"
                    width="500px">
                <div v-loading="loading">
                    <div style="padding:10px;border:1px solid #e9e9e9">
                        <div style="height: 300px;">
                            <el-select
                                    style="width: 100%;"
                                    v-model="dialog.ws.value"
                                    filterable
                                    default-first-option
                                    size="small"
                                    placeholder="请选择资产库"
                                    @change="changeWs">
                                <el-option
                                        v-for="item in dialog.ws.options"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                            <div style="height: 268px;overflow: auto;">
                                <el-tree v-if="dialog.ws.value != ''"
                                         ref="repositoryTree"
                                         :props="dialog.tree.props"
                                         :default-checked-keys="dialog.tree.value"
                                         :expand-on-click-node=false
                                         :highlight-current=true
                                         @node-click="openNode"
                                         @node-expand="expandNode"
                                         @node-collapse="closeNode"
                                         @check-change="checkedNode"
                                         check-strictly
                                         show-checkbox
                                         node-key="versionId"
                                         lazy
                                         :load="loadNode">
                                    <span slot-scope="{node, data}">
                                      <i class="awsui-iconfont tree-content-icon tree-content-icon-padding" :style="{'color': node.data.icon.color}" v-html="node.data.icon.icon"></i>
                                      <span>{{node.data.name}}</span>
                                    </span>
                                </el-tree>
                            </div>
                        </div>
                    </div>

                </div>
                <span slot="footer" class="dialog-footer">
                    <awsui-button class="button-general-color" type="primary" @click="saveCommonData()">确定</awsui-button>
                    <awsui-button @click="closeDlg">取消</awsui-button>
                </span>
            </el-dialog>
        </el-header>
        <el-main>
            <div id="main" :style="{'cursor': 'move', 'height': mainHeight, 'width': '100%'}">
                <el-table
                        :height="mainHeight"
                        :data="data"
                        row-key="id"
                        style="width: 100%">
                    <el-table-column
                            prop="move"
                            label=""
                            align="center"
                            width="20">
                        <template slot-scope="scope">
                            <div class="operate-icon-display">
                                <p class="text-second-color">
                                    <i style="display: inline-block;cursor: pointer;" class="awsui-iconfont">&#xe785;</i>
                                </p>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="sort"
                            label="排序"
                            align="center"
                            width="80">
                    </el-table-column>
                    <el-table-column
                            prop="name"
                            label="名称"
                            :show-overflow-tooltip=true
                            width="400">
                    </el-table-column>
                    <el-table-column
                            prop="wsName"
                            label="关联资产库"
                            :show-overflow-tooltip=true>
                    </el-table-column>
                    <el-table-column
                            prop="opt"
                            label="操作"
                            align="center"
                            width="100">
                        <template slot-scope="scope">
                            <div class="operate-icon-display">
                                <p class="text-second-color">
                                    <i style="display: inline-block;cursor: pointer;" class="awsui-iconfont" @click="deleteCommonData(scope.row.id, scope.row.name)">&#58918;</i>
                                </p>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-main>
    </el-container>
</template>

<script>
    import Sortable from 'sortablejs';
    import awsuiAxios from "../../awsuiAxios";
    export default {
        name: "commonRepository",
        components: {Sortable},
        data() {
            return {
                headerHeight: '50px',
                mainHeight: (parseInt(this.$store.getters.getTopMainHeightFn) - 52) + 'px',
                searchInput: '',
                data: [],
                dataTemp: [],
                checkedData: [],
                dlgLoading: false,
                loading: false,
                dialog: {
                    visible: false,
                    ws: {
                        value: '',
                        options: []
                    },
                    tree: {
                        props: {
                            children: 'children',
                            label: 'label'
                        },
                        value: []
                    }
                }
            }
        },
        mounted() {
            // 火狐浏览器拖拽问题
            document.body.ondrop = function (event) {
                event.preventDefault();
                event.stopPropagation();
            }
            this.initData();
            this.rowDrop();
        },
        methods: {
            //行拖拽
            rowDrop() {
                const tbody = document.querySelector('.el-table__body-wrapper tbody')
                const _this = this;
                Sortable.create(tbody, {
                    onEnd({ newIndex, oldIndex }) {
                        const currRow = _this.data.splice(oldIndex, 1)[0]
                        _this.data.splice(newIndex, 0, currRow);
                        const resourceIds = [];
                        for (let i = 0; i < _this.data.length; i++) {
                            _this.data[i].sort = i+1;
                            resourceIds.push(_this.data[i].versionId);
                        }
                        // 保存
                        const params = {
                            url:'jd',
                            data:{
                                cmd: 'com.actionsoft.apps.coe.pal_publish_publishgroup_common_update_save',
                                resourceIds: JSON.stringify(resourceIds)
                            }
                        };
                        // 查询数据
                        awsuiAxios.post(params).then(function (ro) {
                            if(ro.result == 'ok') {
                                _this.$message({message: '移动成功',type: 'success'});
                            } else {
                                _this.$message.error(ro.msg);
                            }
                        }).catch(error=>{
                            console.log(error);
                        })
                    }
                })
            },
            initData() {// 初始化数据查询
                const that = this;
                const params = {
                    url:'jd',
                    data:{
                        cmd: 'com.actionsoft.apps.coe.pal_publish_publishgroup_common_list'
                    }
                };
                // 查询数据
                awsuiAxios.post(params).then(function (ro) {
                    if(ro.result == 'ok') {
                        const data = ro.data.data;
                        that.data = data;
                        that.dataTemp = JSON.parse(JSON.stringify(that.data));
                        that.checkedData = ro.data.checkedData;
                        // 存取
                    } else {
                        that.$message(ro.msg);
                    }
                }).catch(error=>{
                    console.log(error);
                })
            },
            searchRepository() {// 搜索
                if (this.searchInput && this.searchInput.trim() != '') {// 根据条件搜索
                    const data = [];
                    for (let i = 0; i < this.dataTemp.length; i++) {
                        if (this.dataTemp[i].name.indexOf(this.searchInput) > -1
                            || this.dataTemp[i].wsName.indexOf(this.searchInput) > -1) {
                            data.push(this.dataTemp[i]);
                        }
                    }
                    this.data = data;
                } else {// 显示全部
                    this.data = this.dataTemp;
                }
            },
            add() {// 新增常用流程
                this.dialog.visible = true;
                this.loading = true;
                const that = this;
                const params = {
                    url:'jd',
                    data:{
                        cmd: 'com.actionsoft.apps.coe.pal_publish_publishgroup_create_data_query'
                    }
                };
                // 查询数据
                awsuiAxios.post(params).then(function (ro) {
                    if(ro.result == 'ok') {
                        const data = ro.data;
                        that.dialog.tree.value = (that.checkedData[data.wsId] == undefined ? [] : that.checkedData[data.wsId]);
                        that.dialog.ws.value = data.wsId;
                        that.dialog.ws.options = data.wsArr;
                    } else {
                        that.$message(ro.msg);
                    }
                    that.loading = false;
                }).catch(error=>{
                    console.log(error);
                    that.loading = false;
                })
            },
            deleteCommonData(id, name) {// 删除用户组
                const that = this;
                that.$confirm('确定要删除吗？', '提示', {
                    confirmButtonText: '确定',
                    confirmButtonClass: 'button-general-color',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const params = {
                        url:'jd',
                        data:{
                            cmd: 'com.actionsoft.apps.coe.pal_publish_publishgroup_common_data_delete',
                            ids: id
                        }
                    };
                    awsuiAxios.post(params).then(function (ro) {
                        if(ro.result == 'ok') {
                            that.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            that.initData();
                        } else {
                            that.$message(ro.msg);
                        }
                    }).catch(error=>{
                        console.log(error);
                    })
                }).catch(() => {
                });
            },
            clearDlgData() {// 清除dialog数据
                this.dialog.ws.value = '';
                this.dialog.ws.options = [];
                this.dialog.tree.data = [];
                this.dialog.tree.value = [];
            },
            closeDlg() {// 关闭新建/修改窗口
                this.dialog.visible = false;
            },
            handleCloseDlg(done) {
                this.closeDlg();
                done();
            },
            saveCommonData() {// 保存drawer结果
                const that = this;
                // 数据权限
                const wsId = that.dialog.ws.value;
                const repositorys = that.dialog.tree.value;
                // 保存
                that.dlgLoading = true;
                const params = {
                    url:'jd',
                    data:{
                        cmd: 'com.actionsoft.apps.coe.pal_publish_publishgroup_common_create_save',
                        wsId: wsId,
                        resourceIds: repositorys.join(",")
                    }
                };
                awsuiAxios.post(params).then(function (ro) {
                    if(ro.result == 'ok') {
                        that.dlgLoading = false;
                        that.clearDlgData();
                        that.closeDlg();
                        that.$message({
                            message: '保存成功',
                            type: 'success'
                        });
                        that.initData();
                    } else {
                        that.$message.error('保存失败');
                        that.dlgLoading = false;
                    }
                }).catch(error=>{
                    console.log(error);
                    that.dlgLoading = false;
                })
            },
            /******新增常用流程部分*******/
            changeWs(targetWsId) {// 变更资产库
                const that = this;
                that.dialog.ws.value = '';
                that.dialog.tree.value = (that.checkedData[targetWsId] == undefined ? [] : that.checkedData[targetWsId]);
                that.$nextTick(function () {
                    that.dialog.ws.value = targetWsId;
                })
            },
            openNode(obj, node, tree) {// 点击数

            },
            loadNode(node, resolve) {
                const that = this;
                const data = {
                    url:'jd',
                    data:{
                    }
                };
                data.data.wsId = that.dialog.ws.value;
                data.data.teamId = '';
                data.data.cmd = 'com.actionsoft.apps.coe.pal_processlevel_tree_data';
                if (node.level === 0) {
                    // 获取根目录
                    data.data.pid = '';
                } else {
                    // 获取其他目录
                    data.data.pid = node.data.id;
                }
                // 查询数据
                awsuiAxios.post(data).then(function (ro) {
                    for (let i = 0; i < ro.data.length; i++) {
                        if (ro.data[i].id.length < 36) {
                            ro.data[i].disabled = true;
                        }
                    }
                    resolve(ro.data);
                    if (node.level == 0 && ro.data.length > 0) {
                        const tree = that.$refs.repositoryTree;
                        tree.getNode(ro.data[0].id).expand();
                        setTimeout(function(){
                            const childNode = tree.getNode(ro.data[0].id).childNodes[0];
                            if (childNode != null) {
                                childNode.expand();
                            }
                        }, 500);
                    }
                }).catch(error=>{
                    console.log(error);
                })
            },
            expandNode(obj, node, tree) {// 展开节点

            },
            closeNode(obj, node, tree) {// 关闭时清空，下次展开重新请求动态加载
                node.childNodes = [];
                node.loaded = false;
            },
            checkedNode(data, checked, subChecked) {// 节点选中事件
                // 获取所有子节点
                const that = this;
                const params = {
                    url:'jd',
                    data:{
                        cmd: 'com.actionsoft.apps.coe.pal_publish_publishgroup_repository_data_query',
                        wsId: that.dialog.ws.value,
                        pid: data.id,
                    }
                };
                awsuiAxios.post(params).then(function (ro) {
                    const childVerIds = ro.data;
                    const currVerId = data.versionId;
                    if (checked) {// 选中
                        const checkedVerIds = that.dialog.tree.value;
                        if (checkedVerIds.indexOf(currVerId) == -1) {
                            checkedVerIds.push(currVerId);
                        }
                        for (let i = 0; i < childVerIds.length; i++) {
                            if (checkedVerIds.indexOf(childVerIds[i]) == -1) {
                                checkedVerIds.push(childVerIds[i]);
                            }
                        }
                        that.$refs.repositoryTree.setCheckedKeys(checkedVerIds);
                    } else {// 取消选中
                        const checkedVerIds = that.dialog.tree.value;
                        const tempArr = [];
                        for (let i = 0; i < checkedVerIds.length; i++) {
                            if (checkedVerIds[i] != currVerId && childVerIds.indexOf(checkedVerIds[i]) == -1) {
                                tempArr.push(checkedVerIds[i]);
                            }
                        }
                        that.dialog.tree.value = tempArr;
                        that.$refs.repositoryTree.setCheckedKeys([]);
                    }
                }).catch(error=>{
                    console.log(error);
                })
            }
            /********新增常用流程部分*********/

        },
        computed: {
            listenTopMainHeight() {
                return this.$store.getters.getTopMainHeightFn;
            }
        },
        watch: {
            listenTopMainHeight: function (newd, old) {
                this.mainHeight = (parseInt(this.$store.getters.getTopMainHeightFn) - parseInt(this.headerHeight)) -2 + 'px';
            }
        }
    }
</script>

<style scoped>
    #commonRepository >>> .el-dialog__body {
        padding: 0px 20px;
    }
    #commonRepository >>> .el-main {
        padding: 0px 20px;
    }
    #commonRepository >>> .el-footer {
        padding: 0;
    }
    #commonRepository >>> .el-table__row .operate-icon-display{
        display: none;
    }
    #commonRepository >>> .el-table__row:hover .operate-icon-display{
        display: inline-block;
    }
</style>