<template>
    <ap-container>
        <ap-aside margin="1111">
            <ap-aside-tree :options.sync="treeOptions">
                <span slot="tree" slot-scope="scope" style="width: 100%">
                     <div class="abap-tree-node-left ap-ellipse">
                        <span v-if="scope.data.fdType == 1" style="color: #1890ff;">{{ scope.data.fdName }}</span>
                        <span v-else>{{ scope.data.fdName }}</span>
                    </div>
                    <div style="font-size: 12px;">{{ scope.data.fdDesc }}</div>
                </span>
            </ap-aside-tree>
        </ap-aside>
        <ap-split-panel></ap-split-panel>
        <ap-container>
            <ap-aside margin="1110" width="45%">
                <div class="flex-justify-start" style="height: 100%;">
                    <div style="width: 48%;height: 100%" >
                        <sap-table-field ref="tableFieldTreeRef" :options.sync="fieldTreeOptions"></sap-table-field>
                    </div>
                    <div style="width: 3%;"></div>
                    <div class="flex-1" style="height: 100%;" >
                        <sap-table-field ref="linkTableFieldTreeRef" :options.sync="linkFieldTreeOptions"></sap-table-field>
                    </div>
                </div>
            </ap-aside>
            <ap-main margin="1110" class="flex-col">
                <div style="height: 50%">
                    <ap-table ref="tAbapTableLinkRef" :options.sync="tAbapTableLinkOpt"></ap-table>
                </div>
                <div class="flex-1" style="border-top:1px solid #e9ecf1;margin-top: 5px;">
                    <ap-table ref="tAbapTableLinkConditionRef" :options.sync="tAbapTableLinkConditionOpt"></ap-table>
                </div>
            </ap-main>
        </ap-container>
    </ap-container>
</template>

<script>
import SapTable from './../components/SapTable'
import SapTableField from './../components/SapTableField'

export default {
    name: 'AbapTableLink',
    components: {
        SapTable,
        SapTableField
    },
    data() {
        let tableLinkCols = [
            {
                prop: 'fdTable',
                label: '关联表',
                type: 'select',
                selectOptionsKey: {label: "fdDesc", value: "fdName"},
                selectOptionsRemote: 'tableList',
                edit: false
            }, {
                prop: 'fdType',
                label: '连接方式',
                type: 'select',
                width: 100,
                align: "center",
                selectOptions: [{label: "左连接", value: 1}, {label: "右连接", value: 2},
                    {label: "内连接", value: 3}, {label: "全连接", value: 4}],
                rules: [{required: true, message: "必填", trigger: "blur", type: 'number',}]
            }, {
                prop: 'fdRelation',
                label: '关系',
                type: 'select',
                width: 100,
                align: "center",
                selectOptions: [{label: "1:1", value: "1:1"},{label: "1:n", value: "1:n"},
                    {label: "n:1", value: "n:1"},{label: "n:n", value: "n:n"}],
                rules: [{required: true, message: "必填", trigger: "blur"}],
                help: "左侧树选择表:当前表格的表"
            }, {
                prop: 'fdSort',
                label: '排序',
                type: 'input',
                width: 80,
            },
        ];
        let tableLinkOpt = {
            title: "表连接",
            columns: tableLinkCols,
            editPk: "fdId,fdKey,fdTable", //默认fdId
            deletePk: "fdKey", // 根据fdKey批量删除
            dataUrl: "/apd/abap/TAbapTableLink/getTAbapTableLinkGridList",
            saveUrl: "/apd/abap/TAbapTableLink/saveTAbapTableLinkGridData",
            deleteUrl: "/apd/abap/TAbapTableLink/deleteTAbapTableLinkGridData",
            toolbarBtn: ["add", "edit", "del", "save"],
            initData: false, // 默认false
            multiSelect: false,
            pagination: {pageSizes: [1000], pageSize: 1000},
            selectionChangeEvent: (row, column, event) => {
                if (row != null && row.length > 0) {
                    this.selectedLinkTableKey = row[0].fdKey;
                    this.selectedLinkTable = row[0].fdTable;
                } else {
                    this.selectedLinkTableKey = "";
                    this.selectedLinkTable = "";
                    this.selectedLinkField = "";
                }
                this.linkFieldTreeOptions.selectedTable =  this.selectedLinkTable;
                this.tAbapTableLinkOpt.title = "表连接 " + this.selectedTable + " ## "+ this.selectedLinkTable;
                this.tAbapTableLinkConditionOpt.title = "连接条件 " + this.selectedLinkTable;
                this.$refs.linkTableFieldTreeRef.refresh();

                this.$refs.tAbapTableLinkConditionRef.refresh();
            },
            params: () => {
                return {tableName: this.selectedTable}
            }
        };

        let tableLinkConditionCols = [
            {
                prop: 'fdCondition',
                label: '条件',
                type: 'input',
                help: '表名参数格式：【#表名#】',
                html: this.renderLinkCondition
            }, {
                prop: 'fdRemark',
                label: '备注',
                type: 'input',
                width: 120,
            }, {
                prop: 'fdSort',
                label: '排序',
                type: 'input',
                width: 80,
            }
        ];
        let tableLinkConditionOpt = {
            title: "连接条件",
            columns: tableLinkConditionCols,
            editPk: "fdId", //默认fdId
            deletePk: "fdId", // 默认fdId
            dataUrl: "/apd/abap/TAbapTableLinkCondition/getTAbapTableLinkConditionGridList",
            saveUrl: "/apd/abap/TAbapTableLinkCondition/saveTAbapTableLinkConditionGridData",
            deleteUrl: "/apd/abap/TAbapTableLinkCondition/deleteTAbapTableLinkConditionGridData",
            pagination: {pageSizes: [1000], pageSize: 1000},
            toolbarBtn: [{btnType: "primary", text: "选中添加", icon: "el-icon-finished", onClick: this.addLinkCondition},
                "separator",
                {btnType: "primary", text: "猜一猜", icon: "el-icon-transfer", onClick: this.guessLinkCondition},
                "separator",
                "add", "edit", "del", "refresh", "save"],
            initData: false, // 默认false
            addDefaultObj: () => {
                return {fdKey: this.selectedLinkTableKey}
            },
            params: () => {
                return {key: this.selectedLinkTableKey}
            }
        };
        return {
            // ----- 左侧树 -----
            treeOptions: this.getTreeOption(),
            selectedTable: "",
            tableFunction: "",
            tableSapText: "",
            // ----- 中间 -----
            fieldTreeOptions: this.getFieldTreeOptions(),
            selectedField: "",
            linkFieldTreeOptions: this.getLinkFieldTreeOptions(),
            selectedLinkField: "",
            // ----- 右侧 -----
            selectedLinkTable: "",
            selectedLinkTableKey: "",
            tAbapTableLinkOpt: tableLinkOpt,
            tAbapTableLinkConditionOpt: tableLinkConditionOpt,
            selectedSapTable: {tableName: "", fieldName: ""}
        }
    },
    methods: {
        // 左侧树：配置
        getTreeOption() {
            let treeOptions = {
                title: "SAP常用表",
                showCheckbox: false,
                defaultExpandAll: false,
                showTitle: false,
                indent: 0,
                onClick: (data, node, comp) => {
                    if (data.fdType != 2) {
                        return
                    }
                    this.resetTableInfo();
                    this.tAbapTableLinkOpt.title = "表连接 " + data.fdName;
                    this.tableFunction = data.fdFunction;
                    this.selectedTable = data.fdName;
                    this.fieldTreeOptions.selectedTable = data.fdName;
                    this.$refs.tableFieldTreeRef.refresh();

                    this.$refs.tAbapTableLinkRef.refresh();
                    this.$refs.tAbapTableLinkConditionRef.refresh();
                },
                loadOptions: {
                    url: "/apd/abap/AbapTable/getTAbapTableList",
                    treeKey: {
                        idKey: "fdId",
                        parentKey: "fdParentId",
                        childrenKey: "children",
                        label: "fdName"
                    },
                    success: (response) => {

                    },
                }
            };

            return treeOptions;
        },
        resetTableInfo() {
            this.tableSapText = "";
            this.tableFunction = "";
            this.selectedTable = "";
            this.selectedLinkTableKey = "";
            // this.tAbapTableFieldTable.title = "字段列表";
        },
        getFieldTreeOptions(){
            return {
                selectedTable: this.selectedTable,
                clickEvent: (data) => {
                    this.selectedField = data.fieldName;
                },
            }
        },
        getLinkFieldTreeOptions(){
            return {
                selectedTable: "",
                clickEvent: (data) => {
                    this.selectedLinkField = data.fieldName;
                },
            }
        },
        renderLinkConditionItem(value, table , fieldList){
            for (let i = 0; i < fieldList.length; i++) {
                let str = `#${table}#.${fieldList[i].fieldName}`;
                if (value.indexOf(str) > -1) {
                    // 排除字段前缀一样
                    if (new RegExp(str + "[a-zA-Z]").test(value)) {
                        continue;
                    }
                    let strHtml = `<span style="color:#909399;">#${table}#.</span><span style="color:#ffba00;">${fieldList[i].fieldName}</span>`;
                    value = value.replaceAll(str, strHtml)
                }
            }
            return value;
        },
        renderLinkConditionDescItem(value, table , fieldList){
            for (let i = 0; i < fieldList.length; i++) {
                let str = `#${table}#.${fieldList[i].fieldName}`;
                if (value.indexOf(str) > -1) {
                    // 排除字段前缀一样
                    if (new RegExp(str + "[a-zA-Z]").test(value)) {
                        continue;
                    }

                    let fdDesc = fieldList[i].fdDesc;
                    let desc = fdDesc == "" || fdDesc == null ? fieldList[i].text : fdDesc;
                    let descStrHtml = `${table}.${desc}`;
                    value = value.replaceAll(str, descStrHtml)
                }
            }
            return value;
        },
        renderLinkCondition(value, row){
            let desc = value;
            value = this.renderLinkConditionItem(value, this.selectedTable, this.$refs.tableFieldTreeRef.getData());
            value = this.renderLinkConditionItem(value, this.selectedLinkTable, this.$refs.linkTableFieldTreeRef.getData());
            value = `<span>${value}</span>`

            desc = this.renderLinkConditionDescItem(desc, this.selectedTable, this.$refs.tableFieldTreeRef.getData());
            desc = this.renderLinkConditionDescItem(desc, this.selectedLinkTable, this.$refs.linkTableFieldTreeRef.getData());
            desc = `<span style="color:#a8d1f7;">${desc}</span>`
            return value + "<br>" + desc;
        },
        getConditionStr(tableField, linkTableField){
            // 按表名排序：小的在前
            if (this.selectedTable > this.selectedLinkTable) {
                return `#${this.selectedLinkTable}#.${linkTableField} = #${this.selectedTable}#.${tableField}`
            } else {
                return `#${this.selectedTable}#.${tableField} = #${this.selectedLinkTable}#.${linkTableField}`
            }

        },
        addLinkCondition(){
            if (this.selectedTable == '' || this.selectedField == '' || this.selectedLinkTable == '' || this.selectedLinkField == '') {
                this.$message.error("请选择需要关联的字段");
                return;
            }

            let conditionStr = this.getConditionStr(this.selectedField, this.selectedLinkField);
            let row = {
                fdCondition: conditionStr,
                fdKey: this.selectedLinkTableKey
            }
            this.$refs.tAbapTableLinkConditionRef.toggleAddRow(row);
        },
        guessLinkCondition(){
            let tableFieldList = this.$refs.tableFieldTreeRef.getData();
            let linkTableFieldList = this.$refs.linkTableFieldTreeRef.getData();
            if (tableFieldList == null || tableFieldList.length < 1
                || linkTableFieldList == null || linkTableFieldList.length < 1) {
                this.$message.error("字段列表为空！匹配失败")
                return;
            }

            let addRows = [];

            for (let i = 0; i < tableFieldList.length; i++) {
                let fieldName = tableFieldList[i].fieldName;
                // 1、一样字段是否匹配
                let isMatch = false;
                for (let j = 0; j < linkTableFieldList.length; j++) {
                    if (fieldName == linkTableFieldList[j].fieldName) {
                        addRows.push({
                            fdCondition: this.getConditionStr(fieldName, fieldName),
                            fdKey: this.selectedLinkTableKey
                        });
                        isMatch = true;
                        break
                    }
                }
                if (isMatch) {
                    continue;
                }

                // 2、添加z匹配
                let zFlag = fieldName.startsWith("Z");
                if (zFlag) {
                    for (let m = 0; m < linkTableFieldList.length; m++) {
                        let linkFieldName = linkTableFieldList[m].fieldName;
                        if (fieldName == ("Z" + linkFieldName)) {
                            addRows.push({
                                fdCondition: this.getConditionStr(fieldName, linkFieldName),
                                fdKey: this.selectedLinkTableKey
                            });
                            isMatch = true;
                            break
                        }
                    }
                } else {
                    for (let n = 0; n < linkTableFieldList.length; n++) {
                        let linkFieldName = linkTableFieldList[n].fieldName;
                        if (("Z" +fieldName) == linkFieldName) {
                            addRows.push({
                                fdCondition: this.getConditionStr(fieldName, linkFieldName),
                                fdKey: this.selectedLinkTableKey
                            });
                            isMatch = true;
                            break
                        }
                    }
                }
            }

            let tableDatas = this.$refs.tAbapTableLinkConditionRef.getData();
            // 批量添加行
            for (let k = addRows.length -1; k > -1; k--) {
                let addRow = addRows[k];

                let hasAdd = false;
                for (let l = 0; l < tableDatas.length; l++) {
                    // 判断是否已经添加：剔除空格
                    if (tableDatas[l].fdCondition.replaceAll(" ", "")
                        == addRow.fdCondition.replaceAll(" ", "")) {
                        hasAdd = true;
                        break
                    }
                }
                if (!hasAdd) {
                    this.$refs.tAbapTableLinkConditionRef.toggleAddRow(addRow);
                }
            }
        }

    }
}
</script>

<style scoped>
.abap-tree-node-left {
    font-size: 13px;
    width: 50%;
    float: left;
}
</style>
