/**
 * 树型组件编辑：新增、修改、删除，根据名称过滤节点操作
 * @param {*} dlgId 对话框随机id,防止id冲突与数据集id统一命名引用
 * @param {*} dsId 绑定过滤数据集ID
 * @param {*} option 扩展选项
 * @returns 
 */
 import { $CONST } from "@birt/funclib/ConstUtil";
 import { JsonUtil } from "@birt/funclib/JsonUtil"
 import pinyin from "js-pinyin";
 
export function treeEditFilter(dlgId, dsId, option) {
    let filterField = option.hcTree.labelField;
    let lazy = option.hcTree.lazy;
    let fireAction = lazy ? "" : "keyup";
    let filterSign = lazy ? "like" : "pinyin";
    let treeId = "HcTree_" + dlgId;
    // 过滤编辑器
    let inputFilter = {
        controlName: "HcInputFilter",
        controlId: "HcInputFilter_" + dlgId,
        size: "small",
        fireAction: fireAction,
        events: {
            filterChange: function (filterKey) {
                
                this.getRefCompt(treeId).filter(
                    filterKey
                  );
                // if (filterKey) {
                //     ds.addFilterCdion({
                //         sign: "pinyin",
                //         name: filterField,
                //         dataType: "string",
                //         value: filterKey,
                //         enable: true,
                //     });
                //     // this.getRefCompt(treeId).filter(
                //     //     filterKey
                //     //   );
                // } else {
                //     ds.removeFilterCdion(filterField);
                // }
            },
        }
    };

    // 添加
    let btnAddMenuId = "HcLookup_" + dlgId;
    let HcDropdownId = "HcDropdown_" + dlgId;
    let buttonAddMenu = {
        controlName: "HcLookup",
        controlId: btnAddMenuId,
        dataset: dsId,
        lookDialog: {
            footer: ["cancel", "save"],
            events: {
                saved:function() {
                    var command = this.getWorkBook().param.command
                    var dataset = this.getContent().dataset
                    var data = getFisrt(dataset).getData()
                    var _this = this.getWorkBook().dataset[dsId]
                    var vm = this
                    setDatas(_this, vm, command,data)
                },
              },
        },
        children: [{
            controlName: "HcDropdown",
            controlId: HcDropdownId,
            style: "float:left;width:90p;",
            vshow: false,
            events: {
                command: function (command) {
                    this.getWorkBook().param.command = command
                    let treeMenu = this.getRefCompt(treeId);
                    let currentRow = treeMenu.elTree().getCurrentNode();
                    if (!currentRow) {
                        this.$message({
                            message: '请选择树节点要添加的位置',
                            type: 'warning'
                        });
                        return;
                    }
                    // 获取树当前选中记录，特殊处理虚拟根节点情况
                    let curtRecd;
                    if (command == $CONST.BROTHER && currentRow._isVirtualRoot) {
                        curtRecd = currentRow.children[currentRow.children.length - 1];
                    } else {
                        curtRecd = currentRow;
                    }
                    
                    let btnAddMenu = this.getRefCompt(btnAddMenuId);
                    let pushRecd = btnAddMenu.getPushAddMapRecds(curtRecd);
                    let pushParam = {
                        pushType: "add",
                        command: command,
                        dataset: btnAddMenu.lookDataset.dataset,
                        data: [pushRecd]
                    };
                    btnAddMenu.openLookDialog({ __push: pushParam })
                },
            },
            children: [
                {
                    controlName: "HcButton",
                    controlId: "HcButton_02",
                    size: "mini",
                    title: "添加",
                    children: [
                        {
                            controlName: "HcIcon",
                            controlId: "HcIcon_02_1",
                            slot: "prev",
                            className: "el-icon-plus el-icon--left",
                        },
                        {
                            controlName: "HcIcon",
                            controlId: "HcIcon_02_2",
                            className: "el-icon-arrow-down el-icon--right",
                        },
                    ],
                },
                {
                    controlName: "HcDropdownMenu",
                    controlId: "HcDropdownMenu_02",
                    slot: "dropdown",
                    children: [
                        {
                            controlName: "HcDropdownItem",
                            controlId: "HcDropdownItem_02_1",
                            command: $CONST.BROTHER,
                            title: "同    级",
                            style: "width:80px;"
                        },
                        {
                            controlName: "HcDropdownItem",
                            controlId: "HcDropdownItem_02_2",
                            command: $CONST.CHILD,
                            title: "子    级",
                        },
                    ],
                },
            ],
        }]
    }
    function add(node,data,_this, type){
       _this.getWorkBook().param.node = node
       _this.getWorkBook().param.treeData = data
        if(data.fresguid && type =='child' && !(data.frestype == 'dir' || data.fresguid == '-1')){
                _this.$message({
                    message: '非目录节点不能新增子节点',
                    type: 'warning'
                  });
                return
        }
        if(type =='child'){
            node.loaded = false
            node.expand()
        }
        _this.getWorkBook().param.command = type
        let btnAddMenu = _this.getRefCompt(btnAddMenuId);
        var pushRecd = data;
        var pushParam = {
            pushType: "add",
            command: type,
            dataset: btnAddMenu.lookDataset.dataset,
            data: [pushRecd]
        };
        btnAddMenu.openLookDialog({ __push: pushParam })
    }
    // 修改
    let btnEditId = "HcLookup_edit_" + dlgId;
    let buttonEdit = {
        controlName: "HcLookup",
        controlId: btnEditId,
        dataset: dsId,
        lookDialog: {
            footer: ["cancel", "save"],
            events: {
                saved:function() {
                    debugger
                    var _this = this.getWorkBook().dataset[dsId]
                    var dataset = this.getContent().dataset
                    var data = getFisrt(dataset).getData()
                    var vm = this
                    setDatas(_this, vm, 'edit',data)
                },
            },
        },
        children: [
            {
                controlName: "HcButton",
                title: "修改",
                icon: "el-icon-edit",
                size: "mini",
                style: "float:left;margin-left:5px;width:80px;",
                vshow: false,
                events: {
                    click: function () {
                        let treeMenu = this.getRefCompt(treeId);
                        let currentRow = treeMenu.elTree().getCurrentNode();
                        if (!currentRow || currentRow._isVirtualRoot) {
                            this.$message({
                                message: '请选择要修改的节点',
                                type: 'warning'
                            });
                            return;
                        }

                        let btnEdit = this.getRefCompt(btnEditId);
                        let pushRecd = btnEdit.getPushAddMapRecds(currentRow);
                        let pushParam = {
                            pushType: "edit",
                            dataset: btnEdit.lookDataset.dataset,
                            data: [pushRecd]
                        };
                        btnEdit.openLookDialog({ __push: pushParam })
                    },
                },
            }
        ]
    }
    function edit(node,data,store,_this){
       _this.getWorkBook().param.node = node
       _this.getWorkBook().param.treeData = data
        let btnEdit = _this.getRefCompt(btnEditId);
        var pushRecd = data;
        var pushParam = {
            pushType: "edit",
            dataset: btnEdit.lookDataset.dataset,
            data: [pushRecd]
        };
        btnEdit.openLookDialog({ __push: pushParam })
    }
    // 删除
    let btnDeleteId = "HcLookup_delete_" + dlgId;
    let buttonDelete = {
        controlName: "HcLookup",
        controlId: btnDeleteId,
        dataset: dsId,
        lookDialog: {
            footer: ["cancel", "delete"],
            events: {
                deleted:function() {
                    var _this = this.getWorkBook().dataset[dsId]
                    var vm = this
                    setDatas(_this, vm, 'delete')
                },
               //  confirm(){
               //      var _this = this.getWorkBook().dataset[dsId],
               //      curData = _this.getCurtRecord(),
               //      vm = this,
               //      data = {},
               //      url = ''
               //      if(curData.FROLEGUID){
               //          data = {
               //              FROLEGUID: curData.FROLEGUID
               //          }
               //          url = '/sys/role/delete?pn=' + pn
               //      }else if(curData.FORGGUID){
               //          data = {
               //              FORGGUID: curData.FORGGUID
               //          }
               //          url = '/sys/org/delete?pn=' + pn
               //      }else if(curData.FRESGUID){
               //          data = {
               //              FRESGUID: curData.FRESGUID
               //          }
               //          url = '/sys/menu/delete?pn=' + pn
               //      }
               //      delTree(data,url).then((res) =>{
               //          console.log('删除', res)
               //          if(res.status == 200){
               //              Message.success('删除成功')
               //              setDatas(_this, vm, 'delete')
               //          }else{
               //              Message.error(res.msg)
               //          }
               //      })
                    
               //  }
              },
        },
        children: [
            {
                controlName: "HcButton",
                title: "删除",
                icon: "el-icon-delete",
                size: "mini",
                style: "float:left;margin-left:5px;width:80px;",
                vshow: false,
                events: {
                    click: function () {
                        debugger
                        let treeMenu = this.getRefCompt(treeId);
                        let currentRow = treeMenu.elTree().getCurrentNode();
                        if (!currentRow || currentRow._isVirtualRoot) {
                            this.$message({
                                message: '请选择要删除的节点',
                                type: 'warning'
                            });
                            return;
                        }
                        let btnDelete = this.getRefCompt(btnDeleteId);
                        let pushRecd = btnDelete.getPushAddMapRecds(currentRow);
                        let pushParam = {
                            pushType: "delete",
                            dataset: btnDelete.lookDataset.dataset,
                            // data: [pushRecd]
                        };
                        Object.assign(pushParam,pushRecd);
                        btnDelete.openLookDialog({ __push: pushParam })
                    },
                },
            }
        ]
    }
    function remove(node,data,store,_this){
        debugger
        let wb = _this.getWorkBook();
        wb.param.node = node
        wb.param.treeData = data
        let btnDelete = _this.getRefCompt(btnDeleteId);
        var pushRecd = data;
        var pushParam = {
            pushType: "delete",
            dataset: btnDelete.lookDataset.dataset,
            data: [pushRecd]
        };
        Object.assign(pushParam,pushRecd);
        btnDelete.openLookDialog({ __push: pushParam })
    }
    function getFisrt(obj){
       var n=0;
       for(var key in obj){
           return obj[key]
       }
    }
    // 应用树个性化配置
    JsonUtil.deepMerge(buttonAddMenu, option.hcLookupAdd);
    JsonUtil.deepMerge(buttonEdit, option.hcLookupEdit);
    JsonUtil.deepMerge(buttonDelete, option.hcLookupDelete);
    JsonUtil.deepMerge(buttonAddMenu, option.hcLookup);
    JsonUtil.deepMerge(buttonEdit, option.hcLookup);
    JsonUtil.deepMerge(buttonDelete, option.hcLookup);
    // 转换tree数据
    function arrayToJson(data,id,pid) {
        let result = []
        if(!Array.isArray(data)) {
            return result
        }
        let map = {};
        data.forEach(item => {
            map[item[id]] = item;
        });
        data.forEach(item => {
            let parent = map[item[pid]];
            if(parent) {
                (parent.children || (parent.children = [])).push(item);
            } else {
                result.push(item);
            }
        });
        return result;
    }
    //  查询数据集，set数据
    function  setDatas(_this, vm, type,data){
        debugger
       let treeData = vm.getWorkBook().param.treeData
       let node = vm.getWorkBook().param.node
       var tree = vm.getRefCompt(treeId)
       if(type == 'edit'){
           node.data = data[0]
           _this.setCurtRecord(data[0]);
       }else if (type == 'delete'){
           const parent = node.parent.childNodes;
           const index = parent.findIndex(d => d.key === node.key);
           parent.splice(index, 1);
           _this.setCurtRecord(node.parent.data);
       }else{
           const newChild =  data[0];
           if (!treeData.children) {
               vm.$set(treeData, 'children', []);
           }
           treeData.children.push(newChild);
           _this.setCurtRecord(newChild);
       }
    }
    // 编辑树型按钮工具条
    let treeEditToolbar = {
        controlName: "HcRow",
        style: "margin-top:5px;",
        children: [
            buttonAddMenu,
            buttonEdit,
            buttonDelete,
        ]
    }
    // 编辑树组件
    let hcTree = {
        controlName: "HcTree",
        controlId: treeId,
        dataset: dsId,
        labelField: filterField,
        // defaultExpandAll: true,
        // accordion: true,
        highlightCurrent: true,
        expandOnClickNode: false,
        lazy: false,
        filterNodeMethod:function(value, data,node) {
            if (!value){
                return true
            }else{
                // let res = variableDeepSearch(data.children, value.trim(),filterField) // res是过滤后得到的数据
                let key =node.label +"_" + pinyin.getCamelChars(node.label);
                return key.indexOf(value.toUpperCase()) !== -1;
            }
        },
        height: function (parentHeight) {
            return parentHeight - 80;
        },
        renderContent(h, { node, data, store}) {
            var _this = this
            var iconClass = ''
            var title = ''
            var disabled = false
           //  if(node.isLeaf){
           //     iconClass = 'el-icon-document'
           //  }else{
           //     if(node.expanded){
           //         iconClass = 'el-icon-folder-opened'
           //      }else{
           //         iconClass = 'el-icon-folder'
           //      }
           //  }
           if(data.FROLEKIND || data.FROLEGUID){
               if( data.FROLEKIND?.toLocaleLowerCase() == 'root' || data.FROLEGUID == '-1'){
                   iconClass = 'iconfont icon-root'
                   title = '根节点'
                   disabled = true
               }else if( data.FROLEKIND.toLocaleLowerCase() == 'dir'){
                   iconClass = 'el-icon-folder'
                   title = '文件夹'
               }else{
                   iconClass = 'iconfont icon-ptm'
                   title = '岗位'
               }
           }else if(data.FRESTYPE || data.FRESGUID){
               if(data.FRESTYPE?.toLocaleLowerCase() == 'root' || data.FRESGUID == '-1'){
                   iconClass = 'iconfont icon-root'
                   title = '根节点'
                   disabled = true
               }else if(data.FRESTYPE.toLocaleLowerCase() == 'dir'){
                   iconClass = 'el-icon-folder'
                   title = '文件夹'
               }else if(data.FRESTYPE.toLocaleLowerCase() == 'func'){
                   iconClass = 'iconfont icon-func'
                   title = '功能'
               }else if(data.FRESTYPE.toLocaleLowerCase() == 'flow'){
                   iconClass = 'iconfont icon-flow'
                   title = '流程'
               }
           }else if(data.FLEVELKIND || data.FLEVELGUID){
               if( data.FLEVELKIND?.toLocaleLowerCase() == 'root' || data.FLEVELGUID == '-1'){
                   iconClass = 'iconfont icon-root'
                   title = '根节点'
                   disabled = true
               }else{
                   iconClass = 'iconfont icon-ptm'
                   title = '职级'
               }
           }else {
               iconClass = 'el-icon-document'
           }
            return (
              <span class="custom-tree-node">
                <span title={title}>
                   <i class={iconClass}></i>
                   {node.label}
                </span>
                <span class="btn">
                  <el-button size="large" title="新增同级" type="text" disabled={disabled} icon="el-icon-folder-add" on-click={ () => add(node,data,_this, 'brother') }></el-button>
                  <el-button size="large" title="新增子级" type="text" icon="el-icon-circle-plus-outline" on-click={ () => add(node,data,_this,'child') }></el-button>
                  <el-button size="large" title="编辑" type="text" icon="el-icon-edit" on-click={ () => edit(node,data,store,_this) }></el-button>
                  <el-button size="large" title="删除" type="text" icon="el-icon-delete" on-click={ () => remove(node,data,store,_this) }></el-button>
                </span>
              </span>);
          },
        style: "overflow: auto;border:1px solid rgb(235, 238, 245);margin-top: 5px;",
    };
    // 应用树个性化配置
    Object.assign(hcTree, option.hcTree);

    // 返回布局结构
    return {
        controlName: "HcCol",
        span: 6,
        children: [
            inputFilter,
            treeEditToolbar,
            hcTree
        ]
    }
}