<template>
<div class="rebate-setting-pannel">
    <div class="rules">
        <div style="width: 100%;text-align: center;font-size: 16px;margin-bottom: 10px;height: 28px;">{{ t('partner.rebateRule') }}</div>
        <el-table :data="rebateRuleList" :show-header="false" class="rule-item" @current-change="handleRowClick" row-class-name="rule-item" highlight-current-row >
            <el-table-column prop="rebate_name" width="345" ></el-table-column>
            <el-table-column width="45"  class-name="icon-cell">
                <template #default="scope">
                    <el-icon style="font-size: 20px;"><ArrowRight /></el-icon>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="hierarchy">
        <div v-if="allJunior && allJunior.power == 'all' && !allJunior.tree.length" 
            style="display: flex;flex-direction: column;align-items: center;justify-content: center;font-size: 26px;color: black;height: 100%;">
            <svg-icon icon-class="error" style="font-size: 60px;margin-bottom: 30px;" />
            <span style="font-weight: 700;">{{ t('partner.noIbChoose') }}</span>
        </div>
        <div v-else-if="allJunior" style="width: 100%;height: 100%;padding: 0 20px;">
            <div style="height: 28px;margin-bottom: 10px;" v-if="allJunior && allJunior.power == 'children'">
                {{ t('partner.childrenMaxHierarchy') }}<span style="font-size: 18px;">{{ selectedRow.hierarchy_value }}</span>
            </div>
            <div style="height: 40px;margin-bottom: 10px;position: relative;" v-if="allJunior && allJunior.power == 'all'" >
                <el-input v-model="searchValue" style="width: 600px" size="large" >
                    <template #prepend>
                        <el-select v-model="searchType" placeholder="Select" style="min-width: 115px" size="large" >
                            <el-option :label="t('partner.account')" value="n" />
                            <el-option :label="t('partner.value')" value="v" />
                        </el-select>
                    </template>
                    <template #append>
                        {{ searchResult?searchResult.length:0 }}
                    </template>
                </el-input>
                <el-button size="large" icon="Search" style="margin-left: 10px;" @click="query" ></el-button>
                <el-button v-if="searchResult" @click="searchResult = null" >{{ t('form.collapse') }}</el-button>
                <div style="position: absolute;left: 0;top: 40px;width: 600px;height: 500px;z-index: 999;background-color: #fff;" v-if="searchResult">
                    <el-table-v2 :columns="[{key: 'text', dataKey: 'id'}]" :data="searchResult" :width="600" :height="500" :header-height="0" :row-event-handlers="handleRow" >
                        <template #row="{ rowData }" >
                            <div style="padding: 0 10px;width: 100%;cursor: pointer;" >{{ rowData.text }}</div>
                        </template>
                    </el-table-v2>
                </div>
            </div>
            <div style="height: 420px;" v-show="searchResult == null || !searchResult.length" >
                <BaseTree ref="tree" class="mtl-tree" v-model="treeNodes" treeLine style="height: 420px;overflow-y: auto;" >
                    <template #default="{ node, stat }">
                        <svg-icon v-if="stat.open && stat.children.length" class="tree-node-icon" icon-class="jian" @click.native="stat.open = false" />
                        <svg-icon v-else-if="!stat.open && stat.children.length" class="tree-node-icon" icon-class="jia" @click.native="stat.open = true" />
                        <div class="tree-node" :ref="'refN'+node.id" >
                            <span class="level">{{ stat.level }}</span>
                            <span class="label">{{ node.text }}</span>
                            <el-input-number 
                            :class="{ 't-input-error': (stat.level==1?selectedRow.hierarchy_value:stat.parent.data.val)<node.val && !node.readonly }"
                            style="width: 60px;margin-left: 10px;" 
                            v-model="node.val" 
                            :min="0" :max="stat.level==1?selectedRow.hierarchy_value:stat.parent.data.val" 
                            :controls="false" 
                            :readonly="node.readonly" 
                            :disabled="node.readonly" />
                            <span class="diff" :class="{'error-diff': (stat.parent.data.val?stat.parent.data.val:0) < node.val}" v-if="stat.level!=1" >{{ t('partner.difference', {n: (stat.parent.data.val?stat.parent.data.val:0) - (node.val?node.val:0)}) }}</span>
                        </div>
                    </template>
                </BaseTree>
            </div>
            <div style="width: 100%;height: 70px;display: flex;justify-content: center;align-items: flex-end;">
                <el-button class="save-btn" size="large" type="primary" @click="save" >{{ t('form.save') }}</el-button>
            </div>
        </div>
    </div>
</div>

</template>

<script setup>
import { queryRebate, getAllJunior, saveRebateSet } from "@/api/ib"
import { useLocale } from 'element-plus'
import { isEmpty, returnFloat } from '@/utils/htfx'
import { BaseTree, walkTreeData  } from '@he-tree/vue'
import '@he-tree/vue/style/default.css'
import '@he-tree/vue/style/material-design.css'
import { nextTick } from "vue"

const { t } = useLocale()
const { proxy } = getCurrentInstance();
const rebateRuleList = ref([])
const allJunior = ref(null)
const treeNodes = ref([])
const selectedRow = ref(null)
const bigAgentId = ref(null)

const searchType = ref('n')
const searchValue = ref(null)
const searchResult = ref(null)

function loadData() {
    queryRebate().then(resp => {
        rebateRuleList.value = resp.data
    })
}

function handleRowClick(currentRow) {
    treeNodes.value = []
    getAllJunior({rebate_id: currentRow.id}).then(resp => {
        allJunior.value = resp.data
        if (resp.data.power === 'all') {
            loadTree(currentRow)
        }
        else if (resp.data.power === 'children') {
            loadChildren(currentRow)
        }
    })
}

/**
 * 加载所有下级
 */
function loadTree(currentRow) {
    selectedRow.value = currentRow
    const { tree,listAll,listVal } = allJunior.value
    let valueMap = new Map()
    if (listVal && listVal.length) {
        for(let i=0;i<listVal.length;i++) {
            let val = listVal[i].hierarchy_value;
            let if_fixed = listVal[i].if_fixed;
            if(val==null || val=='' || isNaN(val)) {
                val = 0;
            }
            valueMap.set(listVal[i].user_id, {val:val, if_fixed: if_fixed})
        }
    }
    let node0 = []
    if (tree && tree.length) {
        bigAgentId.value = listAll[0].id;
        node0.push({
            level: 0,
            levelNum: listAll[0].level,
            id: listAll[0].id,
            text: listAll[0].user_code + '(' + listAll[0].id + ')',
            // 大代理的值时默认的，不允许修改
            readonly: true,
            pid: 0,
            val: currentRow.hierarchy_value
        })
    }
    node0[0].children = getTree(tree, valueMap, 0)
    treeNodes.value = node0
    valueMap.clear()
}

function getTree(tree, valueMap, level) {
    if (!tree) {
        return []
    }
    let nodes = []
    const { noChangeUserMap } = allJunior.value
    for(let i=0;i<tree.length;i++) {
        let readonly = false
        if(noChangeUserMap!=null && !isEmpty(noChangeUserMap[tree[i].id])) {
            readonly = true
        }
        let val = 0;
        let if_fixed = 0;
        if (valueMap && valueMap.get(tree[i].id)) {
            val = valueMap.get(tree[i].id).val
            if_fixed = valueMap.get(tree[i].id).if_fixed
        }
        nodes.push({
            readonly: readonly,
            levelNum: tree[i].level,
            id: tree[i].id,
            text: tree[i].user_code + '(' + tree[i].id + ')',
            val: val,
            if_fixed: if_fixed,
            level: level + 1,
            children: getTree(tree[i].child, valueMap, level + 1)
        })
    }
    return nodes;
}

/**
 * 加载直属下级
 */
function loadChildren(currentRow) {
    selectedRow.value = currentRow
    const { listAll, noChangeUserMap } = allJunior.value
    let nodes = []
    for(let i=0;i<listAll.length;i++) {
        let readonly = false
        if(noChangeUserMap!=null && !isEmpty(noChangeUserMap[listAll[i].id])) {
            readonly = true
        }
        let item = listAll[i];
        nodes.push({
            level: 0,
            readonly: readonly,
            id: item.id,
            text: item.user_code+'('+item.id+')',
            val: returnFloat(item.hierarchy_value),
            children: []
        })
    }
    treeNodes.value = nodes
}

function getData(nodes, result, maxValue) {
    if (nodes && nodes.length) {
        for (var j = 0; j < nodes.length; j++) {
            let i = nodes[j]
            if (!i.readonly) {
                result.push({
                    user_id: i.id,
                    hierarchy_value: i.val
                })
                if (maxValue < i.val) {
                    return false
                }
            }
            if (i.children && i.children.length) {
                if(!getData(i.children, result, i.val)) {
                    return false
                }
            }
        }
    }
    return true
}

function save() {
    let data = {
        rebate_id: selectedRow.value.id
    }
    let tmp = []
    if (!getData(treeNodes.value, tmp, selectedRow.value.hierarchy_value)) {
        return
    }
    data.json = JSON.stringify(tmp)
    saveRebateSet(data).then(resp => {
        window.showTip({
            title: t('common.success.action'),
            status: 'success'
        })
    })
}

/**
 * searchType n=按名字，v=按值
 */
function query() {
    let str = searchValue.value
    if (isEmpty(str)) {
        searchResult.value = null
    } else {
        let tmp = []
        walkTreeData(treeNodes.value, (node, index, parent) => {
            if (searchType.value == 'n') {
                if (node.text.indexOf(str) >= 0) {
                    tmp.push(node)
                }
            } else if (searchType.value == 'v') {
                str = parseFloat(str)
                let ibvalue = node.val
                if(isEmpty(ibvalue)){
                    ibvalue = 0;
                }else{
                    ibvalue = parseFloat(ibvalue);
                }
                if(ibvalue == str) {
                    tmp.push(node)
                }
            }
        }, {
            childrenKey: 'children',
            reverse: false,
            childFirst: false
        })
        searchResult.value = tmp
    }
}

const handleRow = {
    onClick(e) {
        const { rowData } = e
        proxy.$refs.tree.openNodeAndParents(
            rowData
        )
        searchResult.value = null
        nextTick(() => {
            proxy.$refs['refN'+rowData.id].scrollIntoView({ behavior: 'smooth' });
        })
    }
}

loadData()
</script>

<style lang="scss" scoped>
.rebate-setting-pannel {
    width: 100%;
    height: 60vh;
    display: flex;

    .rules {
        height: 100%;
        width: 390px;
        flex-shrink: 0;
        flex-grow: 0;
        
        .rule-item {
            cursor: pointer;
        }
    }

    .hierarchy {
        flex-grow: 1;
        flex-shrink: 0;
    }
}

:deep(.el-table) {
    .icon-cell .cell {
        line-height: unset;
    }

    .current-row {
        color: var(--el-menu-active-color);
    }
}

.tree-node-icon {
    width: 20px;
    height: 20px;
    cursor: pointer;
}

.tree-node {
    margin: 4px 0;
    height: 34px;
    font-size: 18px;
    // margin-left: 40px;
    display: flex;
    align-items: center;

    .level {
        height: 20px;
        width: 20px;
        border-radius: 50%;
        text-align: center;
        line-height: 20px;
        font-size: 14px;
        color: #fff;
        background-color: var(--el-color-primary);
        margin: 0 8px;
        user-select: none;
    }

    .label {
        height: 34px;
        line-height: 34px;
        user-select: none;
    }
}

.save-btn {
    min-width: 200px;
    font-size: 18px;
}

</style>

<style lang="scss" >
.t-input-error {
	border: 1px solid red;
    .is-focus {
        --el-input-focus-border-color: red !important;
    }
}

.diff {
    padding-left: 8px;
    font-size: 14px;
}

.error-diff {
    color: red;
}
</style>